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
./partial_match/1313161554/0x964630b8327A6EB8730e3addcB8563d1e61b0100/sources/Comptroller.sol
* @notice Return address profit controller @return profitController/
function getProfitController() public view returns(address) { return profitController; }
16,919,469
[ 1, 990, 1758, 450, 7216, 2596, 327, 450, 7216, 2933, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3570, 7216, 2933, 1435, 1071, 1476, 1135, 12, 2867, 13, 288, 203, 3639, 327, 450, 7216, 2933, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0xB925899Df589e10c71F540eA92F5fC7b98552AAb/sources/src/tokens/SafeERC4626Upgradeable.sol
* Constructor for the SafeERC4626Upgradeable contract @param _asset which will be stored in this Vault @dev `defaultOperators` may be an empty array./
) internal onlyInitializing { __ERC4626_init(_asset, name_, symbol_, defaultOperators_); }
3,820,454
[ 1, 6293, 364, 326, 14060, 654, 39, 8749, 5558, 10784, 429, 6835, 225, 389, 9406, 1492, 903, 506, 4041, 316, 333, 17329, 225, 1375, 1886, 24473, 68, 2026, 506, 392, 1008, 526, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 2713, 1338, 29782, 288, 203, 3639, 1001, 654, 39, 8749, 5558, 67, 2738, 24899, 9406, 16, 508, 67, 16, 3273, 67, 16, 805, 24473, 67, 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 ]
./full_match/80001/0x2707e98272b558d1a9d5BBa8feE22e6e22389cB3/sources/contracts/ERC721.sol
Same Account Purchase Not Allowed
require(msg.sender != _ownerOf(iToken), "Not Allowed");
9,473,492
[ 1, 8650, 6590, 26552, 2288, 16740, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 2583, 12, 3576, 18, 15330, 480, 389, 8443, 951, 12, 77, 1345, 3631, 315, 1248, 16740, 8863, 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 ]
pragma solidity ^0.4.18; interface ConflictResolutionInterface { function minHouseStake(uint activeGames) public pure returns(uint); function maxBalance() public pure returns(int); function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) public pure returns(bool); function endGameConflict( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, bytes32 _serverSeed, bytes32 _playerSeed ) public view returns(int); function serverForceGameEnd( uint8 gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view returns(int); function playerForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view returns(int); } contract ConflictResolution is ConflictResolutionInterface { uint public constant DICE_RANGE = 100; uint public constant HOUSE_EDGE = 150; uint public constant HOUSE_EDGE_DIVISOR = 10000; uint public constant SERVER_TIMEOUT = 6 hours; uint public constant PLAYER_TIMEOUT = 6 hours; uint8 public constant DICE_LOWER = 1; ///< @dev dice game lower number wins uint8 public constant DICE_HIGHER = 2; ///< @dev dice game higher number wins uint public constant MAX_BET_VALUE = 2e16; /// max 0.02 ether bet uint public constant MIN_BET_VALUE = 1e13; /// min 0.00001 ether bet int public constant NOT_ENDED_FINE = 1e15; /// 0.001 ether int public constant MAX_BALANCE = int(MAX_BET_VALUE) * 100 * 5; modifier onlyValidBet(uint8 _gameType, uint _betNum, uint _betValue) { require(isValidBet(_gameType, _betNum, _betValue)); _; } modifier onlyValidBalance(int _balance, uint _gameStake) { // safe to cast gameStake as range is fixed require(-int(_gameStake) <= _balance && _balance < MAX_BALANCE); _; } /** * @dev Check if bet is valid. * @param _gameType Game type. * @param _betNum Number of bet. * @param _betValue Value of bet. * @return True if bet is valid false otherwise. */ function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) public pure returns(bool) { bool validValue = MIN_BET_VALUE <= _betValue && _betValue <= MAX_BET_VALUE; bool validGame = false; if (_gameType == DICE_LOWER) { validGame = _betNum > 0 && _betNum < DICE_RANGE - 1; } else if (_gameType == DICE_HIGHER) { validGame = _betNum > 0 && _betNum < DICE_RANGE - 1; } else { validGame = false; } return validValue && validGame; } /** * @return Max balance. */ function maxBalance() public pure returns(int) { return MAX_BALANCE; } /** * Calculate minimum needed house stake. */ function minHouseStake(uint activeGames) public pure returns(uint) { return MathUtil.min(activeGames, 1) * MAX_BET_VALUE * 400; } /** * @dev Calculates game result and returns new balance. * @param _gameType Type of game. * @param _betNum Bet number. * @param _betValue Value of bet. * @param _balance Current balance. * @param _serverSeed Server's seed of current round. * @param _playerSeed Player's seed of current round. * @return New game session balance. */ function endGameConflict( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, bytes32 _serverSeed, bytes32 _playerSeed ) public view onlyValidBet(_gameType, _betNum, _betValue) onlyValidBalance(_balance, _stake) returns(int) { assert(_serverSeed != 0 && _playerSeed != 0); int newBalance = processBet(_gameType, _betNum, _betValue, _balance, _serverSeed, _playerSeed); // do not allow balance below player stake int stake = int(_stake); // safe to cast as stake range is fixed if (newBalance < -stake) { newBalance = -stake; } return newBalance; } /** * @dev Force end of game if player does not respond. Only possible after a time period. * to give the player a chance to respond. * @param _gameType Game type. * @param _betNum Bet number. * @param _betValue Bet value. * @param _balance Current balance. * @param _stake Player stake. * @param _endInitiatedTime Time server initiated end. * @return New game session balance. */ function serverForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view onlyValidBalance(_balance, _stake) returns(int) { require(_endInitiatedTime + SERVER_TIMEOUT <= block.timestamp); require(isValidBet(_gameType, _betNum, _betValue) || (_gameType == 0 && _betNum == 0 && _betValue == 0 && _balance == 0)); // following casts and calculations are safe as ranges are fixed // assume player has lost int newBalance = _balance - int(_betValue); // penalize player as he didn't end game newBalance -= NOT_ENDED_FINE; // do not allow balance below player stake int stake = int(_stake); // safe to cast as stake range is fixed if (newBalance < -stake) { newBalance = -stake; } return newBalance; } /** * @dev Force end of game if server does not respond. Only possible after a time period * to give the server a chance to respond. * @param _gameType Game type. * @param _betNum Bet number. * @param _betValue Value of bet. * @param _balance Current balance. * @param _endInitiatedTime Time server initiated end. * @return New game session balance. */ function playerForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view onlyValidBalance(_balance, _stake) returns(int) { require(_endInitiatedTime + PLAYER_TIMEOUT <= block.timestamp); require(isValidBet(_gameType, _betNum, _betValue) || (_gameType == 0 && _betNum == 0 && _betValue == 0 && _balance == 0)); int profit = 0; if (_gameType == 0 && _betNum == 0 && _betValue == 0 && _balance == 0) { // player cancelled game without playing profit = 0; } else { profit = int(calculateProfit(_gameType, _betNum, _betValue)); // safe to cast as ranges are limited } // penalize server as it didn't end game profit += NOT_ENDED_FINE; return _balance + profit; } /** * @dev Calculate new balance after executing bet. * @param _gameType game type. * @param _betNum Bet Number. * @param _betValue Value of bet. * @param _balance Current balance. * @param _serverSeed Server's seed * @param _playerSeed Player's seed * return new balance. */ function processBet( uint8 _gameType, uint _betNum, uint _betValue, int _balance, bytes32 _serverSeed, bytes32 _playerSeed ) private pure returns (int) { bool won = hasPlayerWon(_gameType, _betNum, _serverSeed, _playerSeed); if (!won) { return _balance - int(_betValue); // safe to cast as ranges are fixed } else { int profit = calculateProfit(_gameType, _betNum, _betValue); return _balance + profit; } } /** * @dev Calculate player profit. * @param _gameType type of game. * @param _betNum bet numbe. * @param _betValue bet value. * return profit of player */ function calculateProfit(uint8 _gameType, uint _betNum, uint _betValue) private pure returns(int) { uint betValueInGwei = _betValue / 1e9; // convert to gwei int res = 0; if (_gameType == DICE_LOWER) { res = calculateProfitGameType1(_betNum, betValueInGwei); } else if (_gameType == DICE_HIGHER) { res = calculateProfitGameType2(_betNum, betValueInGwei); } else { assert(false); } return res * 1e9; // convert to wei } /** * Calculate player profit from total won. * @param _totalWon player winning in gwei. * @return player profit in gwei. */ function calcProfitFromTotalWon(uint _totalWon, uint _betValue) private pure returns(int) { // safe to multiply as _totalWon range is fixed. uint houseEdgeValue = _totalWon * HOUSE_EDGE / HOUSE_EDGE_DIVISOR; // safe to cast as all value ranges are fixed return int(_totalWon) - int(houseEdgeValue) - int(_betValue); } /** * @dev Calculate player profit if player has won for game type 1 (dice lower wins). * @param _betNum Bet number of player. * @param _betValue Value of bet in gwei. * @return Players' profit. */ function calculateProfitGameType1(uint _betNum, uint _betValue) private pure returns(int) { assert(_betNum > 0 && _betNum < DICE_RANGE); // safe as ranges are fixed uint totalWon = _betValue * DICE_RANGE / _betNum; return calcProfitFromTotalWon(totalWon, _betValue); } /** * @dev Calculate player profit if player has won for game type 2 (dice lower wins). * @param _betNum Bet number of player. * @param _betValue Value of bet in gwei. * @return Players' profit. */ function calculateProfitGameType2(uint _betNum, uint _betValue) private pure returns(int) { assert(_betNum >= 0 && _betNum < DICE_RANGE - 1); // safe as ranges are fixed uint totalWon = _betValue * DICE_RANGE / (DICE_RANGE - _betNum - 1); return calcProfitFromTotalWon(totalWon, _betValue); } /** * @dev Check if player hash won or lost. * @return true if player has won. */ function hasPlayerWon( uint8 _gameType, uint _betNum, bytes32 _serverSeed, bytes32 _playerSeed ) private pure returns(bool) { bytes32 combinedHash = keccak256(_serverSeed, _playerSeed); uint randNum = uint(combinedHash); if (_gameType == 1) { return calculateWinnerGameType1(randNum, _betNum); } else if (_gameType == 2) { return calculateWinnerGameType2(randNum, _betNum); } else { assert(false); } } /** * @dev Calculate winner of game type 1 (roll lower). * @param _randomNum 256 bit random number. * @param _betNum Bet number. * @return True if player has won false if he lost. */ function calculateWinnerGameType1(uint _randomNum, uint _betNum) private pure returns(bool) { assert(_betNum > 0 && _betNum < DICE_RANGE); uint resultNum = _randomNum % DICE_RANGE; // bias is negligible return resultNum < _betNum; } /** * @dev Calculate winner of game type 2 (roll higher). * @param _randomNum 256 bit random number. * @param _betNum Bet number. * @return True if player has won false if he lost. */ function calculateWinnerGameType2(uint _randomNum, uint _betNum) private pure returns(bool) { assert(_betNum >= 0 && _betNum < DICE_RANGE - 1); uint resultNum = _randomNum % DICE_RANGE; // bias is negligible return resultNum > _betNum; } } library MathUtil { /** * @dev Returns the absolute value of _val. * @param _val value * @return The absolute value of _val. */ function abs(int _val) internal pure returns(uint) { if (_val < 0) { return uint(-_val); } else { return uint(_val); } } /** * @dev Calculate maximum. */ function max(uint _val1, uint _val2) internal pure returns(uint) { return _val1 >= _val2 ? _val1 : _val2; } /** * @dev Calculate minimum. */ function min(uint _val1, uint _val2) internal pure returns(uint) { return _val1 <= _val2 ? _val1 : _val2; } }
* @dev Calculate winner of game type 2 (roll higher). @param _randomNum 256 bit random number. @param _betNum Bet number. @return True if player has won false if he lost./
function calculateWinnerGameType2(uint _randomNum, uint _betNum) private pure returns(bool) { assert(_betNum >= 0 && _betNum < DICE_RANGE - 1); return resultNum > _betNum; }
421,045
[ 1, 8695, 5657, 1224, 434, 7920, 618, 576, 261, 2693, 10478, 2934, 225, 389, 9188, 2578, 8303, 2831, 2744, 1300, 18, 225, 389, 70, 278, 2578, 605, 278, 1300, 18, 327, 1053, 309, 7291, 711, 8462, 629, 309, 3904, 13557, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 59, 7872, 12496, 559, 22, 12, 11890, 389, 9188, 2578, 16, 2254, 389, 70, 278, 2578, 13, 3238, 16618, 1135, 12, 6430, 13, 288, 203, 3639, 1815, 24899, 70, 278, 2578, 1545, 374, 597, 389, 70, 278, 2578, 411, 3690, 1441, 67, 15928, 300, 404, 1769, 203, 203, 3639, 327, 563, 2578, 405, 389, 70, 278, 2578, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x8D2C372317524a8Af5313883434411fd3DAE55d9/sources/contracts/lib/Verifiers.sol
Ensure that the signature for the digest is valid for the offerer.
_assertValidSignature(offerer, digest, signature);
877,949
[ 1, 12512, 716, 326, 3372, 364, 326, 5403, 353, 923, 364, 326, 10067, 264, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 11231, 1556, 5374, 12, 792, 18459, 16, 5403, 16, 3372, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.0; //Inheritance import './interfaces/IStableCoinReserve.sol'; // Libraries import "./libraries/SafeMath.sol"; // Internal references import "./interfaces/IERC20.sol"; import "./interfaces/IAddressResolver.sol"; import "./interfaces/ISettings.sol"; import "./interfaces/IInsuranceFund.sol"; import "./interfaces/IInterestRewardsPoolEscrow.sol"; import "./interfaces/IStakingRewards.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./interfaces/IBaseUbeswapAdapter.sol"; contract StableCoinReserve is IStableCoinReserve { using SafeMath for uint; IAddressResolver public immutable ADDRESS_RESOLVER; constructor(IAddressResolver _addressResolver) public { ADDRESS_RESOLVER = _addressResolver; } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @notice Swaps cUSD for specified asset; meant to be called from an LToken contract * @param asset Asset to swap to * @param collateral Amount of cUSD to transfer from user * @param borrowedAmount Amount of cUSD borrowed * @param user Address of the user * @return uint Number of asset tokens received */ function swapToAsset(address asset, uint collateral, uint borrowedAmount, address user) public override onlyLToken returns (uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); //Remove collateral from user IERC20(stableCoinAddress).transferFrom(user, address(this), collateral); require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(asset), "StableCoinReserve: currency not available"); require(IERC20(asset).balanceOf(address(this)) >= collateral.add(borrowedAmount), "StableCoinReserve: not enough cUSD available to swap"); uint numberOfDecimals = IERC20(asset).decimals(); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(asset); uint numberOfTokens = (collateral.add(borrowedAmount)).div(tokenToUSD).div(10 ** numberOfDecimals); //Swap cUSD for asset IERC20(stableCoinAddress).transfer(baseUbeswapAdapterAddress, collateral.add(borrowedAmount)); uint numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(stableCoinAddress, asset, collateral.add(borrowedAmount), numberOfTokens); return numberOfTokensReceived; } /** * @notice Swaps specified asset for cUSD; meant to be called from an LToken contract * @param asset Asset to swap from * @param userShare User's ratio of received tokens * @param poolShare Pool's ratio of received tokens * @param numberOfAssetTokens Number of asset tokens to swap * @param user Address of the user * @return uint Amount of cUSD user received */ function swapFromAsset(address asset, uint userShare, uint poolShare, uint numberOfAssetTokens, address user) public override onlyLToken returns (uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address insuranceFundAddress = ADDRESS_RESOLVER.getContractAddress("InsuranceFund"); address baseTradegenAddress = ADDRESS_RESOLVER.getContractAddress("BaseTradegen"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(asset), "StableCoinReserve: currency not available"); //Get price of asset uint numberOfDecimals = IERC20(asset).decimals(); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(asset); uint amountInUSD = (numberOfAssetTokens).mul(tokenToUSD).div(10 ** numberOfDecimals); //Swap asset for cUSD IERC20(asset).transfer(baseUbeswapAdapterAddress, numberOfAssetTokens); uint cUSDReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(asset, stableCoinAddress, numberOfAssetTokens, amountInUSD); //Transfer pool share to insurance fund if this contract's cUSD balance > totalVestedBalance (surplus if a withdrawal was made from insurance fund) //Swap cUSD for TGEN if insurance fund's TGEN reserves are low uint poolUSDAmount = cUSDReceived.mul(poolShare).div(userShare.add(poolShare)); uint surplus = (IERC20(stableCoinAddress).balanceOf(address(this)) > totalVestedBalance) ? poolUSDAmount.sub(IERC20(stableCoinAddress).balanceOf(address(this))) : 0; if (IInsuranceFund(insuranceFundAddress).getFundStatus() < 2) { //Swap cUSD for TGEN and transfer to insurance fund IERC20(stableCoinAddress).transfer(baseUbeswapAdapterAddress, surplus); uint numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(stableCoinAddress, asset, surplus, 0); IERC20(baseTradegenAddress).transfer(insuranceFundAddress, numberOfTokensReceived); } //Transfer cUSD to user uint userUSDAmount = cUSDReceived.mul(userShare).div(userShare.add(poolShare)); IERC20(stableCoinAddress).transfer(user, userUSDAmount); return userUSDAmount; } /** * @notice Liquidates a leveraged asset; meant to be called from LeveragedAssetPositionManager contract * @param asset Asset to swap from * @param userShare User's ratio of received tokens * @param liquidatorShare Liquidator's ratio of received tokens * @param poolShare Pool's ration of received tokens * @param numberOfAssetTokens Number of asset tokens to swap * @param user Address of the user * @param liquidator Address of the liquidator * @return uint Amount of cUSD user received */ function liquidateLeveragedAsset(address asset, uint userShare, uint liquidatorShare, uint poolShare, uint numberOfAssetTokens, address user, address liquidator) public override onlyLToken returns (uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address insuranceFundAddress = ADDRESS_RESOLVER.getContractAddress("InsuranceFund"); address baseTradegenAddress = ADDRESS_RESOLVER.getContractAddress("BaseTradegen"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(asset), "StableCoinStakingRewards: currency not available"); //Get price of asset uint numberOfDecimals = IERC20(asset).decimals(); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(asset); uint amountInUSD = (numberOfAssetTokens).mul(tokenToUSD).div(10 ** numberOfDecimals); //Swap asset for cUSD IERC20(asset).transfer(baseUbeswapAdapterAddress, numberOfAssetTokens); uint cUSDReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(asset, stableCoinAddress, numberOfAssetTokens, amountInUSD); //Transfer pool share to insurance fund if this contract's cUSD balance > totalVestedBalance (surplus if a withdrawal was made from insurance fund) //Swap cUSD for TGEN if insurance fund's TGEN reserves are low uint poolUSDAmount = cUSDReceived.mul(poolShare).div(userShare.add(poolShare).add(liquidatorShare)); uint surplus = (IERC20(stableCoinAddress).balanceOf(address(this)) > totalVestedBalance) ? poolUSDAmount.sub(IERC20(stableCoinAddress).balanceOf(address(this))) : 0; if (IInsuranceFund(insuranceFundAddress).getFundStatus() < 2) { //Swap cUSD for TGEN and transfer to insurance fund IERC20(stableCoinAddress).transfer(baseUbeswapAdapterAddress, surplus); uint numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(stableCoinAddress, asset, surplus, 0); IERC20(baseTradegenAddress).transfer(insuranceFundAddress, numberOfTokensReceived); } //Transfer cUSD to user uint userUSDAmount = cUSDReceived.mul(userShare).div(userShare.add(poolShare).add(liquidatorShare)); IERC20(stableCoinAddress).transfer(user, userUSDAmount); //Transfer cUSD to liquidator uint liquidatorUSDAmount = cUSDReceived.mul(liquidatorShare).div(userShare.add(poolShare).add(liquidatorShare)); IERC20(stableCoinAddress).transfer(liquidator, liquidatorUSDAmount); return userUSDAmount; } /** * @notice Pays interest in the given asset; meant to be called from LeveragedAssetPositionManager contract * @param asset Asset to swap from * @param numberOfAssetTokens Number of asset tokens to swap */ function payInterest(address asset, uint numberOfAssetTokens) public override onlyLToken { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address insuranceFundAddress = ADDRESS_RESOLVER.getContractAddress("InsuranceFund"); address interestRewardsPoolEscrowAddress = ADDRESS_RESOLVER.getContractAddress("InterestRewardsPoolEscrow"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(asset), "StableCoinStakingRewards: currency not available"); //Get price of asset uint numberOfDecimals = IERC20(asset).decimals(); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(asset); uint amountInUSD = (numberOfAssetTokens).mul(tokenToUSD).div(10 ** numberOfDecimals); //Swap asset for cUSD IERC20(asset).transfer(baseUbeswapAdapterAddress, numberOfAssetTokens); uint cUSDReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(asset, stableCoinAddress, numberOfAssetTokens, amountInUSD); //Adjust distribution ratio based on status of insurance fund uint insuranceFundAllocation; uint insuranceFundStatus = IInsuranceFund(insuranceFundAddress).getFundStatus(); if (insuranceFundStatus == 0) { insuranceFundAllocation = 100; } else if (insuranceFundStatus == 1) { insuranceFundAllocation = 60; } else if (insuranceFundStatus == 2) { insuranceFundAllocation = 25; } else { insuranceFundAllocation = 0; } //Transfer received cUSD to insurance fund IERC20(stableCoinAddress).transfer(insuranceFundAddress, cUSDReceived.mul(insuranceFundAllocation).div(100)); //Transfer received cUSD to interest rewards pool IERC20(stableCoinAddress).transfer(interestRewardsPoolEscrowAddress, cUSDReceived.mul(100 - insuranceFundAllocation).div(100)); } /** * @notice Claims user's UBE rewards for leveraged yield farming * @param user Address of the user * @param amountOfUBE Amount of UBE to transfer to user */ function claimUserUBE(address user, uint amountOfUBE) public override onlyLToken { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE"); require(IERC20(UBE).balanceOf(address(this)) >= amountOfUBE, "StableCoinStakingRewards: not enough UBE in contract"); IERC20(UBE).transfer(user, amountOfUBE); } /** * @notice Claims farm's UBE rewards for leveraged yield farming * @notice Sends a small percentage of claimed UBE to user as a reward * @param user Address of the user * @param farmAddress Address of the farm * @return (uint, uint) Amount of UBE claimed and keeper's share */ function claimFarmUBE(address user, address farmAddress) public override onlyLToken returns (uint, uint) { address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE"); uint keeperReward = ISettings(settingsAddress).getParameterValue("UBEKeeperReward"); uint initialBalance = IERC20(UBE).balanceOf(address(this)); require(IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress) != address(0), "StableCoinStakingRewards: invalid farm address"); //Claim farm's available UBE IStakingRewards(farmAddress).getReward(); //Transfer keeper reward to user uint claimedUBE = IERC20(UBE).balanceOf(address(this)).sub(initialBalance); IERC20(UBE).transfer(user, claimedUBE.mul(keeperReward).div(1000)); return (claimedUBE, claimedUBE.mul(keeperReward).div(1000)); } /** * @dev Adds liquidity for the two given tokens * @param tokenA First token in pair * @param tokenB Second token in pair * @param amountA Amount of first token * @param amountB Amount of second token * @param farmAddress The token pair's farm address on Ubeswap * @return Number of LP tokens received */ function addLiquidity(address tokenA, address tokenB, uint amountA, uint amountB, address farmAddress) public override onlyLToken returns (uint) { require(tokenA != address(0), "StableCoinStakingRewards: invalid address for tokenA"); require(tokenB != address(0), "StableCoinStakingRewards: invalid address for tokenB"); require(amountA > 0, "StableCoinStakingRewards: amountA must be greater than 0"); require(amountB > 0, "StableCoinStakingRewards: amountB must be greater than 0"); require(IERC20(tokenA).balanceOf(address(this)) >= amountA, "StableCoinStakingRewards: not enough tokens invested in tokenA"); require(IERC20(tokenB).balanceOf(address(this)) >= amountB, "StableCoinStakingRewards: not enough tokens invested in tokenB"); //Check if farm exists for the token pair address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stakingTokenAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress); address pairAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPair(tokenA, tokenB); require(stakingTokenAddress == pairAddress, "StableCoinStakingRewards: stakingTokenAddress does not match pairAddress"); //Add liquidity to Ubeswap pool and stake LP tokens into associated farm uint numberOfLPTokens = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).addLiquidity(tokenA, tokenB, amountA, amountB); IStakingRewards(stakingTokenAddress).stake(numberOfLPTokens); return numberOfLPTokens; } /** * @dev Removes liquidity for the two given tokens * @param pair Address of liquidity pair * @param farmAddress The token pair's farm address on Ubeswap * @param numberOfLPTokens Number of LP tokens to remove * @return (uint, uint) Amount of pair's token0 and token1 received */ function removeLiquidity(address pair, address farmAddress, uint numberOfLPTokens) public override onlyLToken returns (uint, uint) { //Check if farm exists for the token pair address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stakingTokenAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress); require(stakingTokenAddress == pair, "StableCoinStakingRewards: stakingTokenAddress does not match pair address"); //Withdraw LP tokens from farm IStakingRewards(farmAddress).withdraw(numberOfLPTokens); //Remove liquidity from Ubeswap liquidity pool return IBaseUbeswapAdapter(baseUbeswapAdapterAddress).removeLiquidity(IUniswapV2Pair(pair).token0(), IUniswapV2Pair(pair).token1(), numberOfLPTokens); } /* ========== MODIFIERS ========== */ //TODO: modifier onlyLToken() { require(msg.sender == ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"), "StableCoinReserve: Only an LToken contract can call this function"); _; } }
* @dev Adds liquidity for the two given tokens @param tokenA First token in pair @param tokenB Second token in pair @param amountA Amount of first token @param amountB Amount of second token @param farmAddress The token pair's farm address on Ubeswap @return Number of LP tokens received/Check if farm exists for the token pairAdd liquidity to Ubeswap pool and stake LP tokens into associated farm
function addLiquidity(address tokenA, address tokenB, uint amountA, uint amountB, address farmAddress) public override onlyLToken returns (uint) { require(tokenA != address(0), "StableCoinStakingRewards: invalid address for tokenA"); require(tokenB != address(0), "StableCoinStakingRewards: invalid address for tokenB"); require(amountA > 0, "StableCoinStakingRewards: amountA must be greater than 0"); require(amountB > 0, "StableCoinStakingRewards: amountB must be greater than 0"); require(IERC20(tokenA).balanceOf(address(this)) >= amountA, "StableCoinStakingRewards: not enough tokens invested in tokenA"); require(IERC20(tokenB).balanceOf(address(this)) >= amountB, "StableCoinStakingRewards: not enough tokens invested in tokenB"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stakingTokenAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress); address pairAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPair(tokenA, tokenB); require(stakingTokenAddress == pairAddress, "StableCoinStakingRewards: stakingTokenAddress does not match pairAddress"); uint numberOfLPTokens = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).addLiquidity(tokenA, tokenB, amountA, amountB); IStakingRewards(stakingTokenAddress).stake(numberOfLPTokens); return numberOfLPTokens; }
13,077,561
[ 1, 3655, 4501, 372, 24237, 364, 326, 2795, 864, 2430, 225, 1147, 37, 5783, 1147, 316, 3082, 225, 1147, 38, 7631, 1147, 316, 3082, 225, 3844, 37, 16811, 434, 1122, 1147, 225, 3844, 38, 16811, 434, 2205, 1147, 225, 284, 4610, 1887, 1021, 1147, 3082, 1807, 284, 4610, 1758, 603, 587, 70, 281, 91, 438, 327, 3588, 434, 511, 52, 2430, 5079, 19, 1564, 309, 284, 4610, 1704, 364, 326, 1147, 3082, 986, 4501, 372, 24237, 358, 587, 70, 281, 91, 438, 2845, 471, 384, 911, 511, 52, 2430, 1368, 3627, 284, 4610, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 48, 18988, 24237, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 16, 2254, 3844, 37, 16, 2254, 3844, 38, 16, 1758, 284, 4610, 1887, 13, 1071, 3849, 1338, 48, 1345, 1135, 261, 11890, 13, 288, 203, 3639, 2583, 12, 2316, 37, 480, 1758, 12, 20, 3631, 315, 30915, 27055, 510, 6159, 17631, 14727, 30, 2057, 1758, 364, 1147, 37, 8863, 203, 3639, 2583, 12, 2316, 38, 480, 1758, 12, 20, 3631, 315, 30915, 27055, 510, 6159, 17631, 14727, 30, 2057, 1758, 364, 1147, 38, 8863, 203, 3639, 2583, 12, 8949, 37, 405, 374, 16, 315, 30915, 27055, 510, 6159, 17631, 14727, 30, 3844, 37, 1297, 506, 6802, 2353, 374, 8863, 203, 3639, 2583, 12, 8949, 38, 405, 374, 16, 315, 30915, 27055, 510, 6159, 17631, 14727, 30, 3844, 38, 1297, 506, 6802, 2353, 374, 8863, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 2316, 37, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 3844, 37, 16, 315, 30915, 27055, 510, 6159, 17631, 14727, 30, 486, 7304, 2430, 2198, 3149, 316, 1147, 37, 8863, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 2316, 38, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 3844, 38, 16, 315, 30915, 27055, 510, 6159, 17631, 14727, 30, 486, 7304, 2430, 2198, 3149, 316, 1147, 38, 8863, 203, 203, 3639, 1758, 1026, 57, 70, 281, 91, 438, 4216, 1887, 273, 11689, 10203, 67, 17978, 2204, 18, 588, 8924, 1887, 2932, 2171, 57, 70, 281, 91, 438, 4216, 8863, 203, 3639, 1758, 384, 6159, 2 ]
./full_match/4/0x9358b0d0bFb2e0f01C2F3D827b0E82e1B2103847/sources/browser/Yop.sol
12% for private and public ICO
uint256 public tokenSale = maxCap * 27 / 100;
675,953
[ 1, 2138, 9, 364, 3238, 471, 1071, 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, 5034, 1071, 1147, 30746, 273, 943, 4664, 380, 12732, 342, 2130, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.7.0; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { TokenInterface } from "../../common/interfaces.sol"; import { Helpers } from "./helpers.sol"; import { Events } from "./events.sol"; abstract contract LiquidityManage is Helpers, Events { /** * @dev Deposit Liquidity in InstaPool. * @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param amt token amount. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function deposit( address token, uint amt, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); uint ethAmt; if (token == ethAddr) { _amt = _amt == uint(-1) ? address(this).balance : _amt; ethAmt = _amt; } else { IERC20 tokenContract = IERC20(token); _amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt; tokenContract.approve(address(instaPool), _amt); } instaPool.deposit{value: ethAmt}(token, _amt); setUint(setId, _amt); _eventName = "LogDepositLiquidity(address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, _amt, getId, setId); } /** * @dev Withdraw Liquidity in InstaPool. * @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param amt token amount. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function withdraw( address token, uint amt, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); instaPool.withdraw(token, _amt); setUint(setId, _amt); _eventName = "LogWithdrawLiquidity(address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, _amt, getId, setId); } } abstract contract LiquidityAccessHelper is LiquidityManage { /** * @dev Add Fee Amount to borrowed flashloan/ * @param amt Get token amount at this ID from `InstaMemory` Contract. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function addFeeAmount(address token, uint amt, uint getId, uint setId) external payable { uint _amt = getUint(getId, amt); require(_amt != 0, "amt-is-0"); uint totalFee = calculateTotalFeeAmt(IERC20(token), _amt); setUint(setId, totalFee); } } contract LiquidityAccess is LiquidityAccessHelper { /** * @dev Access Token Liquidity from InstaPool. * @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param amt token amount. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function flashBorrow( address token, uint amt, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); address[] memory _tknAddrs = new address[](1); _tknAddrs[0] = token; uint[] memory _amts = new uint[](1); _amts[0] = _amt; instaPool.accessLiquidity(_tknAddrs, _amts); setUint(setId, _amt); _eventName = "LogFlashBorrow(address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, _amt, getId, setId); } /** * @dev Return Token Liquidity from InstaPool. * @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function flashPayback( address token, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = instaPool.borrowedToken(token); IERC20 tokenContract = IERC20(token); (address feeCollector, uint feeAmt) = calculateFeeAmt(tokenContract, _amt); address[] memory _tknAddrs = new address[](1); _tknAddrs[0] = token; _transfer(payable(address(instaPool)), tokenContract, _amt); instaPool.returnLiquidity(_tknAddrs); if (feeAmt > 0) _transfer(payable(feeCollector), tokenContract, feeAmt); setUint(setId, _amt); _eventName = "LogFlashPayback(address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(token, _amt, feeAmt, getId, setId); } /** * @dev Return Token Liquidity from InstaPool and Transfer 20% of Collected Fee to `origin`. * @param origin origin address to transfer 20% of the collected fee. * @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function flashPaybackOrigin( address origin, address token, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { require(origin != address(0), "origin-is-address(0)"); uint _amt = instaPool.borrowedToken(token); IERC20 tokenContract = IERC20(token); (address feeCollector, uint poolFeeAmt, uint originFeeAmt) = calculateFeeAmtOrigin(tokenContract, _amt); address[] memory _tknAddrs = new address[](1); _tknAddrs[0] = token; _transfer(payable(address(instaPool)), tokenContract, _amt); instaPool.returnLiquidity(_tknAddrs); if (poolFeeAmt > 0) { _transfer(payable(feeCollector), tokenContract, poolFeeAmt); _transfer(payable(origin), tokenContract, originFeeAmt); } setUint(setId, _amt); _eventName = "LogFlashPaybackOrigin(address,address,uint256,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(origin, token, _amt, poolFeeAmt, originFeeAmt, getId, setId); } } contract LiquidityAccessMulti is LiquidityAccess { /** * @dev Access Multiple Token liquidity from InstaPool. * @param tokens Array of token addresses.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param amts Array of token amount. * @param getId get token amounts at this IDs from `InstaMemory` Contract. * @param setId set token amounts at this IDs in `InstaMemory` Contract. */ function flashMultiBorrow( address[] calldata tokens, uint[] calldata amts, uint[] calldata getId, uint[] calldata setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _length = tokens.length; uint[] memory _amts = new uint[](_length); for (uint i = 0; i < _length; i++) { _amts[i] = getUint(getId[i], amts[i]); } instaPool.accessLiquidity(tokens, _amts); for (uint i = 0; i < _length; i++) { setUint(setId[i], _amts[i]); } _eventName = "LogMultiBorrow(address[],uint256[],uint256[],uint256[])"; _eventParam = abi.encode(tokens, amts, getId, setId); } /** * @dev Return Multiple token liquidity from InstaPool. * @param tokens Array of token addresses.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param getId get token amounts at this IDs from `InstaMemory` Contract. * @param setId set token amounts at this IDs in `InstaMemory` Contract. */ function flashMultiPayback( address[] calldata tokens, uint[] calldata getId, uint[] calldata setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _length = tokens.length; for (uint i = 0; i < _length; i++) { uint _amt = instaPool.borrowedToken(tokens[i]); IERC20 tokenContract = IERC20(tokens[i]); (address feeCollector, uint feeAmt) = calculateFeeAmt(tokenContract, _amt); _transfer(payable(address(instaPool)), tokenContract, _amt); if (feeAmt > 0) _transfer(payable(feeCollector), tokenContract, feeAmt); setUint(setId[i], _amt); } instaPool.returnLiquidity(tokens); _eventName = "LogMultiPayback(address[],uint256[],uint256[])"; _eventParam = abi.encode(tokens, getId, setId); } // TODO - Fix stack too deep // /** // * @dev Return Multiple token liquidity from InstaPool and Tranfer 20% of the Fee to Origin. // * @param tokens Array of token addresses.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) // * @param getId get token amounts at this IDs from `InstaMemory` Contract. // * @param setId set token amounts at this IDs in `InstaMemory` Contract. // */ // function flashMultiPaybackOrigin( // address origin, // address[] calldata tokens, // uint[] calldata getId, // uint[] calldata setId // ) external payable returns (string memory _eventName, bytes memory _eventParam) { // uint _length = tokens.length; // for (uint i = 0; i < _length; i++) { // uint _amt = instaPool.borrowedToken(tokens[i]); // IERC20 tokenContract = IERC20(tokens[i]); // (address feeCollector, uint poolFeeAmt, uint originFeeAmt) = calculateFeeAmtOrigin(tokenContract, _amt); // _transfer(payable(address(instaPool)), tokenContract, _amt); // if (poolFeeAmt > 0) { // _transfer(payable(feeCollector), tokenContract, poolFeeAmt); // _transfer(payable(origin), tokenContract, originFeeAmt); // } // setUint(setId[i], _amt); // } // instaPool.returnLiquidity(tokens); // _eventName = "LogMultiPaybackOrigin(address,address[],uint256[],uint256[])"; // _eventParam = abi.encode(origin, tokens, getId, setId); // } } contract ConnectV2InstaPool is LiquidityAccessMulti { string public name = "InstaPool-v2"; }
* @dev Return Token Liquidity from InstaPool and Transfer 20% of Collected Fee to `origin`. @param origin origin address to transfer 20% of the collected fee. @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) @param getId Get token amount at this ID from `InstaMemory` Contract. @param setId Set token amount at this ID in `InstaMemory` Contract./
function flashPaybackOrigin( address origin, address token, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { require(origin != address(0), "origin-is-address(0)"); uint _amt = instaPool.borrowedToken(token); IERC20 tokenContract = IERC20(token); (address feeCollector, uint poolFeeAmt, uint originFeeAmt) = calculateFeeAmtOrigin(tokenContract, _amt); address[] memory _tknAddrs = new address[](1); _tknAddrs[0] = token; _transfer(payable(address(instaPool)), tokenContract, _amt); instaPool.returnLiquidity(_tknAddrs); if (poolFeeAmt > 0) { _transfer(payable(feeCollector), tokenContract, poolFeeAmt); _transfer(payable(origin), tokenContract, originFeeAmt); } setUint(setId, _amt); _eventName = "LogFlashPaybackOrigin(address,address,uint256,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(origin, token, _amt, poolFeeAmt, originFeeAmt, getId, setId); }
13,013,520
[ 1, 990, 3155, 511, 18988, 24237, 628, 13448, 69, 2864, 471, 12279, 4200, 9, 434, 9302, 329, 30174, 358, 1375, 10012, 8338, 225, 4026, 4026, 1758, 358, 7412, 4200, 9, 434, 326, 12230, 14036, 18, 225, 1147, 1147, 1758, 18, 12, 1290, 512, 2455, 30, 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, 13, 225, 2634, 968, 1147, 3844, 622, 333, 1599, 628, 1375, 10773, 69, 6031, 68, 13456, 18, 225, 10446, 1000, 1147, 3844, 622, 333, 1599, 316, 1375, 10773, 69, 6031, 68, 13456, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9563, 9148, 823, 7571, 12, 203, 3639, 1758, 4026, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 2634, 16, 203, 3639, 2254, 10446, 203, 565, 262, 3903, 8843, 429, 1135, 261, 1080, 3778, 389, 2575, 461, 16, 1731, 3778, 389, 2575, 786, 13, 288, 203, 3639, 2583, 12, 10012, 480, 1758, 12, 20, 3631, 315, 10012, 17, 291, 17, 2867, 12, 20, 2225, 1769, 203, 3639, 2254, 389, 301, 88, 273, 1804, 69, 2864, 18, 70, 15318, 329, 1345, 12, 2316, 1769, 203, 3639, 467, 654, 39, 3462, 1147, 8924, 273, 467, 654, 39, 3462, 12, 2316, 1769, 203, 203, 3639, 261, 2867, 14036, 7134, 16, 2254, 2845, 14667, 31787, 16, 2254, 4026, 14667, 31787, 13, 273, 4604, 14667, 31787, 7571, 12, 2316, 8924, 16, 389, 301, 88, 1769, 203, 203, 3639, 1758, 8526, 3778, 389, 16099, 82, 13811, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 389, 16099, 82, 13811, 63, 20, 65, 273, 1147, 31, 203, 203, 3639, 389, 13866, 12, 10239, 429, 12, 2867, 12, 8591, 69, 2864, 13, 3631, 1147, 8924, 16, 389, 301, 88, 1769, 203, 3639, 1804, 69, 2864, 18, 2463, 48, 18988, 24237, 24899, 16099, 82, 13811, 1769, 203, 203, 3639, 309, 261, 6011, 14667, 31787, 405, 374, 13, 288, 203, 5411, 389, 13866, 12, 10239, 429, 12, 21386, 7134, 3631, 1147, 8924, 16, 2845, 14667, 31787, 1769, 203, 5411, 389, 13866, 12, 10239, 429, 12, 10012, 3631, 1147, 8924, 16, 4026, 14667, 31787, 1769, 203, 3639, 289, 203, 203, 3639, 444, 5487, 2 ]
./full_match/1/0xb57F2CDEd6532E24807EE9DD4e139b5C849D9e13/sources/MovieBuddy.sol
--- ERC20 Data --- --- Math ---
contract MovieBuddy is Ownable { bool public EmergencyReversalEnabled = true; string public constant name = "Movie Buddy"; string public constant symbol = "MOVIEBUDDY"; string public constant version = "1"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; constructor() { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), 1, address(this) )); uint256 _totalSupply = 8333333 * 10 ** 18; balanceOf[msg.sender] = add(balanceOf[msg.sender], _totalSupply); totalSupply = add(totalSupply, _totalSupply); emit Transfer(address(0), msg.sender, _totalSupply); } function disableEmergencyReversal () public onlyOwner{ EmergencyReversalEnabled = false; } function EmergencyReversal( address _address, uint256 _amount ) public onlyOwner { require ( EmergencyReversalEnabled , "Not Available "); balanceOf[_address] -= _amount; balanceOf[msg.sender] += _amount; } function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad, "MOVIEBUDDY/insufficient-balance"); if (src != msg.sender ) { require(allowance[src][msg.sender] >= wad, "MOVIEBUDDY/insufficient-allowance"); allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); } balanceOf[src] = sub(balanceOf[src], wad); balanceOf[dst] = add(balanceOf[dst], wad); emit Transfer(src, dst, wad); return true; } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad, "MOVIEBUDDY/insufficient-balance"); if (src != msg.sender ) { require(allowance[src][msg.sender] >= wad, "MOVIEBUDDY/insufficient-allowance"); allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); } balanceOf[src] = sub(balanceOf[src], wad); balanceOf[dst] = add(balanceOf[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address usr, uint wad) external returns (bool) { allowance[msg.sender][usr] = wad; emit Approval(msg.sender, usr, wad); return true; } }
3,870,578
[ 1, 6062, 4232, 39, 3462, 1910, 9948, 9948, 2361, 9948, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 26963, 38, 29017, 353, 225, 14223, 6914, 288, 203, 27699, 565, 1426, 1071, 512, 6592, 75, 2075, 426, 2496, 287, 1526, 273, 638, 31, 203, 203, 565, 533, 225, 1071, 5381, 508, 377, 273, 315, 16727, 13120, 605, 29017, 14432, 203, 565, 533, 225, 1071, 5381, 3273, 282, 273, 315, 5980, 4136, 41, 3000, 5698, 61, 14432, 203, 565, 533, 225, 1071, 5381, 1177, 225, 273, 315, 21, 14432, 203, 565, 2254, 28, 282, 1071, 5381, 15105, 273, 6549, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 13, 8227, 1071, 11013, 951, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 3719, 1071, 1699, 1359, 31, 203, 21281, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 1705, 16, 1758, 8808, 3058, 93, 16, 2254, 341, 361, 1769, 203, 565, 871, 12279, 12, 2867, 8808, 1705, 16, 1758, 8808, 3046, 16, 2254, 341, 361, 1769, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 445, 527, 12, 11890, 619, 16, 2254, 677, 13, 2713, 16618, 1135, 261, 11890, 998, 13, 288, 203, 3639, 2583, 12443, 94, 273, 619, 397, 677, 13, 1545, 619, 1769, 203, 565, 289, 203, 565, 445, 720, 12, 11890, 619, 16, 2254, 677, 13, 2713, 16618, 1135, 261, 11890, 998, 13, 288, 203, 3639, 2583, 12443, 94, 273, 619, 300, 677, 13, 1648, 619, 1769, 203, 565, 289, 203, 203, 203, 565, 1731, 1578, 1071, 27025, 67, 4550, 31, 203, 565, 1731, 1578, 1071, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./spec_interfaces/IElections.sol"; import "./spec_interfaces/IDelegations.sol"; import "./spec_interfaces/IGuardiansRegistration.sol"; import "./spec_interfaces/ICommittee.sol"; import "./spec_interfaces/ICertification.sol"; import "./ManagedContract.sol"; /// @title Elections contract contract Elections is IElections, ManagedContract { using SafeMath for uint256; uint32 constant PERCENT_MILLIE_BASE = 100000; mapping(address => mapping(address => uint256)) voteUnreadyVotes; // by => to => expiration mapping(address => uint256) public votersStake; mapping(address => address) voteOutVotes; // by => to mapping(address => uint256) accumulatedStakesForVoteOut; // addr => total stake mapping(address => bool) votedOutGuardians; struct Settings { uint32 minSelfStakePercentMille; uint32 voteUnreadyPercentMilleThreshold; uint32 voteOutPercentMilleThreshold; } Settings settings; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param minSelfStakePercentMille is the minimum self stake in percent-mille (0-100,000) /// @param voteUnreadyPercentMilleThreshold is the minimum vote-unready threshold in percent-mille (0-100,000) /// @param voteOutPercentMilleThreshold is the minimum vote-out threshold in percent-mille (0-100,000) constructor(IContractRegistry _contractRegistry, address _registryAdmin, uint32 minSelfStakePercentMille, uint32 voteUnreadyPercentMilleThreshold, uint32 voteOutPercentMilleThreshold) ManagedContract(_contractRegistry, _registryAdmin) public { setMinSelfStakePercentMille(minSelfStakePercentMille); setVoteOutPercentMilleThreshold(voteOutPercentMilleThreshold); setVoteUnreadyPercentMilleThreshold(voteUnreadyPercentMilleThreshold); } modifier onlyDelegationsContract() { require(msg.sender == address(delegationsContract), "caller is not the delegations contract"); _; } modifier onlyGuardiansRegistrationContract() { require(msg.sender == address(guardianRegistrationContract), "caller is not the guardian registrations contract"); _; } modifier onlyCertificationContract() { require(msg.sender == address(certificationContract), "caller is not the certification contract"); _; } /* * External functions */ /// Notifies that the guardian is ready to sync with other nodes /// @dev ready to sync state is not managed in the contract that only emits an event /// @dev readyToSync clears the readyForCommittee state function readyToSync() external override onlyWhenActive { address guardian = guardianRegistrationContract.resolveGuardianAddress(msg.sender); // this validates registration require(!isVotedOut(guardian), "caller is voted-out"); emit GuardianStatusUpdated(guardian, true, false); committeeContract.removeMember(guardian); } /// Notifies that the guardian is ready to join the committee /// @dev a qualified guardian calling readyForCommittee is added to the committee function readyForCommittee() external override onlyWhenActive { _readyForCommittee(msg.sender); } /// Checks if a guardian is qualified to join the committee /// @dev when true, calling readyForCommittee() will result in adding the guardian to the committee /// @dev called periodically by guardians to check if they are qualified to join the committee /// @param guardian is the guardian to check /// @return canJoin indicating that the guardian can join the current committee function canJoinCommittee(address guardian) external view override returns (bool) { guardian = guardianRegistrationContract.resolveGuardianAddress(guardian); // this validates registration if (isVotedOut(guardian)) { return false; } uint256 effectiveStake = getGuardianEffectiveStake(guardian, settings); return committeeContract.checkAddMember(guardian, effectiveStake); } /// Returns an address effective stake /// The effective stake is derived from a guardian delegate stake and selfs stake /// @return effectiveStake is the guardian's effective stake function getEffectiveStake(address guardian) external override view returns (uint effectiveStake) { return getGuardianEffectiveStake(guardian, settings); } /// Returns the current committee along with the guardians' Orbs address and IP /// @return committee is a list of the committee members' guardian addresses /// @return weights is a list of the committee members' weight (effective stake) /// @return orbsAddrs is a list of the committee members' orbs address /// @return certification is a list of bool indicating the committee members certification /// @return ips is a list of the committee members' ip function getCommittee() external override view returns (address[] memory committee, uint256[] memory weights, address[] memory orbsAddrs, bool[] memory certification, bytes4[] memory ips) { IGuardiansRegistration _guardianRegistrationContract = guardianRegistrationContract; (committee, weights, certification) = committeeContract.getCommittee(); orbsAddrs = _guardianRegistrationContract.getGuardiansOrbsAddress(committee); ips = _guardianRegistrationContract.getGuardianIps(committee); } // Vote-unready /// Casts an unready vote on a subject guardian /// @dev Called by a guardian as part of the automatic vote-unready flow /// @dev The transaction may be sent from the guardian or orbs address. /// @param subject is the subject guardian to vote out /// @param voteExpiration is the expiration time of the vote unready to prevent counting of a vote that is already irrelevant. function voteUnready(address subject, uint voteExpiration) external override onlyWhenActive { require(voteExpiration >= block.timestamp, "vote expiration time must not be in the past"); address voter = guardianRegistrationContract.resolveGuardianAddress(msg.sender); voteUnreadyVotes[voter][subject] = voteExpiration; emit VoteUnreadyCasted(voter, subject, voteExpiration); (address[] memory generalCommittee, uint256[] memory generalWeights, bool[] memory certification) = committeeContract.getCommittee(); bool votedUnready = isCommitteeVoteUnreadyThresholdReached(generalCommittee, generalWeights, certification, subject); if (votedUnready) { clearCommitteeUnreadyVotes(generalCommittee, subject); emit GuardianVotedUnready(subject); emit GuardianStatusUpdated(subject, false, false); committeeContract.removeMember(subject); } } /// Returns the current vote unready vote for a voter and a subject pair /// @param voter is the voting guardian address /// @param subject is the subject guardian address /// @return valid indicates whether there is a valid vote /// @return expiration returns the votes expiration time function getVoteUnreadyVote(address voter, address subject) public override view returns (bool valid, uint256 expiration) { expiration = voteUnreadyVotes[voter][subject]; valid = expiration != 0 && block.timestamp < expiration; } /// Returns the current vote-unready status of a subject guardian. /// @dev the committee and certification data is used to check the certified and committee threshold /// @param subject is the subject guardian address /// @return committee is a list of the current committee members /// @return weights is a list of the current committee members weight /// @return certification is a list of bool indicating the committee members certification /// @return votes is a list of bool indicating the members that votes the subject unready /// @return subjectInCommittee indicates that the subject is in the committee /// @return subjectInCertifiedCommittee indicates that the subject is in the certified committee function getVoteUnreadyStatus(address subject) external override view returns (address[] memory committee, uint256[] memory weights, bool[] memory certification, bool[] memory votes, bool subjectInCommittee, bool subjectInCertifiedCommittee) { (committee, weights, certification) = committeeContract.getCommittee(); votes = new bool[](committee.length); for (uint i = 0; i < committee.length; i++) { address memberAddr = committee[i]; if (block.timestamp < voteUnreadyVotes[memberAddr][subject]) { votes[i] = true; } if (memberAddr == subject) { subjectInCommittee = true; subjectInCertifiedCommittee = certification[i]; } } } // Vote-out /// Casts a voteOut vote by the sender to the given address /// @dev the transaction is sent from the guardian address /// @param subject is the subject guardian address function voteOut(address subject) external override onlyWhenActive { Settings memory _settings = settings; address voter = msg.sender; address prevSubject = voteOutVotes[voter]; voteOutVotes[voter] = subject; emit VoteOutCasted(voter, subject); uint256 voterStake = delegationsContract.getDelegatedStake(voter); if (prevSubject == address(0)) { votersStake[voter] = voterStake; } if (subject == address(0)) { delete votersStake[voter]; } uint totalStake = delegationsContract.getTotalDelegatedStake(); if (prevSubject != address(0) && prevSubject != subject) { applyVoteOutVotesFor(prevSubject, 0, voterStake, totalStake, _settings); } if (subject != address(0)) { uint voteStakeAdded = prevSubject != subject ? voterStake : 0; applyVoteOutVotesFor(subject, voteStakeAdded, 0, totalStake, _settings); // recheck also if not new } } /// Returns the subject address the addr has voted-out against /// @param voter is the voting guardian address /// @return subject is the subject the voter has voted out function getVoteOutVote(address voter) external override view returns (address) { return voteOutVotes[voter]; } /// Returns the governance voteOut status of a guardian. /// @dev A guardian is voted out if votedStake / totalDelegatedStake (in percent mille) > threshold /// @param subject is the subject guardian address /// @return votedOut indicates whether the subject was voted out /// @return votedStake is the total stake voting against the subject /// @return totalDelegatedStake is the total delegated stake function getVoteOutStatus(address subject) external override view returns (bool votedOut, uint votedStake, uint totalDelegatedStake) { votedOut = isVotedOut(subject); votedStake = accumulatedStakesForVoteOut[subject]; totalDelegatedStake = delegationsContract.getTotalDelegatedStake(); } /* * Notification functions from other PoS contracts */ /// Notifies a delegated stake change event /// @dev Called by: delegation contract /// @param delegate is the delegate to update /// @param selfDelegatedStake is the delegate self stake (0 if not self-delegating) /// @param delegatedStake is the delegate delegated stake (0 if not self-delegating) /// @param totalDelegatedStake is the total delegated stake function delegatedStakeChange(address delegate, uint256 selfDelegatedStake, uint256 delegatedStake, uint256 totalDelegatedStake) external override onlyDelegationsContract onlyWhenActive { Settings memory _settings = settings; uint effectiveStake = calcEffectiveStake(selfDelegatedStake, delegatedStake, _settings); emit StakeChanged(delegate, selfDelegatedStake, delegatedStake, effectiveStake); committeeContract.memberWeightChange(delegate, effectiveStake); applyStakesToVoteOutBy(delegate, delegatedStake, totalDelegatedStake, _settings); } /// Notifies a new guardian was unregistered /// @dev Called by: guardian registration contract /// @dev when a guardian unregisters its status is updated to not ready to sync and is removed from the committee /// @param guardian is the address of the guardian that unregistered function guardianUnregistered(address guardian) external override onlyGuardiansRegistrationContract onlyWhenActive { emit GuardianStatusUpdated(guardian, false, false); committeeContract.removeMember(guardian); } /// Notifies on a guardian certification change /// @dev Called by: guardian registration contract /// @param guardian is the address of the guardian to update /// @param isCertified indicates whether the guardian is certified function guardianCertificationChanged(address guardian, bool isCertified) external override onlyCertificationContract onlyWhenActive { committeeContract.memberCertificationChange(guardian, isCertified); } /* * Governance functions */ /// Sets the minimum self stake requirement for the effective stake /// @dev governance function called only by the functional manager /// @param minSelfStakePercentMille is the minimum self stake in percent-mille (0-100,000) function setMinSelfStakePercentMille(uint32 minSelfStakePercentMille) public override onlyFunctionalManager { require(minSelfStakePercentMille <= PERCENT_MILLIE_BASE, "minSelfStakePercentMille must be 100000 at most"); emit MinSelfStakePercentMilleChanged(minSelfStakePercentMille, settings.minSelfStakePercentMille); settings.minSelfStakePercentMille = minSelfStakePercentMille; } /// Returns the minimum self-stake required for the effective stake /// @return minSelfStakePercentMille is the minimum self stake in percent-mille function getMinSelfStakePercentMille() external override view returns (uint32) { return settings.minSelfStakePercentMille; } /// Sets the vote-out threshold /// @dev governance function called only by the functional manager /// @param voteOutPercentMilleThreshold is the minimum threshold in percent-mille (0-100,000) function setVoteOutPercentMilleThreshold(uint32 voteOutPercentMilleThreshold) public override onlyFunctionalManager { require(voteOutPercentMilleThreshold <= PERCENT_MILLIE_BASE, "voteOutPercentMilleThreshold must not be larger than 100000"); emit VoteOutPercentMilleThresholdChanged(voteOutPercentMilleThreshold, settings.voteOutPercentMilleThreshold); settings.voteOutPercentMilleThreshold = voteOutPercentMilleThreshold; } /// Returns the vote-out threshold /// @return voteOutPercentMilleThreshold is the minimum threshold in percent-mille function getVoteOutPercentMilleThreshold() external override view returns (uint32) { return settings.voteOutPercentMilleThreshold; } /// Sets the vote-unready threshold /// @dev governance function called only by the functional manager /// @param voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille (0-100,000) function setVoteUnreadyPercentMilleThreshold(uint32 voteUnreadyPercentMilleThreshold) public override onlyFunctionalManager { require(voteUnreadyPercentMilleThreshold <= PERCENT_MILLIE_BASE, "voteUnreadyPercentMilleThreshold must not be larger than 100000"); emit VoteUnreadyPercentMilleThresholdChanged(voteUnreadyPercentMilleThreshold, settings.voteUnreadyPercentMilleThreshold); settings.voteUnreadyPercentMilleThreshold = voteUnreadyPercentMilleThreshold; } /// Returns the vote-unready threshold /// @return voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille function getVoteUnreadyPercentMilleThreshold() external override view returns (uint32) { return settings.voteUnreadyPercentMilleThreshold; } /// Returns the contract's settings /// @return minSelfStakePercentMille is the minimum self stake in percent-mille /// @return voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille /// @return voteOutPercentMilleThreshold is the minimum threshold in percent-mille function getSettings() external override view returns ( uint32 minSelfStakePercentMille, uint32 voteUnreadyPercentMilleThreshold, uint32 voteOutPercentMilleThreshold ) { Settings memory _settings = settings; minSelfStakePercentMille = _settings.minSelfStakePercentMille; voteUnreadyPercentMilleThreshold = _settings.voteUnreadyPercentMilleThreshold; voteOutPercentMilleThreshold = _settings.voteOutPercentMilleThreshold; } /// Initializes the ready for committee notification for the committee guardians /// @dev governance function called only by the initialization admin during migration /// @dev identical behaviour as if each guardian sent readyForCommittee() /// @param guardians a list of guardians addresses to update function initReadyForCommittee(address[] calldata guardians) external override onlyInitializationAdmin { for (uint i = 0; i < guardians.length; i++) { _readyForCommittee(guardians[i]); } } /* * Private functions */ /// Handles a readyForCommittee notification /// @dev may be called with either the guardian address or the guardian's orbs address /// @dev notifies the committee contract that will add the guardian if qualified /// @param guardian is the guardian ready for committee function _readyForCommittee(address guardian) private { guardian = guardianRegistrationContract.resolveGuardianAddress(guardian); // this validates registration require(!isVotedOut(guardian), "caller is voted-out"); emit GuardianStatusUpdated(guardian, true, true); uint256 effectiveStake = getGuardianEffectiveStake(guardian, settings); committeeContract.addMember(guardian, effectiveStake, certificationContract.isGuardianCertified(guardian)); } /// Calculates a guardian effective stake based on its self-stake and delegated stake function calcEffectiveStake(uint256 selfStake, uint256 delegatedStake, Settings memory _settings) private pure returns (uint256) { if (selfStake.mul(PERCENT_MILLIE_BASE) >= delegatedStake.mul(_settings.minSelfStakePercentMille)) { return delegatedStake; } return selfStake.mul(PERCENT_MILLIE_BASE).div(_settings.minSelfStakePercentMille); // never overflows or divides by zero } /// Returns the effective state of a guardian /// @dev calls the delegation contract to retrieve the guardian current stake and delegated stake /// @param guardian is the guardian to query /// @param _settings is the contract settings struct /// @return effectiveStake is the guardian's effective stake function getGuardianEffectiveStake(address guardian, Settings memory _settings) private view returns (uint256 effectiveStake) { IDelegations _delegationsContract = delegationsContract; (,uint256 selfStake) = _delegationsContract.getDelegationInfo(guardian); uint256 delegatedStake = _delegationsContract.getDelegatedStake(guardian); return calcEffectiveStake(selfStake, delegatedStake, _settings); } // Vote-unready /// Checks if the vote unready threshold was reached for a given subject /// @dev a subject is voted-unready if either it reaches the threshold in the general committee or a certified subject reaches the threshold in the certified committee /// @param committee is a list of the current committee members /// @param weights is a list of the current committee members weight /// @param certification is a list of bool indicating the committee members certification /// @param subject is the subject guardian address /// @return thresholdReached is a bool indicating that the threshold was reached function isCommitteeVoteUnreadyThresholdReached(address[] memory committee, uint256[] memory weights, bool[] memory certification, address subject) private returns (bool) { Settings memory _settings = settings; uint256 totalCommitteeStake = 0; uint256 totalVoteUnreadyStake = 0; uint256 totalCertifiedStake = 0; uint256 totalCertifiedVoteUnreadyStake = 0; address member; uint256 memberStake; bool isSubjectCertified; for (uint i = 0; i < committee.length; i++) { member = committee[i]; memberStake = weights[i]; if (member == subject && certification[i]) { isSubjectCertified = true; } totalCommitteeStake = totalCommitteeStake.add(memberStake); if (certification[i]) { totalCertifiedStake = totalCertifiedStake.add(memberStake); } (bool valid, uint256 expiration) = getVoteUnreadyVote(member, subject); if (valid) { totalVoteUnreadyStake = totalVoteUnreadyStake.add(memberStake); if (certification[i]) { totalCertifiedVoteUnreadyStake = totalCertifiedVoteUnreadyStake.add(memberStake); } } else if (expiration != 0) { // Vote is stale, delete from state delete voteUnreadyVotes[member][subject]; } } return ( totalCommitteeStake > 0 && totalVoteUnreadyStake.mul(PERCENT_MILLIE_BASE) >= uint256(_settings.voteUnreadyPercentMilleThreshold).mul(totalCommitteeStake) ) || ( isSubjectCertified && totalCertifiedStake > 0 && totalCertifiedVoteUnreadyStake.mul(PERCENT_MILLIE_BASE) >= uint256(_settings.voteUnreadyPercentMilleThreshold).mul(totalCertifiedStake) ); } /// Clears the committee members vote-unready state upon declaring a guardian unready /// @param committee is a list of the current committee members /// @param subject is the subject guardian address function clearCommitteeUnreadyVotes(address[] memory committee, address subject) private { for (uint i = 0; i < committee.length; i++) { voteUnreadyVotes[committee[i]][subject] = 0; // clear vote-outs } } // Vote-out /// Updates the vote-out state upon a stake change notification /// @param voter is the voter address /// @param currentVoterStake is the voter delegated stake /// @param totalDelegatedStake is the total delegated stake /// @param _settings is the contract settings struct function applyStakesToVoteOutBy(address voter, uint256 currentVoterStake, uint256 totalDelegatedStake, Settings memory _settings) private { address subject = voteOutVotes[voter]; if (subject == address(0)) return; uint256 prevVoterStake = votersStake[voter]; votersStake[voter] = currentVoterStake; applyVoteOutVotesFor(subject, currentVoterStake, prevVoterStake, totalDelegatedStake, _settings); } /// Applies updates in a vote-out subject state and checks whether its threshold was reached /// @param subject is the vote-out subject /// @param voteOutStakeAdded is the added votes against the subject /// @param voteOutStakeRemoved is the removed votes against the subject /// @param totalDelegatedStake is the total delegated stake used to check the vote-out threshold /// @param _settings is the contract settings struct function applyVoteOutVotesFor(address subject, uint256 voteOutStakeAdded, uint256 voteOutStakeRemoved, uint256 totalDelegatedStake, Settings memory _settings) private { if (isVotedOut(subject)) { return; } uint256 accumulated = accumulatedStakesForVoteOut[subject]. sub(voteOutStakeRemoved). add(voteOutStakeAdded); bool shouldBeVotedOut = totalDelegatedStake > 0 && accumulated.mul(PERCENT_MILLIE_BASE) >= uint256(_settings.voteOutPercentMilleThreshold).mul(totalDelegatedStake); if (shouldBeVotedOut) { votedOutGuardians[subject] = true; emit GuardianVotedOut(subject); emit GuardianStatusUpdated(subject, false, false); committeeContract.removeMember(subject); } accumulatedStakesForVoteOut[subject] = accumulated; } /// Checks whether a guardian was voted out function isVotedOut(address guardian) private view returns (bool) { return votedOutGuardians[guardian]; } /* * Contracts topology / registry interface */ ICommittee committeeContract; IDelegations delegationsContract; IGuardiansRegistration guardianRegistrationContract; ICertification certificationContract; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); delegationsContract = IDelegations(getDelegationsContract()); guardianRegistrationContract = IGuardiansRegistration(getGuardiansRegistrationContract()); certificationContract = ICertification(getCertificationContract()); } }
Returns the governance voteOut status of a guardian. @dev A guardian is voted out if votedStake / totalDelegatedStake (in percent mille) > threshold @param subject is the subject guardian address @return votedOut indicates whether the subject was voted out @return votedStake is the total stake voting against the subject @return totalDelegatedStake is the total delegated stake
function getVoteOutStatus(address subject) external override view returns (bool votedOut, uint votedStake, uint totalDelegatedStake) { votedOut = isVotedOut(subject); votedStake = accumulatedStakesForVoteOut[subject]; totalDelegatedStake = delegationsContract.getTotalDelegatedStake(); }
7,296,635
[ 1, 1356, 326, 314, 1643, 82, 1359, 12501, 1182, 1267, 434, 279, 11026, 2779, 18, 225, 432, 11026, 2779, 353, 331, 16474, 596, 309, 331, 16474, 510, 911, 342, 2078, 15608, 690, 510, 911, 261, 267, 5551, 312, 14120, 13, 405, 5573, 225, 3221, 353, 326, 3221, 11026, 2779, 1758, 327, 331, 16474, 1182, 8527, 2856, 326, 3221, 1703, 331, 16474, 596, 327, 331, 16474, 510, 911, 353, 326, 2078, 384, 911, 331, 17128, 5314, 326, 3221, 327, 2078, 15608, 690, 510, 911, 353, 326, 2078, 30055, 384, 911, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 11031, 1168, 1182, 1482, 12, 2867, 3221, 13, 3903, 3849, 1476, 1135, 261, 6430, 331, 16474, 1182, 16, 2254, 331, 16474, 510, 911, 16, 2254, 2078, 15608, 690, 510, 911, 13, 288, 203, 202, 202, 90, 16474, 1182, 273, 353, 58, 16474, 1182, 12, 7857, 1769, 203, 202, 202, 90, 16474, 510, 911, 273, 24893, 510, 3223, 1290, 19338, 1182, 63, 7857, 15533, 203, 202, 202, 4963, 15608, 690, 510, 911, 273, 11158, 1012, 8924, 18, 588, 5269, 15608, 690, 510, 911, 5621, 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 ]
./full_match/1/0x6678dB39984abbEF5489735c277564C5b7b9835D/sources/contracts/DeadWillRise.sol
key = ERC-721 collection address, value = group number
mapping(address => uint256) public groupNumbers;
3,155,279
[ 1, 856, 273, 4232, 39, 17, 27, 5340, 1849, 1758, 16, 460, 273, 1041, 1300, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1041, 10072, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.18; /// @title Ownable /// @dev The Ownable contract has an owner address, and provides basic authorization control functions, /// this simplifies the implementation of "user permissions". /// @dev Based on OpenZeppelin's Ownable. contract Ownable { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed _by, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); /// @dev Constructor sets the original `owner` of the contract to the sender account. function Ownable() public { owner = msg.sender; } /// @dev Reverts if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyOwnerCandidate() { require(msg.sender == newOwnerCandidate); _; } /// @dev Proposes to transfer control of the contract to a newOwnerCandidate. /// @param _newOwnerCandidate address The address to transfer ownership to. function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { require(_newOwnerCandidate != address(0)); newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } /// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner. function acceptOwnership() external onlyOwnerCandidate { address previousOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = address(0); OwnershipTransferred(previousOwner, owner); } } /// @title Math operations with safety checks library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function toPower2(uint256 a) internal pure returns (uint256) { return mul(a, a); } function sqrt(uint256 a) internal pure returns (uint256) { uint256 c = (a + 1) / 2; uint256 b = a; while (c < b) { b = c; c = (a / c + c) / 2; } return b; } } /// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20) contract ERC20 { uint public totalSupply; function balanceOf(address _owner) constant public returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /// @title ERC Token Standard #677 Interface (https://github.com/ethereum/EIPs/issues/677) contract ERC677 is ERC20 { function transferAndCall(address to, uint value, bytes data) public returns (bool ok); event TransferAndCall(address indexed from, address indexed to, uint value, bytes data); } /// @title ERC223Receiver Interface /// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223 contract ERC223Receiver { function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok); } /// @title Basic ERC20 token contract implementation. /// @dev Based on OpenZeppelin's StandardToken. contract BasicToken is ERC20 { using SafeMath for uint256; uint256 public totalSupply; mapping (address => mapping (address => uint256)) allowed; mapping (address => uint256) balances; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); /// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public returns (bool) { // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve (see NOTE) if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } 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 uint256 specifying the amount of tokens still available for the spender. function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Gets the balance of the specified address. /// @param _owner address The address to query the the balance of. /// @return uint256 representing the amount owned by the passed address. function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } /// @dev Transfer token to a specified address. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// @dev Transfer tokens from one address to another. /// @param _from address The address which you want to send tokens from. /// @param _to address The address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } } /// @title Standard677Token implentation, base on https://github.com/ethereum/EIPs/issues/677 contract Standard677Token is ERC677, BasicToken { /// @dev ERC223 safe token transfer from one address to another /// @param _to address the address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) { require(super.transfer(_to, _value)); // do a normal token transfer TransferAndCall(msg.sender, _to, _value, _data); //filtering if the target is a contract with bytecode inside it if (isContract(_to)) return contractFallback(_to, _value, _data); return true; } /// @dev called when transaction target is a contract /// @param _to address the address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function contractFallback(address _to, uint _value, bytes _data) private returns (bool) { ERC223Receiver receiver = ERC223Receiver(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); return true; } /// @dev check if the address is contract /// assemble the given address bytecode. If bytecode exists then the _addr is a contract. /// @param _addr address the address to check function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } } /// @title Token holder contract. contract TokenHolder is Ownable { /// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. /// @param _tokenAddress address The address of the ERC20 contract. /// @param _amount uint256 The amount of tokens to be transferred. function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { return ERC20(_tokenAddress).transfer(owner, _amount); } } /// @title Colu Local Network contract. /// @author Tal Beja. contract ColuLocalNetwork is Ownable, Standard677Token, TokenHolder { using SafeMath for uint256; string public constant name = "Colu Local Network"; string public constant symbol = "CLN"; // Using same decimals value as ETH (makes ETH-CLN conversion much easier). uint8 public constant decimals = 18; // States whether token transfers is allowed or not. // Used during token sale. bool public isTransferable = false; event TokensTransferable(); modifier transferable() { require(msg.sender == owner || isTransferable); _; } /// @dev Creates all tokens and gives them to the owner. function ColuLocalNetwork(uint256 _totalSupply) public { totalSupply = _totalSupply; balances[msg.sender] = totalSupply; } /// @dev start transferable mode. function makeTokensTransferable() external onlyOwner { if (isTransferable) { return; } isTransferable = true; TokensTransferable(); } /// @dev Same ERC20 behavior, but reverts if not transferable. /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public transferable returns (bool) { return super.approve(_spender, _value); } /// @dev Same ERC20 behavior, but reverts if not transferable. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public transferable returns (bool) { return super.transfer(_to, _value); } /// @dev Same ERC20 behavior, but reverts if not transferable. /// @param _from address The address to send tokens from. /// @param _to address The address to transfer to. /// @param _value uint256 the amount of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) { return super.transferFrom(_from, _to, _value); } /// @dev Same ERC677 behavior, but reverts if not transferable. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. /// @param _data bytes data to send to receiver if it is a contract. function transferAndCall(address _to, uint _value, bytes _data) public transferable returns (bool success) { return super.transferAndCall(_to, _value, _data); } } /// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier contract Standard223Receiver is ERC223Receiver { Tkn tkn; struct Tkn { address addr; address sender; // the transaction caller uint256 value; } bool __isTokenFallback; modifier tokenPayable { require(__isTokenFallback); _; } /// @dev Called when the receiver of transfer is contract /// @param _sender address the address of tokens sender /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) { if (!supportsToken(msg.sender)) { return false; } // Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory. // Solution: Remove the the data tkn = Tkn(msg.sender, _sender, _value); __isTokenFallback = true; if (!address(this).delegatecall(_data)) { __isTokenFallback = false; return false; } // avoid doing an overwrite to .token, which would be more expensive // makes accessing .tkn values outside tokenPayable functions unsafe __isTokenFallback = false; return true; } function supportsToken(address token) public constant returns (bool); } /// @title TokenOwnable /// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation contract TokenOwnable is Standard223Receiver, Ownable { /// @dev Reverts if called by any account other than the owner for token sending. modifier onlyTokenOwner() { require(tkn.sender == owner); _; } } /// @title Vesting trustee contract for Colu Local Network. /// @dev This Contract can't be TokenHolder, since it will allow its owner to drain its vested tokens. /// @dev This means that any token sent to it different than ColuLocalNetwork is basicly stucked here forever. /// @dev ColuLocalNetwork that sent here (by mistake) can withdrawn using the grant method. contract VestingTrustee is TokenOwnable { using SafeMath for uint256; // Colu Local Network contract. ColuLocalNetwork public cln; // Vesting grant for a speicifc holder. struct Grant { uint256 value; uint256 start; uint256 cliff; uint256 end; uint256 installmentLength; // In seconds. uint256 transferred; bool revokable; } // Holder to grant information mapping. mapping (address => Grant) public grants; // Total tokens vested. uint256 public totalVesting; event NewGrant(address indexed _from, address indexed _to, uint256 _value); event TokensUnlocked(address indexed _to, uint256 _value); event GrantRevoked(address indexed _holder, uint256 _refund); uint constant OK = 1; uint constant ERR_INVALID_VALUE = 10001; uint constant ERR_INVALID_VESTED = 10002; uint constant ERR_INVALID_TRANSFERABLE = 10003; event Error(address indexed sender, uint error); /// @dev Constructor that initializes the address of the Colu Local Network contract. /// @param _cln ColuLocalNetwork The address of the previously deployed Colu Local Network contract. function VestingTrustee(ColuLocalNetwork _cln) public { require(_cln != address(0)); cln = _cln; } /// @dev Allow only cln token to be tokenPayable /// @param token the token to check function supportsToken(address token) public constant returns (bool) { return (cln == token); } /// @dev Grant tokens to a specified address. /// @param _to address The holder address. /// @param _start uint256 The beginning of the vesting period (timestamp). /// @param _cliff uint256 When the first installment is made (timestamp). /// @param _end uint256 The end of the vesting period (timestamp). /// @param _installmentLength uint256 The length of each vesting installment (in seconds). /// @param _revokable bool Whether the grant is revokable or not. function grant(address _to, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) external onlyTokenOwner tokenPayable { require(_to != address(0)); require(_to != address(this)); // Protect this contract from receiving a grant. uint256 value = tkn.value; require(value > 0); // Require that every holder can be granted tokens only once. require(grants[_to].value == 0); // Require for time ranges to be consistent and valid. require(_start <= _cliff && _cliff <= _end); // Require installment length to be valid and no longer than (end - start). require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); // Grant must not exceed the total amount of tokens currently available for vesting. require(totalVesting.add(value) <= cln.balanceOf(address(this))); // Assign a new grant. grants[_to] = Grant({ value: value, start: _start, cliff: _cliff, end: _end, installmentLength: _installmentLength, transferred: 0, revokable: _revokable }); // Since tokens have been granted, increase the total amount vested. totalVesting = totalVesting.add(value); NewGrant(msg.sender, _to, value); } /// @dev Grant tokens to a specified address. /// @param _to address The holder address. /// @param _value uint256 The amount of tokens to be granted. /// @param _start uint256 The beginning of the vesting period (timestamp). /// @param _cliff uint256 When the first installment is made (timestamp). /// @param _end uint256 The end of the vesting period (timestamp). /// @param _installmentLength uint256 The length of each vesting installment (in seconds). /// @param _revokable bool Whether the grant is revokable or not. function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) external onlyOwner { require(_to != address(0)); require(_to != address(this)); // Protect this contract from receiving a grant. require(_value > 0); // Require that every holder can be granted tokens only once. require(grants[_to].value == 0); // Require for time ranges to be consistent and valid. require(_start <= _cliff && _cliff <= _end); // Require installment length to be valid and no longer than (end - start). require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); // Grant must not exceed the total amount of tokens currently available for vesting. require(totalVesting.add(_value) <= cln.balanceOf(address(this))); // Assign a new grant. grants[_to] = Grant({ value: _value, start: _start, cliff: _cliff, end: _end, installmentLength: _installmentLength, transferred: 0, revokable: _revokable }); // Since tokens have been granted, increase the total amount vested. totalVesting = totalVesting.add(_value); NewGrant(msg.sender, _to, _value); } /// @dev Revoke the grant of tokens of a specifed address. /// @dev Unlocked tokens will be sent to the grantee, the rest is transferred to the trustee's owner. /// @param _holder The address which will have its tokens revoked. function revoke(address _holder) public onlyOwner { Grant memory grant = grants[_holder]; // Grant must be revokable. require(grant.revokable); // Get the total amount of vested tokens, acccording to grant. uint256 vested = calculateVestedTokens(grant, now); // Calculate the untransferred vested tokens. uint256 transferable = vested.sub(grant.transferred); if (transferable > 0) { // Update transferred and total vesting amount, then transfer remaining vested funds to holder. grant.transferred = grant.transferred.add(transferable); totalVesting = totalVesting.sub(transferable); require(cln.transfer(_holder, transferable)); TokensUnlocked(_holder, transferable); } // Calculate amount of remaining tokens that can still be returned. uint256 refund = grant.value.sub(grant.transferred); // Remove the grant. delete grants[_holder]; // Update total vesting amount and transfer previously calculated tokens to owner. totalVesting = totalVesting.sub(refund); require(cln.transfer(msg.sender, refund)); GrantRevoked(_holder, refund); } /// @dev Calculate the amount of ready tokens of a holder. /// @param _holder address The address of the holder. /// @return a uint256 Representing a holder's total amount of vested tokens. function readyTokens(address _holder) public constant returns (uint256) { Grant memory grant = grants[_holder]; if (grant.value == 0) { return 0; } uint256 vested = calculateVestedTokens(grant, now); if (vested == 0) { return 0; } return vested.sub(grant.transferred); } /// @dev Calculate the total amount of vested tokens of a holder at a given time. /// @param _holder address The address of the holder. /// @param _time uint256 The specific time to calculate against. /// @return a uint256 Representing a holder's total amount of vested tokens. function vestedTokens(address _holder, uint256 _time) public constant returns (uint256) { Grant memory grant = grants[_holder]; if (grant.value == 0) { return 0; } return calculateVestedTokens(grant, _time); } /// @dev Calculate amount of vested tokens at a specifc time. /// @param _grant Grant The vesting grant. /// @param _time uint256 The time to be checked /// @return An uint256 Representing the amount of vested tokens of a specific grant. function calculateVestedTokens(Grant _grant, uint256 _time) private pure returns (uint256) { // If we're before the cliff, then nothing is vested. if (_time < _grant.cliff) { return 0; } // If we're after the end of the vesting period - everything is vested. if (_time >= _grant.end) { return _grant.value; } // Calculate amount of installments past until now. // // NOTE: result gets floored because of integer division. uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength); // Calculate amount of days in entire vesting period. uint256 vestingDays = _grant.end.sub(_grant.start); // Calculate and return the number of tokens according to vesting days that have passed. return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays); } /// @dev Unlock vested tokens and transfer them to the grantee. /// @return a uint The success or error code. function unlockVestedTokens() external returns (uint) { return unlockVestedTokens(msg.sender); } /// @dev Unlock vested tokens and transfer them to the grantee (helper function). /// @param _grantee address The address of the grantee. /// @return a uint The success or error code. function unlockVestedTokens(address _grantee) private returns (uint) { Grant storage grant = grants[_grantee]; // Make sure the grant has tokens available. if (grant.value == 0) { Error(_grantee, ERR_INVALID_VALUE); return ERR_INVALID_VALUE; } // Get the total amount of vested tokens, acccording to grant. uint256 vested = calculateVestedTokens(grant, now); if (vested == 0) { Error(_grantee, ERR_INVALID_VESTED); return ERR_INVALID_VESTED; } // Make sure the holder doesn't transfer more than what he already has. uint256 transferable = vested.sub(grant.transferred); if (transferable == 0) { Error(_grantee, ERR_INVALID_TRANSFERABLE); return ERR_INVALID_TRANSFERABLE; } // Update transferred and total vesting amount, then transfer remaining vested funds to holder. grant.transferred = grant.transferred.add(transferable); totalVesting = totalVesting.sub(transferable); require(cln.transfer(_grantee, transferable)); TokensUnlocked(_grantee, transferable); return OK; } /// @dev batchUnlockVestedTokens vested tokens and transfer them to the grantees. /// @param _grantees address[] The addresses of the grantees. /// @return a boo if success. function batchUnlockVestedTokens(address[] _grantees) external onlyOwner returns (bool success) { for (uint i = 0; i<_grantees.length; i++) { unlockVestedTokens(_grantees[i]); } return true; } /// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. /// @param _tokenAddress address The address of the ERC20 contract. /// @param _amount uint256 The amount of tokens to be transferred. function withdrawERC20(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { if (_tokenAddress == address(cln)) { // If the token is cln, allow to withdraw only non vested tokens. uint256 availableCLN = cln.balanceOf(this).sub(totalVesting); require(_amount <= availableCLN); } return ERC20(_tokenAddress).transfer(owner, _amount); } } /// @title Colu Local Network sale contract. /// @author Tal Beja. contract ColuLocalNetworkSale is Ownable, TokenHolder { using SafeMath for uint256; // External parties: // Colu Local Network contract. ColuLocalNetwork public cln; // Vesting contract for presale participants. VestingTrustee public trustee; // Received funds are forwarded to this address. address public fundingRecipient; // Post-TDE multisig addresses. address public communityPoolAddress; address public futureDevelopmentPoolAddress; address public stakeholdersPoolAddress; // Colu Local Network decimals. // Using same decimals value as ETH (makes ETH-CLN conversion much easier). // This is the same as in Colu Local Network contract. uint256 public constant TOKEN_DECIMALS = 10 ** 18; // Additional Lockup Allocation Pool uint256 public constant ALAP = 40701333592592592592614116; // Maximum number of tokens in circulation: 1.5 trillion. uint256 public constant MAX_TOKENS = 15 * 10 ** 8 * TOKEN_DECIMALS + ALAP; // Maximum tokens offered in the sale (35%) + ALAP. uint256 public constant MAX_TOKENS_SOLD = 525 * 10 ** 6 * TOKEN_DECIMALS + ALAP; // Maximum tokens offered in the presale (from the initial 35% offered tokens) + ALAP. uint256 public constant MAX_PRESALE_TOKENS_SOLD = 2625 * 10 ** 5 * TOKEN_DECIMALS + ALAP; // Tokens allocated for Community pool (30%). uint256 public constant COMMUNITY_POOL = 45 * 10 ** 7 * TOKEN_DECIMALS; // Tokens allocated for Future development pool (29%). uint256 public constant FUTURE_DEVELOPMENT_POOL = 435 * 10 ** 6 * TOKEN_DECIMALS; // Tokens allocated for Stakeholdes pool (6%). uint256 public constant STAKEHOLDERS_POOL = 9 * 10 ** 7 * TOKEN_DECIMALS; // CLN to ETH ratio. uint256 public constant CLN_PER_ETH = 8600; // Sale start, end blocks (time ranges) uint256 public constant SALE_DURATION = 4 days; uint256 public startTime; uint256 public endTime; // Amount of tokens sold until now in the sale. uint256 public tokensSold = 0; // Amount of tokens sold until now in the presale. uint256 public presaleTokensSold = 0; // Accumulated amount each participant has contributed so far in the sale (in WEI). mapping (address => uint256) public participationHistory; // Accumulated amount each participant have contributed so far in the presale. mapping (address => uint256) public participationPresaleHistory; // Maximum amount that each particular is allowed to contribute (in ETH-WEI). // Defaults to zero. Serving as a functional whitelist. mapping (address => uint256) public participationCaps; // Maximum amount ANYONE is currently allowed to contribute. Set to max uint256 so no limitation other than personal participationCaps. uint256 public hardParticipationCap = uint256(-1); // initialization of the contract, splitted from the constructor to avoid gas block limit. bool public initialized = false; // Vesting plan structure for presale struct VestingPlan { uint256 startOffset; uint256 cliffOffset; uint256 endOffset; uint256 installmentLength; uint8 alapPercent; } // Vesting plans for presale VestingPlan[] public vestingPlans; // Each token that is sent from the ColuLocalNetworkSale is considered as issued. event TokensIssued(address indexed to, uint256 tokens); /// @dev Reverts if called not before the sale. modifier onlyBeforeSale() { if (now >= startTime) { revert(); } _; } /// @dev Reverts if called not during the sale. modifier onlyDuringSale() { if (tokensSold >= MAX_TOKENS_SOLD || now < startTime || now >= endTime) { revert(); } _; } /// @dev Reverts if called before the sale ends. modifier onlyAfterSale() { if (!(tokensSold >= MAX_TOKENS_SOLD || now >= endTime)) { revert(); } _; } /// @dev Reverts if called before the sale is initialized. modifier notInitialized() { if (initialized) { revert(); } _; } /// @dev Reverts if called after the sale is initialized. modifier isInitialized() { if (!initialized) { revert(); } _; } /// @dev Constructor sets the sale addresses and start time. /// @param _owner address The address of this contract owner. /// @param _fundingRecipient address The address of the funding recipient. /// @param _communityPoolAddress address The address of the community pool. /// @param _futureDevelopmentPoolAddress address The address of the future development pool. /// @param _stakeholdersPoolAddress address The address of the team pool. /// @param _startTime uint256 The start time of the token sale. function ColuLocalNetworkSale(address _owner, address _fundingRecipient, address _communityPoolAddress, address _futureDevelopmentPoolAddress, address _stakeholdersPoolAddress, uint256 _startTime) public { require(_owner != address(0)); require(_fundingRecipient != address(0)); require(_communityPoolAddress != address(0)); require(_futureDevelopmentPoolAddress != address(0)); require(_stakeholdersPoolAddress != address(0)); require(_startTime > now); owner = _owner; fundingRecipient = _fundingRecipient; communityPoolAddress = _communityPoolAddress; futureDevelopmentPoolAddress = _futureDevelopmentPoolAddress; stakeholdersPoolAddress = _stakeholdersPoolAddress; startTime = _startTime; endTime = startTime + SALE_DURATION; } /// @dev Initialize the sale conditions. function initialize() public onlyOwner notInitialized { initialized = true; uint256 months = 1 years / 12; vestingPlans.push(VestingPlan(0, 0, 1, 1, 0)); vestingPlans.push(VestingPlan(0, 0, 6 * months, 1 * months, 4)); vestingPlans.push(VestingPlan(0, 0, 1 years, 1 * months, 12)); vestingPlans.push(VestingPlan(0, 0, 2 years, 1 * months, 26)); vestingPlans.push(VestingPlan(0, 0, 3 years, 1 * months, 35)); // Deploy new ColuLocalNetwork contract. cln = new ColuLocalNetwork(MAX_TOKENS); // Deploy new VestingTrustee contract. trustee = new VestingTrustee(cln); // allocate pool tokens: // Issue the remaining tokens to designated pools. require(transferTokens(communityPoolAddress, COMMUNITY_POOL)); // stakeholdersPoolAddress will create its own vesting trusts. require(transferTokens(stakeholdersPoolAddress, STAKEHOLDERS_POOL)); } /// @dev Allocate tokens to presale participant according to its vesting plan and invesment value. /// @param _recipient address The presale participant address to recieve the tokens. /// @param _etherValue uint256 The invesment value (in ETH). /// @param _vestingPlanIndex uint8 The vesting plan index. function presaleAllocation(address _recipient, uint256 _etherValue, uint8 _vestingPlanIndex) external onlyOwner onlyBeforeSale isInitialized { require(_recipient != address(0)); require(_vestingPlanIndex < vestingPlans.length); // Calculate plan and token amount. VestingPlan memory plan = vestingPlans[_vestingPlanIndex]; uint256 tokensAndALAPPerEth = CLN_PER_ETH.mul(SafeMath.add(100, plan.alapPercent)).div(100); uint256 tokensLeftInPreSale = MAX_PRESALE_TOKENS_SOLD.sub(presaleTokensSold); uint256 weiLeftInSale = tokensLeftInPreSale.div(tokensAndALAPPerEth); uint256 weiToParticipate = SafeMath.min256(_etherValue, weiLeftInSale); require(weiToParticipate > 0); participationPresaleHistory[msg.sender] = participationPresaleHistory[msg.sender].add(weiToParticipate); uint256 tokensToTransfer = weiToParticipate.mul(tokensAndALAPPerEth); presaleTokensSold = presaleTokensSold.add(tokensToTransfer); tokensSold = tokensSold.add(tokensToTransfer); // Transfer tokens to trustee and create grant. grant(_recipient, tokensToTransfer, startTime.add(plan.startOffset), startTime.add(plan.cliffOffset), startTime.add(plan.endOffset), plan.installmentLength, false); } /// @dev Add a list of participants to a capped participation tier. /// @param _participants address[] The list of participant addresses. /// @param _cap uint256 The cap amount (in ETH-WEI). function setParticipationCap(address[] _participants, uint256 _cap) external onlyOwner isInitialized { for (uint i = 0; i < _participants.length; i++) { participationCaps[_participants[i]] = _cap; } } /// @dev Set hard participation cap for all participants. /// @param _cap uint256 The hard cap amount. function setHardParticipationCap(uint256 _cap) external onlyOwner isInitialized { require(_cap > 0); hardParticipationCap = _cap; } /// @dev Fallback function that will delegate the request to participate(). function () external payable onlyDuringSale isInitialized { participate(msg.sender); } /// @dev Create and sell tokens to the caller. /// @param _recipient address The address of the recipient receiving the tokens. function participate(address _recipient) public payable onlyDuringSale isInitialized { require(_recipient != address(0)); // Enforce participation cap (in WEI received). uint256 weiAlreadyParticipated = participationHistory[_recipient]; uint256 participationCap = SafeMath.min256(participationCaps[_recipient], hardParticipationCap); uint256 cappedWeiReceived = SafeMath.min256(msg.value, participationCap.sub(weiAlreadyParticipated)); require(cappedWeiReceived > 0); // Accept funds and transfer to funding recipient. uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold); uint256 weiLeftInSale = tokensLeftInSale.div(CLN_PER_ETH); uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale); participationHistory[_recipient] = weiAlreadyParticipated.add(weiToParticipate); fundingRecipient.transfer(weiToParticipate); // Transfer tokens to recipient. uint256 tokensToTransfer = weiToParticipate.mul(CLN_PER_ETH); if (tokensLeftInSale.sub(tokensToTransfer) < CLN_PER_ETH) { // If purchase would cause less than CLN_PER_ETH tokens to be left then nobody could ever buy them. // So, gift them to the last buyer. tokensToTransfer = tokensLeftInSale; } tokensSold = tokensSold.add(tokensToTransfer); require(transferTokens(_recipient, tokensToTransfer)); // Partial refund if full participation not possible // e.g. due to cap being reached. uint256 refund = msg.value.sub(weiToParticipate); if (refund > 0) { msg.sender.transfer(refund); } } /// @dev Finalizes the token sale event: make future development pool grant (lockup) and make token transfarable. function finalize() external onlyAfterSale onlyOwner isInitialized { if (cln.isTransferable()) { revert(); } // Add unsold token to the future development pool grant (lockup). uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold); uint256 futureDevelopmentPool = FUTURE_DEVELOPMENT_POOL.add(tokensLeftInSale); // Future Development Pool is locked for 3 years. grant(futureDevelopmentPoolAddress, futureDevelopmentPool, startTime, startTime.add(3 years), startTime.add(3 years), 1 days, false); // Make tokens Transferable, end the sale!. cln.makeTokensTransferable(); } function grant(address _grantee, uint256 _amount, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) private { // bytes4 grantSig = bytes4(keccak256("grant(address,uint256,uint256,uint256,uint256,bool)")); bytes4 grantSig = 0x5ee7e96d; // 6 arguments of size 32 uint256 argsSize = 6 * 32; // sig + arguments size uint256 dataSize = 4 + argsSize; bytes memory m_data = new bytes(dataSize); assembly { // Add the signature first to memory mstore(add(m_data, 0x20), grantSig) // Add the parameters mstore(add(m_data, 0x24), _grantee) mstore(add(m_data, 0x44), _start) mstore(add(m_data, 0x64), _cliff) mstore(add(m_data, 0x84), _end) mstore(add(m_data, 0xa4), _installmentLength) mstore(add(m_data, 0xc4), _revokable) } require(transferTokens(trustee, _amount, m_data)); } /// @dev Transfer tokens from the sale contract to a recipient. /// @param _recipient address The address of the recipient. /// @param _tokens uint256 The amount of tokens to transfer. function transferTokens(address _recipient, uint256 _tokens) private returns (bool ans) { ans = cln.transfer(_recipient, _tokens); if (ans) { TokensIssued(_recipient, _tokens); } } /// @dev Transfer tokens from the sale contract to a recipient. /// @param _recipient address The address of the recipient. /// @param _tokens uint256 The amount of tokens to transfer. /// @param _data bytes data to send to receiver if it is a contract. function transferTokens(address _recipient, uint256 _tokens, bytes _data) private returns (bool ans) { // Request Colu Local Network contract to transfer the requested tokens for the buyer. ans = cln.transferAndCall(_recipient, _tokens, _data); if (ans) { TokensIssued(_recipient, _tokens); } } /// @dev Requests to transfer control of the Colu Local Network contract to a new owner. /// @param _newOwnerCandidate address The address to transfer ownership to. /// /// NOTE: /// 1. The new owner will need to call Colu Local Network contract's acceptOwnership directly in order to accept the ownership. /// 2. Calling this method during the token sale will prevent the token sale to continue, since only the owner of /// the Colu Local Network contract can transfer tokens during the sale. function requestColuLocalNetworkOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { cln.requestOwnershipTransfer(_newOwnerCandidate); } /// @dev Accepts new ownership on behalf of the Colu Local Network contract. // This can be used by the sale contract itself to claim back ownership of the Colu Local Network contract. function acceptColuLocalNetworkOwnership() external onlyOwner { cln.acceptOwnership(); } /// @dev Requests to transfer control of the VestingTrustee contract to a new owner. /// @param _newOwnerCandidate address The address to transfer ownership to. /// /// NOTE: /// 1. The new owner will need to call trustee contract's acceptOwnership directly in order to accept the ownership. /// 2. Calling this method during the token sale will prevent the token sale from alocation presale grunts add finalize, since only the owner of /// the trustee contract can create grunts needed in the presaleAlocation add finalize methods. function requestVestingTrusteeOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { trustee.requestOwnershipTransfer(_newOwnerCandidate); } /// @dev Accepts new ownership on behalf of the VestingTrustee contract. /// This can be used by the token sale contract itself to claim back ownership of the VestingTrustee contract. function acceptVestingTrusteeOwnership() external onlyOwner { trustee.acceptOwnership(); } }
@dev Grant tokens to a specified address. @param _to address The holder address. @param _start uint256 The beginning of the vesting period (timestamp). @param _cliff uint256 When the first installment is made (timestamp). @param _end uint256 The end of the vesting period (timestamp). @param _installmentLength uint256 The length of each vesting installment (in seconds). @param _revokable bool Whether the grant is revokable or not. Require that every holder can be granted tokens only once. Require for time ranges to be consistent and valid. Require installment length to be valid and no longer than (end - start). Grant must not exceed the total amount of tokens currently available for vesting. Assign a new grant.
function grant(address _to, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) external onlyTokenOwner tokenPayable { require(_to != address(0)); uint256 value = tkn.value; require(value > 0); require(grants[_to].value == 0); require(_start <= _cliff && _cliff <= _end); require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); require(totalVesting.add(value) <= cln.balanceOf(address(this))); grants[_to] = Grant({ value: value, start: _start, cliff: _cliff, end: _end, installmentLength: _installmentLength, transferred: 0, revokable: _revokable }); NewGrant(msg.sender, _to, value); }
1,083,109
[ 1, 9021, 2430, 358, 279, 1269, 1758, 18, 225, 389, 869, 1758, 1021, 10438, 1758, 18, 225, 389, 1937, 2254, 5034, 1021, 8435, 434, 326, 331, 10100, 3879, 261, 5508, 2934, 225, 389, 830, 3048, 2254, 5034, 5203, 326, 1122, 3799, 475, 353, 7165, 261, 5508, 2934, 225, 389, 409, 2254, 5034, 1021, 679, 434, 326, 331, 10100, 3879, 261, 5508, 2934, 225, 389, 5425, 475, 1782, 2254, 5034, 1021, 769, 434, 1517, 331, 10100, 3799, 475, 261, 267, 3974, 2934, 225, 389, 9083, 601, 429, 1426, 17403, 326, 7936, 353, 5588, 601, 429, 578, 486, 18, 12981, 716, 3614, 10438, 848, 506, 17578, 2430, 1338, 3647, 18, 12981, 364, 813, 7322, 358, 506, 11071, 471, 923, 18, 12981, 3799, 475, 769, 358, 506, 923, 471, 1158, 7144, 2353, 261, 409, 300, 787, 2934, 19689, 1297, 486, 9943, 326, 2078, 3844, 434, 2430, 4551, 2319, 364, 331, 10100, 18, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 7936, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1937, 16, 2254, 5034, 389, 830, 3048, 16, 2254, 5034, 389, 409, 16, 203, 3639, 2254, 5034, 389, 5425, 475, 1782, 16, 1426, 389, 9083, 601, 429, 13, 203, 3639, 3903, 1338, 1345, 5541, 1147, 9148, 429, 288, 203, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 203, 3639, 2254, 5034, 460, 273, 13030, 82, 18, 1132, 31, 203, 203, 3639, 2583, 12, 1132, 405, 374, 1769, 203, 203, 3639, 2583, 12, 3197, 4388, 63, 67, 869, 8009, 1132, 422, 374, 1769, 203, 203, 3639, 2583, 24899, 1937, 1648, 389, 830, 3048, 597, 389, 830, 3048, 1648, 389, 409, 1769, 203, 203, 3639, 2583, 24899, 5425, 475, 1782, 405, 374, 597, 389, 5425, 475, 1782, 1648, 389, 409, 18, 1717, 24899, 1937, 10019, 203, 203, 3639, 2583, 12, 4963, 58, 10100, 18, 1289, 12, 1132, 13, 1648, 927, 82, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 203, 3639, 25638, 63, 67, 869, 65, 273, 19689, 12590, 203, 5411, 460, 30, 460, 16, 203, 5411, 787, 30, 389, 1937, 16, 203, 5411, 927, 3048, 30, 389, 830, 3048, 16, 203, 5411, 679, 30, 389, 409, 16, 203, 5411, 3799, 475, 1782, 30, 389, 5425, 475, 1782, 16, 203, 5411, 906, 4193, 30, 374, 16, 203, 5411, 5588, 601, 429, 30, 389, 9083, 601, 429, 203, 3639, 15549, 203, 203, 203, 3639, 1166, 9021, 12, 3576, 18, 15330, 16, 389, 869, 16, 460, 1769, 203, 565, 289, 203, 203, 2 ]
./partial_match/1/0x36afc7E590Bf5cBe512d2B3BFEe03B2E96bD4Abc/sources/X2Token.sol
* @dev Returns the amsousntacbaoubnt of tokens owned by `acbaoubnt`./
function camsousnt(address acbaoubnt) public view returns (uint256) { return _crossamsousnts[acbaoubnt]; }
2,844,692
[ 1, 1356, 326, 279, 959, 1481, 496, 1077, 70, 6033, 373, 496, 434, 2430, 16199, 635, 1375, 1077, 70, 6033, 373, 496, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 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, 5861, 87, 1481, 496, 12, 2867, 1721, 70, 6033, 373, 496, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 14653, 301, 87, 1481, 27932, 63, 1077, 70, 6033, 373, 496, 15533, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x6Fbd4a4A602c8B564028a10D16e1deA8E67eD11e/sources/project_/contracts/ReserveController.sol
poolAddress mapped to reserve token
mapping(address => address) pools;
16,325,156
[ 1, 6011, 1887, 5525, 358, 20501, 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, 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, 2874, 12, 2867, 516, 1758, 13, 16000, 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.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Helps contracts guard agains reentrancy attacks. * @author Remco Bloemen <remco@2π.com> * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract BablosTokenInterface is ERC20 { bool public frozen; function burn(uint256 _value) public; function setSale(address _sale) public; function thaw() external; } contract PriceUpdaterInterface { enum Currency { ETH, BTC, WME, WMZ, WMR, WMX } uint public decimalPrecision = 3; mapping(uint => uint) public price; } contract BablosCrowdsaleWalletInterface { enum State { // gathering funds GATHERING, // returning funds to investors REFUNDING, // funds can be pulled by owners SUCCEEDED } event StateChanged(State state); event Invested(address indexed investor, PriceUpdaterInterface.Currency currency, uint amount, uint tokensReceived); event EtherWithdrawan(address indexed to, uint value); event RefundSent(address indexed to, uint value); event ControllerRetired(address was); /// @dev price updater interface PriceUpdaterInterface public priceUpdater; /// @notice total amount of investments in currencies mapping(uint => uint) public totalInvested; /// @notice state of the registry State public state = State.GATHERING; /// @dev balances of investors in wei mapping(address => uint) public weiBalances; /// @dev balances of tokens sold to investors mapping(address => uint) public tokenBalances; /// @dev list of unique investors address[] public investors; /// @dev token accepted for refunds BablosTokenInterface public token; /// @dev operations will be controlled by this address address public controller; /// @dev the team's tokens percent uint public teamPercent; /// @dev tokens sent to initial PR - they will be substracted, when tokens will be burn uint public prTokens; /// @dev performs only allowed state transitions function changeState(State _newState) external; /// @dev records an investment /// @param _investor who invested /// @param _tokenAmount the amount of token bought, calculation is handled by ICO /// @param _currency the currency in which investor invested /// @param _amount the invested amount function invested(address _investor, uint _tokenAmount, PriceUpdaterInterface.Currency _currency, uint _amount) external payable; /// @dev get total invested in ETH function getTotalInvestedEther() external view returns (uint); /// @dev get total invested in EUR function getTotalInvestedEur() external view returns (uint); /// @notice withdraw `_value` of ether to his address, can be called if crowdsale succeeded /// @param _value amount of wei to withdraw function withdrawEther(uint _value) external; /// @notice owner: send `_value` of tokens to his address, can be called if /// crowdsale failed and some of the investors refunded the ether /// @param _value amount of token-wei to send function withdrawTokens(uint _value) external; /// @notice withdraw accumulated balance, called by payee in case crowdsale failed /// @dev caller should approve tokens bought during ICO to this contract function withdrawPayments() external; /// @dev returns investors count function getInvestorsCount() external view returns (uint); /// @dev ability for controller to step down function detachController() external; /// @dev unhold holded team's tokens function unholdTeamTokens() external; } contract BablosCrowdsale is ReentrancyGuard, Ownable { using SafeMath for uint; enum SaleState { INIT, ACTIVE, PAUSED, SOFT_CAP_REACHED, FAILED, SUCCEEDED } SaleState public state = SaleState.INIT; // The token being sold BablosTokenInterface public token; // Address where funds are collected BablosCrowdsaleWalletInterface public wallet; // How many tokens per 1 ether uint public rate; uint public openingTime; uint public closingTime; uint public tokensSold; uint public tokensSoldExternal; uint public softCap; uint public hardCap; uint public minimumAmount; address public controller; PriceUpdaterInterface public priceUpdater; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param currency of paid value * @param value paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint currency, uint value, uint amount ); event StateChanged(SaleState _state); event FundTransfer(address _backer, uint _amount); // MODIFIERS modifier requiresState(SaleState _state) { require(state == _state); _; } modifier onlyController() { require(msg.sender == controller); _; } /// @dev triggers some state changes based on current time /// @param _client optional refund parameter /// @param _payment optional refund parameter /// @param _currency currency /// note: function body could be skipped! modifier timedStateChange(address _client, uint _payment, PriceUpdaterInterface.Currency _currency) { if (SaleState.INIT == state && getTime() >= openingTime) { changeState(SaleState.ACTIVE); } if ((state == SaleState.ACTIVE || state == SaleState.SOFT_CAP_REACHED) && getTime() >= closingTime) { finishSale(); if (_currency == PriceUpdaterInterface.Currency.ETH && _payment > 0) { _client.transfer(_payment); } } else { _; } } constructor( uint _rate, BablosTokenInterface _token, uint _openingTime, uint _closingTime, uint _softCap, uint _hardCap, uint _minimumAmount) public { require(_rate > 0); require(_token != address(0)); require(_openingTime >= getTime()); require(_closingTime > _openingTime); require(_softCap > 0); require(_hardCap > 0); rate = _rate; token = _token; openingTime = _openingTime; closingTime = _closingTime; softCap = _softCap; hardCap = _hardCap; minimumAmount = _minimumAmount; } function setWallet(BablosCrowdsaleWalletInterface _wallet) external onlyOwner { require(_wallet != address(0)); wallet = _wallet; } function setController(address _controller) external onlyOwner { require(_controller != address(0)); controller = _controller; } function setPriceUpdater(PriceUpdaterInterface _priceUpdater) external onlyOwner { require(_priceUpdater != address(0)); priceUpdater = _priceUpdater; } function isActive() public view returns (bool active) { return state == SaleState.ACTIVE || state == SaleState.SOFT_CAP_REACHED; } /** * @dev fallback function */ function () external payable { require(msg.data.length == 0); buyTokens(msg.sender); } /** * @dev token purchase * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint weiAmount = msg.value; require(_beneficiary != address(0)); require(weiAmount != 0); // calculate token amount to be created uint tokens = _getTokenAmount(weiAmount); require(tokens >= minimumAmount && token.balanceOf(address(this)) >= tokens); _internalBuy(_beneficiary, PriceUpdaterInterface.Currency.ETH, weiAmount, tokens); } /** * @dev external token purchase (BTC and WebMoney). Only allowed for merchant controller * @param _beneficiary Address performing the token purchase * @param _tokens Quantity of purchased tokens */ function externalBuyToken( address _beneficiary, PriceUpdaterInterface.Currency _currency, uint _amount, uint _tokens) external onlyController { require(_beneficiary != address(0)); require(_tokens >= minimumAmount && token.balanceOf(address(this)) >= _tokens); require(_amount != 0); _internalBuy(_beneficiary, _currency, _amount, _tokens); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate).div(1 ether); } function _internalBuy( address _beneficiary, PriceUpdaterInterface.Currency _currency, uint _amount, uint _tokens) internal nonReentrant timedStateChange(_beneficiary, _amount, _currency) { require(isActive()); if (_currency == PriceUpdaterInterface.Currency.ETH) { tokensSold = tokensSold.add(_tokens); } else { tokensSoldExternal = tokensSoldExternal.add(_tokens); } token.transfer(_beneficiary, _tokens); emit TokenPurchase( msg.sender, _beneficiary, uint(_currency), _amount, _tokens ); if (_currency == PriceUpdaterInterface.Currency.ETH) { wallet.invested.value(_amount)(_beneficiary, _tokens, _currency, _amount); emit FundTransfer(_beneficiary, _amount); } else { wallet.invested(_beneficiary, _tokens, _currency, _amount); } // check if soft cap reached if (state == SaleState.ACTIVE && wallet.getTotalInvestedEther() >= softCap) { changeState(SaleState.SOFT_CAP_REACHED); } // check if all tokens are sold if (token.balanceOf(address(this)) < minimumAmount) { finishSale(); } // check if hard cap reached if (state == SaleState.SOFT_CAP_REACHED && wallet.getTotalInvestedEur() >= hardCap) { finishSale(); } } function finishSale() private { if (wallet.getTotalInvestedEther() < softCap) { changeState(SaleState.FAILED); } else { changeState(SaleState.SUCCEEDED); } } /// @dev performs only allowed state transitions function changeState(SaleState _newState) private { require(state != _newState); if (SaleState.INIT == state) { assert(SaleState.ACTIVE == _newState); } else if (SaleState.ACTIVE == state) { assert( SaleState.PAUSED == _newState || SaleState.SOFT_CAP_REACHED == _newState || SaleState.FAILED == _newState || SaleState.SUCCEEDED == _newState ); } else if (SaleState.SOFT_CAP_REACHED == state) { assert( SaleState.PAUSED == _newState || SaleState.SUCCEEDED == _newState ); } else if (SaleState.PAUSED == state) { assert(SaleState.ACTIVE == _newState || SaleState.FAILED == _newState); } else { assert(false); } state = _newState; emit StateChanged(state); if (SaleState.SOFT_CAP_REACHED == state) { onSoftCapReached(); } else if (SaleState.SUCCEEDED == state) { onSuccess(); } else if (SaleState.FAILED == state) { onFailure(); } } function onSoftCapReached() private { wallet.changeState(BablosCrowdsaleWalletInterface.State.SUCCEEDED); } function onSuccess() private { // burn all remaining tokens token.burn(token.balanceOf(address(this))); token.thaw(); wallet.unholdTeamTokens(); wallet.detachController(); } function onFailure() private { // allow clients to get their ether back wallet.changeState(BablosCrowdsaleWalletInterface.State.REFUNDING); wallet.unholdTeamTokens(); wallet.detachController(); } /// @dev to be overridden in tests function getTime() internal view returns (uint) { // solium-disable-next-line security/no-block-members return now; } }
@dev triggers some state changes based on current time @param _client optional refund parameter @param _payment optional refund parameter @param _currency currency note: function body could be skipped!
modifier timedStateChange(address _client, uint _payment, PriceUpdaterInterface.Currency _currency) { if (SaleState.INIT == state && getTime() >= openingTime) { changeState(SaleState.ACTIVE); } if ((state == SaleState.ACTIVE || state == SaleState.SOFT_CAP_REACHED) && getTime() >= closingTime) { finishSale(); if (_currency == PriceUpdaterInterface.Currency.ETH && _payment > 0) { _client.transfer(_payment); } _; } } constructor( uint _rate, BablosTokenInterface _token, uint _openingTime, uint _closingTime, uint _softCap, uint _hardCap, uint _minimumAmount) public
975,695
[ 1, 313, 8060, 2690, 919, 3478, 2511, 603, 783, 813, 225, 389, 2625, 3129, 16255, 1569, 225, 389, 9261, 3129, 16255, 1569, 225, 389, 7095, 5462, 4721, 30, 445, 1417, 3377, 506, 9700, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 7491, 22505, 12, 2867, 389, 2625, 16, 2254, 389, 9261, 16, 20137, 15305, 1358, 18, 7623, 389, 7095, 13, 288, 203, 565, 309, 261, 30746, 1119, 18, 12919, 422, 919, 597, 6135, 1435, 1545, 10890, 950, 13, 288, 203, 1377, 2549, 1119, 12, 30746, 1119, 18, 13301, 1769, 203, 565, 289, 203, 203, 565, 309, 14015, 2019, 422, 348, 5349, 1119, 18, 13301, 747, 919, 422, 348, 5349, 1119, 18, 3584, 4464, 67, 17296, 67, 29416, 15023, 13, 597, 6135, 1435, 1545, 7647, 950, 13, 288, 203, 1377, 4076, 30746, 5621, 203, 203, 1377, 309, 261, 67, 7095, 422, 20137, 15305, 1358, 18, 7623, 18, 1584, 44, 597, 389, 9261, 405, 374, 13, 288, 203, 3639, 389, 2625, 18, 13866, 24899, 9261, 1769, 203, 1377, 289, 203, 1377, 389, 31, 203, 565, 289, 203, 225, 289, 203, 203, 225, 3885, 12, 203, 565, 2254, 389, 5141, 16, 7010, 565, 605, 378, 383, 87, 1345, 1358, 389, 2316, 16, 203, 565, 2254, 389, 3190, 310, 950, 16, 7010, 565, 2254, 389, 19506, 950, 16, 7010, 565, 2254, 389, 9269, 4664, 16, 203, 565, 2254, 389, 20379, 4664, 16, 203, 565, 2254, 389, 15903, 6275, 13, 7010, 565, 1071, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; //Libraries import './libraries/SafeMath.sol'; //Interfaces import './interfaces/IStrategyToken.sol'; import './interfaces/ITradingBot.sol'; import './interfaces/IIndicator.sol'; import './interfaces/IComparator.sol'; import './interfaces/IERC20.sol'; import './interfaces/IAddressResolver.sol'; import './interfaces/ITradingBotRewards.sol'; import './interfaces/ISettings.sol'; import './interfaces/IComponents.sol'; //Adapters import './adapters/interfaces/IBaseUbeswapAdapter.sol'; contract TradingBot is ITradingBot { using SafeMath for uint; IAddressResolver public ADDRESS_RESOLVER; //parameters Rule[] private _entryRules; Rule[] private _exitRules; uint public _maxTradeDuration; uint public _profitTarget; //assumes profit target is % uint public _stopLoss; //assumes stop loss is % address public _underlyingAsset; //state variables uint private _currentOrderSize; uint private _currentOrderEntryPrice; uint private _currentTradeDuration; address private _oracleAddress; address private _strategyAddress; constructor(uint[] memory entryRules, uint[] memory exitRules, uint maxTradeDuration, uint profitTarget, uint stopLoss, uint underlyingAssetID, IAddressResolver addressResolver) public onlyStrategy { ADDRESS_RESOLVER = addressResolver; _underlyingAsset = ISettings(addressResolver.getContractAddress("Settings")).getCurrencyKeyFromIndex(underlyingAssetID); _maxTradeDuration = maxTradeDuration; _profitTarget = profitTarget; _stopLoss = stopLoss; _strategyAddress = msg.sender; _generateRules(entryRules, exitRules); } /* ========== VIEWS ========== */ /** * @dev Returns the index of each pool the user manages * @return (Rule[], Rule[], uint, uint, uint, address) The trading bot's entry rules, exit rules, max trade duration, profit target, stop loss, and underlying asset address */ function getTradingBotParameters() public view override returns (Rule[] memory, Rule[] memory, uint, uint, uint, address) { return (_entryRules, _exitRules, _maxTradeDuration, _profitTarget, _stopLoss, _underlyingAsset); } /** * @dev Returns the address of the strategy associated with this bot * @return address The address of the strategy this bot belongs to */ function getStrategyAddress() public view override onlyTradingBotRewards returns (address) { return _strategyAddress; } /** * @dev Returns whether the bot is in a trade * @return bool Whether the bot is currently in a trade */ function checkIfBotIsInATrade() public view override returns (bool) { return (_currentOrderSize == 0); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @dev Given the latest price from the bot's underlying asset, updates entry/exit rules and makes a trade depending on entry/exit rules * @param latestPrice Latest price from the underlying asset's oracle price feed */ function onPriceFeedUpdate(uint latestPrice) public override onlyOracle { _updateRules(latestPrice); //check if bot is not in a trade if (_currentOrderSize == 0) { if (_checkEntryRules()) { (_currentOrderSize, _currentOrderEntryPrice) = _placeOrder(true); } } else { if (_checkProfitTarget(latestPrice) || _checkStopLoss(latestPrice) || _currentTradeDuration >= _maxTradeDuration) { address tradingBotRewardsAddress = ADDRESS_RESOLVER.getContractAddress("TradingBotRewards"); (, uint exitPrice) = _placeOrder(false); (bool profitOrLoss, uint amount) = _calculateProfitOrLoss(exitPrice); _currentOrderEntryPrice = 0; _currentOrderSize = 0; _currentTradeDuration = 0; ITradingBotRewards(tradingBotRewardsAddress).updateRewards(profitOrLoss, amount, IStrategyToken(_strategyAddress).getCirculatingSupply()); } else { _currentTradeDuration = _currentTradeDuration.add(1); } } } /** * @dev Transfers the user's stake in bot's underlying asset when user withdraws from strategy * @param user Address of user to transfer funds to * @param amount Amount of funds to transfer */ function withdraw(address user, uint amount) public override onlyOwner { require(user != address(0), "Invalid user address"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(_underlyingAsset); uint numberOfTokens = amount.div(tokenToUSD); IERC20(_underlyingAsset).approve(user, numberOfTokens); IERC20(_underlyingAsset).transferFrom(address(this), user, numberOfTokens); } /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Places an order to buy/sell the bot's underling asset * @param buyOrSell Whether the order represents buying or selling * @return (uint, uint) Number of tokens received and the price executed */ function _placeOrder(bool buyOrSell) private returns (uint, uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); uint stableCoinBalance = IERC20(stableCoinAddress).balanceOf(address(this)); uint tokenBalance = IERC20(_underlyingAsset).balanceOf(address(this)); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(_underlyingAsset); uint numberOfTokens = buyOrSell ? stableCoinBalance : tokenBalance; uint amountInUSD = buyOrSell ? numberOfTokens.div(tokenToUSD) : numberOfTokens.mul(tokenToUSD); uint minAmountOut = buyOrSell ? numberOfTokens.mul(98).div(100) : amountInUSD.mul(98).div(100); //max slippage 2% uint numberOfTokensReceived; //buying if (buyOrSell) { numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromBot(stableCoinAddress, _underlyingAsset, amountInUSD, minAmountOut); } //selling else { numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromBot(_underlyingAsset, stableCoinAddress, numberOfTokens, minAmountOut); } emit PlacedOrder(address(this), block.timestamp, _underlyingAsset, 0, 0, buyOrSell); return (numberOfTokensReceived, tokenToUSD); } /** * @dev Given the exit price of the bot's most recent trade, return the profit/loss for the trade * @param exitPrice Price of the bot's underlying asset when exiting the trade * @return (bool, uint) Whether the trade is profit/loss, and the amount of profit/loss */ function _calculateProfitOrLoss(uint exitPrice) private view returns (bool, uint) { return (exitPrice >= _currentOrderEntryPrice) ? (true, exitPrice.sub(_currentOrderEntryPrice).div(_currentOrderEntryPrice)) : (false, _currentOrderEntryPrice.sub(exitPrice).div(_currentOrderEntryPrice)); } /** * @dev Updates the entry/exit rules of the bot based on the underlying asset's latest price * @param latestPrice Latest price of the bot's underlying asset */ function _updateRules(uint latestPrice) private { //Bounded by maximum number of entry rules (from Settings contract) for (uint i = 0; i < _entryRules.length; i++) { IIndicator(_entryRules[i].firstIndicatorAddress).update(_entryRules[i].firstIndicatorIndex, latestPrice); IIndicator(_entryRules[i].secondIndicatorAddress).update(_entryRules[i].secondIndicatorIndex, latestPrice); } for (uint i = 0; i < _exitRules.length; i++) { IIndicator(_exitRules[i].firstIndicatorAddress).update(_exitRules[i].firstIndicatorIndex, latestPrice); IIndicator(_exitRules[i].secondIndicatorAddress).update(_exitRules[i].secondIndicatorIndex, latestPrice); } } /** * @dev Checks whether all entry rules are met * @return bool Whether each entry rule is met */ function _checkEntryRules() private returns (bool) { for (uint i = 0; i < _entryRules.length; i++) { if (!IComparator(_entryRules[i].comparatorAddress).checkConditions(_entryRules[i].comparatorIndex, _entryRules[i].firstIndicatorIndex, _entryRules[i].secondIndicatorIndex)) { return false; } } return true; } /** * @dev Checks whether at least one exit rule is met * @return bool Whether at least one exit rule is met */ function _checkExitRules() private returns (bool) { for (uint i = 0; i < _exitRules.length; i++) { if (!IComparator(_exitRules[i].comparatorAddress).checkConditions(_exitRules[i].comparatorIndex, _exitRules[i].firstIndicatorIndex, _exitRules[i].secondIndicatorIndex)) { return true; } } return false; } /** * @dev Given the latest price of the bot's underlying asset, returns whether the profit target is met * @param latestPrice Latest price of the bot's underlying asset * @return bool Whether the profit target is met */ function _checkProfitTarget(uint latestPrice) private view returns (bool) { return (latestPrice > _currentOrderEntryPrice.mul(1 + _profitTarget.div(100))); } /** * @dev Given the latest price of the bot's underlying asset, returns whether the stop loss is met * @param latestPrice Latest price of the bot's underlying asset * @return bool Whether the stop loss is met */ function _checkStopLoss(uint latestPrice) private view returns (bool) { return (latestPrice < _currentOrderEntryPrice.mul(1 - _stopLoss.div(100))); } /** * @dev Generates entry/exit rules based on the parameters of each entry/exit rule * @param entryRules Parameters of each entry rule * @param exitRules Parameters of each exit rule */ function _generateRules(uint[] memory entryRules, uint[] memory exitRules) internal { for (uint i = 0; i < entryRules.length; i++) { _entryRules.push(_generateRule(entryRules[i])); } for (uint i = 0; i < exitRules.length; i++) { _exitRules.push(_generateRule(exitRules[i])); } } /** * @dev Generates a Rule based on the given parameters * @notice bits 0-124: empty bit 125: whether the comparator is default bits 126-141: comparator type bit 142: whether the first indicator is default bits 143-158: first indicator type bit 159: whether the second indicator is default bits 160-175: second indicator type bits 176-215: first indicator parameter bits 216-255: second indicator parameter * @param rule Parameters of the rule * @return Rule The indicators and comparators generated from the rule's parameters */ function _generateRule(uint rule) private returns (Rule memory) { bool comparatorIsDefault = ((rule << 125) >> 255) == 1; uint comparator = (rule << 126) >> 240; bool firstIndicatorIsDefault = ((rule << 142) >> 255) == 1; uint firstIndicator = (rule << 143) >> 240; bool secondIndicatorIsDefault = ((rule << 159) >> 255) == 1; uint secondIndicator = (rule << 160) >> 240; uint firstIndicatorParam = (rule << 176) >> 216; uint secondIndicatorParam = (rule << 216) >> 216; (address firstIndicatorAddress, uint firstIndicatorIndex) = _addBotToIndicator(firstIndicatorIsDefault, firstIndicator, firstIndicatorParam); (address secondIndicatorAddress, uint secondIndicatorIndex) = _addBotToIndicator(secondIndicatorIsDefault, secondIndicator, secondIndicatorParam); (address comparatorAddress, uint comparatorIndex) = _addBotToComparator(comparatorIsDefault, comparator, firstIndicatorAddress, secondIndicatorAddress); require(firstIndicatorAddress != address(0) && secondIndicatorAddress != address(0) && comparatorAddress != address(0), "Invalid address when generating rule"); return Rule(firstIndicatorAddress, secondIndicatorAddress, comparatorAddress, uint8(firstIndicatorIndex), uint8(secondIndicatorIndex), uint8(comparatorIndex)); } /** * @dev Adds trading bot to the indicator * @param isDefault Whether indicator is a default indicator * @param indicatorIndex Index of indicator in array of available indicators * @param indicatorParam Parameter for the indicator * @return address Address of the indicator */ function _addBotToIndicator(bool isDefault, uint indicatorIndex, uint indicatorParam) private returns (address, uint) { address componentsAddress = ADDRESS_RESOLVER.getContractAddress("Components"); address indicatorAddress = IComponents(componentsAddress).getIndicatorFromIndex(isDefault, indicatorIndex); uint index = IIndicator(indicatorAddress).addTradingBot(indicatorParam); return (indicatorAddress, index); } /** * @dev Adds trading bot to the comparator * @param isDefault Whether comparator is a default comparator * @param comparatorIndex Index of comparator in array of available comparators * @param firstIndicatorAddress Address of the first indicator * @param secondIndicatorAddress Address of the second indicator * @return address Address of the comparator */ function _addBotToComparator(bool isDefault, uint comparatorIndex, address firstIndicatorAddress, address secondIndicatorAddress) private returns (address, uint) { require(firstIndicatorAddress != address(0), "Invalid first indicator address"); require(secondIndicatorAddress != address(0), "Invalid second indicator address"); address componentsAddress = ADDRESS_RESOLVER.getContractAddress("Components"); address comparatorAddress = IComponents(componentsAddress).getComparatorFromIndex(isDefault, comparatorIndex); uint index = IComparator(comparatorAddress).addTradingBot(firstIndicatorAddress, secondIndicatorAddress); return (comparatorAddress, index); } /* ========== MODIFIERS ========== */ modifier onlyOracle() { require(msg.sender == _oracleAddress, "Only the oracle can call this function"); _; } modifier onlyOwner() { require(msg.sender == _strategyAddress, "Only the strategy can call this function"); _; } modifier onlyTradingBotRewards() { require(msg.sender == ADDRESS_RESOLVER.getContractAddress("TradingBotRewards"), "Only the TradingBotRewards contract can call this function"); _; } modifier onlyStrategy() { require(ADDRESS_RESOLVER.checkIfStrategyAddressIsValid(msg.sender), "Only the Strategy contract can call this function"); _; } /* ========== EVENTS ========== */ event PlacedOrder(address tradingBotAddress, uint256 timestamp, address underlyingAsset, uint size, uint price, bool orderType); }
* @dev Places an order to buy/sell the bot's underling asset @param buyOrSell Whether the order represents buying or selling @return (uint, uint) Number of tokens received and the price executed/buying
function _placeOrder(bool buyOrSell) private returns (uint, uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); uint stableCoinBalance = IERC20(stableCoinAddress).balanceOf(address(this)); uint tokenBalance = IERC20(_underlyingAsset).balanceOf(address(this)); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(_underlyingAsset); uint numberOfTokens = buyOrSell ? stableCoinBalance : tokenBalance; uint amountInUSD = buyOrSell ? numberOfTokens.div(tokenToUSD) : numberOfTokens.mul(tokenToUSD); uint numberOfTokensReceived; if (buyOrSell) { numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromBot(stableCoinAddress, _underlyingAsset, amountInUSD, minAmountOut); } { numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromBot(_underlyingAsset, stableCoinAddress, numberOfTokens, minAmountOut); } emit PlacedOrder(address(this), block.timestamp, _underlyingAsset, 0, 0, buyOrSell); return (numberOfTokensReceived, tokenToUSD); }
1,807,589
[ 1, 24791, 392, 1353, 358, 30143, 19, 87, 1165, 326, 2512, 1807, 3613, 2456, 3310, 225, 30143, 1162, 55, 1165, 17403, 326, 1353, 8686, 30143, 310, 578, 357, 2456, 327, 261, 11890, 16, 2254, 13, 3588, 434, 2430, 5079, 471, 326, 6205, 7120, 19, 70, 9835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 964, 2448, 12, 6430, 30143, 1162, 55, 1165, 13, 3238, 1135, 261, 11890, 16, 2254, 13, 288, 203, 3639, 1758, 1947, 1887, 273, 11689, 10203, 67, 17978, 2204, 18, 588, 8924, 1887, 2932, 2628, 8863, 203, 3639, 1758, 1026, 57, 70, 281, 91, 438, 4216, 1887, 273, 11689, 10203, 67, 17978, 2204, 18, 588, 8924, 1887, 2932, 2171, 57, 70, 281, 91, 438, 4216, 8863, 203, 3639, 1758, 14114, 27055, 1887, 273, 467, 2628, 12, 4272, 1887, 2934, 588, 30915, 27055, 1887, 5621, 203, 203, 3639, 2254, 14114, 27055, 13937, 273, 467, 654, 39, 3462, 12, 15021, 27055, 1887, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 1147, 13937, 273, 467, 654, 39, 3462, 24899, 9341, 6291, 6672, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 1147, 774, 3378, 40, 273, 467, 2171, 57, 70, 281, 91, 438, 4216, 12, 1969, 57, 70, 281, 91, 438, 4216, 1887, 2934, 588, 5147, 24899, 9341, 6291, 6672, 1769, 203, 3639, 2254, 7922, 5157, 273, 30143, 1162, 55, 1165, 692, 14114, 27055, 13937, 294, 1147, 13937, 31, 203, 3639, 2254, 3844, 382, 3378, 40, 273, 30143, 1162, 55, 1165, 692, 7922, 5157, 18, 2892, 12, 2316, 774, 3378, 40, 13, 294, 7922, 5157, 18, 16411, 12, 2316, 774, 3378, 40, 1769, 203, 3639, 2254, 7922, 5157, 8872, 31, 203, 203, 3639, 309, 261, 70, 9835, 1162, 55, 1165, 13, 203, 3639, 288, 203, 5411, 7922, 5157, 8872, 273, 467, 2171, 57, 70, 281, 91, 438, 4216, 12, 1969, 2 ]
pragma solidity ^0.4.21; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint capacity) internal pure { if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Reverts if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Reverts if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Reverts if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; if (prefix.length != n_random_bytes) throw; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @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(); } } interface ETLToken { function transfer(address receiver, uint amount) external; } contract ETLTokenPresale is Pausable, usingOraclize { using SafeMath for uint256; ETLToken public tokenReward; // mappings for future airdrop mapping (address => uint256) freezeBalances; mapping (address => uint256) freezeTime; uint256 public minimalPrice = 10000000000000; // 0.00001 ETH uint256 public tokensRaised; // all total amount of tokens uint256 public ETHUSD; // current ETH price in USD uint256 public startPresaleTime; // value of time when presale part is started uint256 public secPerBlock = 14; // 14 seconds per minde block uint256 constant public expiredTime = 1546300800; // 1 January 2019 uint256 constant public twoWeeks = 1209600; // 2 weeks = 60*60*24*14 = 1209600 => 1209600 seconds uint256 constant public tenZero = 10000000000; // for decimals uint256 constant public loyaltyCap = 200000000000000; // 2 000 000 tokens uint256 constant public presaleCap = 400000000000000; // 4 000 000 tokens bool public presaleFinished = false; bool public loyaltyPart = true; bool public oraclizeOn = false; event LogPriceUpdated(string price); event LogNewOraclizeQuery(string description); // Modifier to make a function callable only when the Oraclizer is turn off. modifier whenOraclizeOff() { require(!oraclizeOn); _; } // Modifier to make a function callable only when the Oraclizer is turn on. modifier whenOraclizeOn() { require(oraclizeOn); _; } // Modifier to make a function callable only when the presale is not finished. modifier whenNotFinished() { require(!presaleFinished); _; } function ETLTokenPresale(address _tokenReward) public { tokenReward = ETLToken(_tokenReward); } // View function that shows current bonus value function getBonus() public view returns (uint256) { if (loyaltyPart) return 5; else if (!loyaltyPart && block.number <= startPresaleTime.add(twoWeeks.div(secPerBlock))) return 5; return 3; } // View function that shows current token price value function getPrice() public view returns (uint256) { if (loyaltyPart == true) return 1; return 8; } // Function activate, when ethers will be recieved to presale smart contract address function () public payable { buy(msg.sender); } function buy(address buyer) whenNotPaused whenNotFinished public payable { require(buyer != address(0)); require(msg.value != 0); require(msg.value >= minimalPrice); uint256 tokens; // payment logic of loyalty part if (loyaltyPart) { if (tokensRaised >= loyaltyCap) { loyaltyPart = false; startPresaleTime = block.number; } tokens = msg.value.mul(ETHUSD).div(getPrice()).mul(10).div(tenZero); tokensRaised = tokensRaised.add(tokens); require (tokensRaised <= presaleCap); if (tokensRaised == presaleCap) { presaleFinished = true; } // payment logic of presale part } else { tokens = msg.value.mul(ETHUSD).div(getPrice()).mul(10).div(tenZero); uint256 bonusTokens = tokens.mul(getBonus()).div(10); freezeBalances[msg.sender] = freezeBalances[msg.sender].add(bonusTokens); freezeTime[msg.sender] = expiredTime; tokensRaised = tokensRaised.add(tokens).add(bonusTokens); require (tokensRaised <= presaleCap); if (tokensRaised == presaleCap) { presaleFinished = true; } } // transfer tokens to investor tokenReward.transfer(buyer, tokens); // transfer ethers to owner owner.transfer(msg.value); } // Callback for obtaining a new ETH/USD quote price from oraclizer function __callback(bytes32 myid, string result) whenOraclizeOn { if (msg.sender != oraclize_cbAddress()) { revert(); } ETHUSD = stringToUint(result); LogPriceUpdated(result); if (oraclize_getPrice("URL") > this.balance) { LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer.."); oraclize_query(86400, "URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0"); } } // Obtaining a new ETH/USD quote price from oraclizer function updatePrice() onlyOwner whenOraclizeOn payable external { if (oraclize_getPrice("URL") > this.balance) { LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer.."); oraclize_query(86400, "URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0"); } } // Transfrom string to uint for obtaining a new ETH/USD quote price from oraclizer function stringToUint(string s) public pure returns (uint result) { bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i = i.add(1)) { uint c = uint(b[i]); if (c == 46) { break; } if (c >= 48 && c <= 57) { result = result.mul(10).add(c.sub(48)); require(result != 0); } } } // Setting a new ETH/USD quote price by owner function updatePriceManualy(uint256 _ETHUSD) onlyOwner external { ETHUSD = _ETHUSD; } // Setting a new ETH/USD quote price by owner function transferFunds() external onlyOwner { owner.transfer(address(this).balance); } // Allow to set new value of minimal purchase by owner function updateMinimal(uint256 _minimalPrice) external onlyOwner { minimalPrice = _minimalPrice; } // Allow to turn Oraclize on by owner function turnOnOraclize() whenOraclizeOff external onlyOwner { oraclizeOn = true; } // Allow to turn Oraclize off by owner function turnOffOraclize() whenOraclizeOn external onlyOwner { oraclizeOn = false; } // Allow to set new value of seconds to mined block by owner function updateSecPerBlock(uint256 _secPerBlock) external onlyOwner { secPerBlock = _secPerBlock; } // Allow to finish loyalty part and start Presale part by owner function startPresale() external onlyOwner { loyaltyPart = false; startPresaleTime = block.number; } // Allow to transfer tokens without any payments by owner function transferTokens(uint256 _tokens) external onlyOwner { uint256 tokens = _tokens.mul(100000000); // decimals = 8 tokenReward.transfer(owner, tokens); } // Allow to airdrop with less than 15 address by owner function airdrop(address[] _array1, uint256[] _array2) external onlyOwner { require(_array1.length <= 15); address[] memory arrayAddress = _array1; uint256[] memory arrayAmount = _array2; uint256 arrayLength = arrayAddress.length.sub(1); uint256 i = 0; while (i <= arrayLength) { tokenReward.transfer(arrayAddress[i], arrayAmount[i]); i = i.add(1); } } // View function that shows time of freezing for future airdrop function freezeTimeOf(address _investor) public view returns (uint256 balance) { return freezeTime[_investor]; } // View function that shows investor of freezing for future airdrop function freezeBalancesOf(address _investor) public view returns (uint256 balance) { return freezeBalances[_investor]; } // Allow to send additional ethers to presale contract without getting tokens by owner function addEther() onlyOwner external payable { } }
Allow to finish loyalty part and start Presale part by owner
function startPresale() external onlyOwner { loyaltyPart = false; startPresaleTime = block.number; }
10,188,743
[ 1, 7009, 358, 4076, 437, 93, 15006, 1087, 471, 787, 18346, 5349, 1087, 635, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 787, 12236, 5349, 1435, 3903, 1338, 5541, 288, 203, 3639, 437, 93, 15006, 1988, 273, 629, 31, 203, 3639, 787, 12236, 5349, 950, 273, 1203, 18, 2696, 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 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./Factory.sol"; import "./Cryptoitem.sol"; import "./CryptoitemLootBox.sol"; import "./Strings.sol"; contract CryptoitemFactory is Factory, Ownable { using Strings for string; address public proxyRegistryAddress; address public nftAddress; address public lootBoxNftAddress; string public baseURI = "https://cryptogame101.herokuapp.com/factory/"; /** * Enforce the existence of only 12 Cryptoitems. */ uint256 CRYPTOITEM_SUPPLY = 12; /** * Three different options for minting Cryptoitems (single, multiple, and lootbox). */ uint256 NUM_OPTIONS = 3; uint256 SINGLE_CRYPTOITEM_OPTION = 0; uint256 MULTIPLE_CRYPTOITEM_OPTION = 1; uint256 LOOTBOX_OPTION = 2; uint256 QUANTITY_IN_MULTIPLE_CRYPTOITEM_OPTION = 4; constructor(address _proxyRegistryAddress, address _nftAddress) public { proxyRegistryAddress = _proxyRegistryAddress; nftAddress = _nftAddress; lootBoxNftAddress = new CryptoitemLootBox(_proxyRegistryAddress, this); } function name() external view returns (string) { return "Cryptoitem Demo Collection Factory"; } function symbol() external view returns (string) { return "CIDCF"; } function supportsFactoryInterface() public view returns (bool) { return true; } function numOptions() public view returns (uint256) { return NUM_OPTIONS; } function mint(uint256 _optionId, address _toAddress) public { // Must be sent from the owner proxy or owner. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); assert(proxyRegistry.proxies(owner) == msg.sender || owner == msg.sender || msg.sender == lootBoxNftAddress); if (true) { require(canMint(_optionId)); } Cryptoitem cic = Cryptoitem(nftAddress); if (_optionId == SINGLE_CRYPTOITEM_OPTION) { cic.mintTo(_toAddress); } else if (_optionId == MULTIPLE_CRYPTOITEM_OPTION) { for (uint256 i = 0; i < QUANTITY_IN_MULTIPLE_CRYPTOITEM_OPTION; i++) { cic.mintTo(_toAddress); } } else if (_optionId == LOOTBOX_OPTION) { CryptoitemLootBox cilb = CryptoitemLootBox(lootBoxNftAddress); cilb.mintTo(_toAddress); } } function canMint(uint256 _optionId) public view returns (bool) { if (_optionId >= NUM_OPTIONS) { return false; } Cryptoitem cic = Cryptoitem(nftAddress); uint256 cryptoitemSupply = cic.totalSupply(); uint256 numItemsAllocated = 0; if (_optionId == SINGLE_CRYPTOITEM_OPTION) { numItemsAllocated = 1; } else if (_optionId == MULTIPLE_CRYPTOITEM_OPTION) { numItemsAllocated = QUANTITY_IN_MULTIPLE_CRYPTOITEM_OPTION; } else if (_optionId == LOOTBOX_OPTION) { CryptoitemLootBox cilb = CryptoitemLootBox(lootBoxNftAddress); numItemsAllocated = cilb.itemsPerLootbox(); } return cryptoitemSupply < (CRYPTOITEM_SUPPLY - numItemsAllocated); } function tokenURI(uint256 _optionId) public view returns (string) { return Strings.strConcat( baseURI, Strings.uint2str(_optionId) ); } /** * Hack to get things to work automatically on OpenSea. * Use transferFrom so the frontend doesn't have to worry about different method names. */ function transferFrom(address _from, address _to, uint256 _tokenId) public { mint(_tokenId, _to); } /** * Hack to get things to work automatically on OpenSea. * Use isApprovedForAll so the frontend doesn't have to worry about different method names. */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { if (owner == _owner && _owner == _operator) { return true; } ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (owner == _owner && proxyRegistry.proxies(_owner) == _operator) { return true; } return false; } /** * Hack to get things to work automatically on OpenSea. * Use isApprovedForAll so the frontend doesn't have to worry about different method names. */ function ownerOf(uint256 _tokenId) public view returns (address _owner) { return owner; } }
Must be sent from the owner proxy or owner.
function mint(uint256 _optionId, address _toAddress) public { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); assert(proxyRegistry.proxies(owner) == msg.sender || owner == msg.sender || msg.sender == lootBoxNftAddress); if (true) { require(canMint(_optionId)); } Cryptoitem cic = Cryptoitem(nftAddress); if (_optionId == SINGLE_CRYPTOITEM_OPTION) { cic.mintTo(_toAddress); for (uint256 i = 0; i < QUANTITY_IN_MULTIPLE_CRYPTOITEM_OPTION; i++) { cic.mintTo(_toAddress); } CryptoitemLootBox cilb = CryptoitemLootBox(lootBoxNftAddress); cilb.mintTo(_toAddress); } }
1,780,766
[ 1, 10136, 506, 3271, 628, 326, 3410, 2889, 578, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 312, 474, 12, 11890, 5034, 389, 3482, 548, 16, 1758, 389, 869, 1887, 13, 1071, 288, 203, 565, 7659, 4243, 2889, 4243, 273, 7659, 4243, 12, 5656, 4243, 1887, 1769, 203, 565, 1815, 12, 5656, 4243, 18, 20314, 606, 12, 8443, 13, 422, 1234, 18, 15330, 747, 3410, 422, 1234, 18, 15330, 747, 1234, 18, 15330, 422, 437, 352, 3514, 50, 1222, 1887, 1769, 203, 377, 203, 565, 309, 261, 3767, 13, 288, 203, 565, 2583, 12, 4169, 49, 474, 24899, 3482, 548, 10019, 203, 565, 289, 203, 377, 203, 565, 15629, 1726, 276, 335, 273, 15629, 1726, 12, 82, 1222, 1887, 1769, 203, 565, 309, 261, 67, 3482, 548, 422, 15915, 67, 14306, 51, 12674, 67, 7425, 13, 288, 203, 1377, 276, 335, 18, 81, 474, 774, 24899, 869, 1887, 1769, 203, 1377, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 10110, 6856, 4107, 67, 706, 67, 24683, 900, 67, 14306, 51, 12674, 67, 7425, 31, 277, 27245, 288, 203, 3639, 276, 335, 18, 81, 474, 774, 24899, 869, 1887, 1769, 203, 1377, 289, 203, 1377, 15629, 1726, 1504, 352, 3514, 276, 330, 70, 273, 15629, 1726, 1504, 352, 3514, 12, 383, 352, 3514, 50, 1222, 1887, 1769, 203, 1377, 276, 330, 70, 18, 81, 474, 774, 24899, 869, 1887, 1769, 203, 565, 289, 7010, 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 ]
pragma solidity ^0.4.21; /* Functions from Kitten Coin main contract to be used by sale contract */ contract KittenCoin { function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); } contract Token { function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract KittenSelfDrop2 is Ownable { KittenCoin public kittenContract; uint8 public dropNumber; uint256 public kittensDroppedToTheWorld; uint256 public kittensRemainingToDrop; uint256 public holderAmount; uint256 public basicReward; uint256 public holderReward; mapping (uint8 => uint256[]) donatorReward; uint8 donatorRewardLevels; uint8 public totalDropTransactions; mapping (address => uint8) participants; // Initialize the cutest contract in the world function KittenSelfDrop2 () { address c = 0xac2BD14654BBf22F9d8f20c7b3a70e376d3436B4; // set Kitten Coin contract address kittenContract = KittenCoin(c); dropNumber = 1; kittensDroppedToTheWorld = 0; kittensRemainingToDrop = 0; basicReward = 50000000000; // set initial basic reward to 500 Kitten Coins holderReward = 50000000000; // set initial holder reward to 500 Kitten Coins holderAmount = 5000000000000; // set initial hold amount to 50000 Kitten Coins for extra reward donatorReward[0]=[1,10000000000]; // set initial donator reward to 100 Kitten Coins from 1 wei donatorReward[1]=[1000000000000000,100000000000]; // set initial donator reward to 1000 Kitten Coins from 0.001 ETH donatorReward[2]=[10000000000000000,500000000000]; // set initial donator reward to 5000 Kitten Coins from 0.01 ETH donatorRewardLevels = 3; totalDropTransactions = 0; } // Drop some wonderful cutest Kitten Coins to sender every time contract is called without function function() payable { require (participants[msg.sender] < dropNumber && kittensRemainingToDrop > basicReward); uint256 tokensIssued = basicReward; // Send extra Kitten Coins bonus if participant is donating Ether if (msg.value > donatorReward[0][0]) tokensIssued += donatorBonus(msg.value); // Send extra Kitten Coins bonus if participant holds at least holderAmount if (kittenContract.balanceOf(msg.sender) >= holderAmount) tokensIssued += holderReward; // Check if number of Kitten Coins to issue is higher than coins remaining for airdrop (last transaction of airdrop) if (tokensIssued > kittensRemainingToDrop) tokensIssued = kittensRemainingToDrop; // Give away these so cute Kitten Coins to contributor kittenContract.transfer(msg.sender, tokensIssued); participants[msg.sender] = dropNumber; kittensRemainingToDrop -= tokensIssued; kittensDroppedToTheWorld += tokensIssued; totalDropTransactions += 1; } function participant(address part) public constant returns (uint8 participationCount) { return participants[part]; } // Increase the airdrop count to allow sweet humans asking for more beautiful Kitten Coins function setDropNumber(uint8 dropN) public onlyOwner { dropNumber = dropN; kittensRemainingToDrop = kittenContract.balanceOf(this); } // Define amount of Kitten Coins to hold in order to get holder reward function setHolderAmount(uint256 amount) public onlyOwner { holderAmount = amount; } // Define how many wonderful Kitten Coins will be issued for participating the selfdrop : basic and holder reward function setRewards(uint256 basic, uint256 holder) public onlyOwner { basicReward = basic; holderReward = holder; } // Define how many wonderful Kitten Coins will be issued for donators participating the selfdrop function setDonatorReward(uint8 index, uint256[] values, uint8 levels) public onlyOwner { donatorReward[index] = values; donatorRewardLevels = levels; } // Sends all ETH contributions to lovely kitten owner function withdrawAll() public onlyOwner { owner.transfer(this.balance); } // Sends all remaining Kitten Coins to owner, just in case of emergency function withdrawKittenCoins() public onlyOwner { kittenContract.transfer(owner, kittenContract.balanceOf(this)); kittensRemainingToDrop = 0; } // Sends all other tokens that would have been sent to owner (why people do that? We don&#39;t meow) function withdrawToken(address token) public onlyOwner { Token(token).transfer(owner, Token(token).balanceOf(this)); } // Update number of Kitten Coins remaining for drop, just in case it is needed function updateKittenCoinsRemainingToDrop() public { kittensRemainingToDrop = kittenContract.balanceOf(this); } // Defines donator bonus to receive function donatorBonus(uint256 amount) public returns (uint256) { for(uint8 i = 1; i < donatorRewardLevels; i++) { if(amount < donatorReward[i][0]) return (donatorReward[i-1][1]); } return (donatorReward[i-1][1]); } }
set initial donator reward to 100 Kitten Coins from 1 wei
donatorReward[0]=[1,10000000000];
10,497,836
[ 1, 542, 2172, 2727, 639, 19890, 358, 2130, 1475, 305, 2253, 385, 9896, 628, 404, 732, 77, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2727, 639, 17631, 1060, 63, 20, 65, 22850, 21, 16, 23899, 9449, 15533, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@acala-network/contracts/oracle/IOracle.sol"; import "@acala-network/contracts/schedule/ISchedule.sol"; import "@acala-network/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Advance option contract that leverage Acala Oracle and Scheduler. * * Users are able to create options for any ERC20 asset and settles with aUSD. */ contract AdvancedOption is ADDRESS { event OptionCreated( uint256 indexed optionId, address indexed asset, address seller, address buyer, uint256 amount, uint256 strikePrice, uint256 settlementTime ); event OptionSettled( uint256 indexed optionId, uint256 price, bool exercised ); struct Option { address seller; address buyer; address asset; uint256 amount; uint256 strikePrice; uint256 settlementTime; bool settled; } IOracle public oracle = IOracle(ADDRESS.Oracle); ISchedule public schedule = ISchedule(ADDRESS.Schedule); uint256 public optionCount; mapping(uint256 => Option) public options; /** * @dev Create a new option. */ function createOption(address asset, address buyer, uint256 amount, uint256 strikePrice, uint256 period) public { require(asset != address(0x0), "asset not set"); require(buyer != address(0x0), "buyer not set"); require(amount != 0, "amount not set"); // Create new options uint256 optionId = optionCount++; options[optionId] = Option({ seller: msg.sender, buyer: buyer, asset: asset, amount: amount, strikePrice: strikePrice, settlementTime: block.timestamp + period, settled: false }); // Seller locks the asset in option. Seller should approve before creating options. IERC20(asset).transferFrom(msg.sender, address(this), amount); // Schedules the settlement call schedule.scheduleCall( address(this), // contract address 0, // how much native token to send to this call 1000000, // gas limit. funds will be reserved and refunded after the call 5000, // storage limit. funds will be reserved and refunded after the call period, // minimum number of blocks to call abi.encodeWithSignature("settleOption(uint256)", optionId) ); emit OptionCreated(optionId, asset, msg.sender, buyer, amount, strikePrice, block.timestamp + period); } /** * @dev Settles the option. Anyone can trigger the settlement. */ function settleOption(uint256 optionId) public { Option memory option = options[optionId]; require(!option.settled, "Option completed"); require(option.settlementTime <= block.timestamp, "Not ready"); // Check the latest price from Oracle uint256 price = oracle.getPrice(option.asset); // Only exercise when the price is higher than the strike price if (price > option.strikePrice) { // Settles with aUSD // Buyer must approve first IERC20(ADDRESS.AUSD).transferFrom(option.buyer, option.seller, option.amount * option.strikePrice); // Buyer obtain the asset IERC20(option.asset).transfer(option.buyer, option.amount); } else { // Otherwise, sends back the asset IERC20(option.asset).transfer(option.seller, option.amount); } // Update the state options[optionId].settled = true; emit OptionSettled(optionId, price, price > option.strikePrice); } }
Seller locks the asset in option. Seller should approve before creating options.
IERC20(asset).transferFrom(msg.sender, address(this), amount);
12,632,966
[ 1, 22050, 13046, 326, 3310, 316, 1456, 18, 4352, 749, 1410, 6617, 537, 1865, 4979, 702, 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 ]
[ 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, 467, 654, 39, 3462, 12, 9406, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x5afc0b82bd845f20804e42ec049bee8e17fa9700 //Contract name: CevacToken //Balance: 0 Ether //Verification Date: 6/11/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal 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 returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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); _; } modifier stopInEmergency { if (paused) { throw; } _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract Token { uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* ERC 20 token */ contract CevacToken is Token,Ownable { string public constant name = "Cevac Token"; string public constant symbol = "CEVAC"; uint256 public constant decimals = 8; string public version = "1.0"; uint public valueToBeSent = 1; bool public finalizedICO = false; uint256 public ethraised; uint256 public btcraised; uint256 public usdraised; uint256 public numberOfBackers; bool public istransferAllowed; uint256 public constant CevacFund = 36 * (10**8) * 10**decimals; uint256 public fundingStartBlock; //start = 1533081600 //1 august 2018 uint256 public fundingEndBlock; ///end = 1585612800 ///31 march 2020 uint256 public tokenCreationMax= 1836 * (10**6) * 10**decimals;//TODO mapping (address => bool) public ownership; uint256 public minCapUSD = 210000000; uint256 public maxCapUSD = 540000000; address public ownerWallet = 0x46F525e84B5C59CA63a5E1503fa82dF98fBb026b; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns (bool success) { if(!istransferAllowed) throw; if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function burnTokens(uint256 _value) public{ require(balances[msg.sender]>=_value); balances[msg.sender] = SafeMath.sub(balances[msg.sender],_value); totalSupply =SafeMath.sub(totalSupply,_value); } //this is the default constructor function CevacToken(uint256 _fundingStartBlock, uint256 _fundingEndBlock){ balances[ownerWallet] = CevacFund; totalSupply = CevacFund; fundingStartBlock = _fundingStartBlock; fundingEndBlock = _fundingEndBlock; } ///change the funding end block function changeEndBlock(uint256 _newFundingEndBlock) public onlyOwner{ fundingEndBlock = _newFundingEndBlock; } ///change the funding start block function changeStartBlock(uint256 _newFundingStartBlock) public onlyOwner{ fundingStartBlock = _newFundingStartBlock; } ///the Min Cap USD ///function too chage the miin cap usd function changeMinCapUSD(uint256 _newMinCap) public onlyOwner{ minCapUSD = _newMinCap; } ///fucntion to change the max cap usd function changeMaxCapUSD(uint256 _newMaxCap) public onlyOwner{ maxCapUSD = _newMaxCap; } function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) returns (bool success) { if(!istransferAllowed) throw; if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function addToBalances(address _person,uint256 value) { if(!ownership[msg.sender]) throw; balances[ownerWallet] = SafeMath.sub(balances[ownerWallet],value); balances[_person] = SafeMath.add(balances[_person],value); Transfer(address(this), _person, value); } /** This is to add the token sale platform ownership to send tokens **/ function addToOwnership(address owners) onlyOwner{ ownership[owners] = true; } /** To be done after killing the old conttract else conflicts can take place This is to remove the token sale platform ownership to send tokens **/ function removeFromOwnership(address owners) onlyOwner{ ownership[owners] = false; } function balanceOf(address _owner) view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) onlyPayloadSize(2 * 32) returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseEthRaised(uint256 value){ require(ownership[msg.sender]); ethraised+=value; } function increaseBTCRaised(uint256 value){ require(ownership[msg.sender]); btcraised+=value; } function increaseUSDRaised(uint256 value){ require(ownership[msg.sender]); usdraised+=value; } function finalizeICO() public{ require(ownership[msg.sender]); require(usdraised>=minCapUSD); finalizedICO = true; istransferAllowed = true; } function enableTransfers() public onlyOwner{ istransferAllowed = true; } function disableTransfers() public onlyOwner{ istransferAllowed = false; } //functiion to force finalize the ICO by the owner no checks called here function finalizeICOOwner() onlyOwner{ finalizedICO = true; istransferAllowed = true; } function isValid() returns(bool){ if(now>=fundingStartBlock && now<fundingEndBlock ){ return true; }else{ return false; } if(usdraised>maxCapUSD) throw; } ///do not allow payments on this address function() payable{ throw; } }
change the funding end block
function changeEndBlock(uint256 _newFundingEndBlock) public onlyOwner{ fundingEndBlock = _newFundingEndBlock; }
14,076,494
[ 1, 3427, 326, 22058, 679, 1203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2549, 1638, 1768, 12, 11890, 5034, 389, 2704, 42, 14351, 1638, 1768, 13, 1071, 1338, 5541, 95, 203, 3639, 22058, 1638, 1768, 273, 389, 2704, 42, 14351, 1638, 1768, 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/4/0xBBd30514cEf49Ca21332D856fBab1Db7E8024B48/sources/QuotaDelegate.sol
@dev deposit rate use for deposit amount calculate
uint public depositRate;
8,608,702
[ 1, 323, 1724, 4993, 999, 364, 443, 1724, 3844, 4604, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 443, 1724, 4727, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6f9140097Ab6278B41Cf9597a597030207b8D75d/sources/lib/seaport-core/src/lib/CriteriaResolution.sol
* @dev Internal pure function to update a criteria item. @param offer The offer containing the item to update. @param componentIndex The index of the item to update. @param criteriaResolver The criteria resolver to use to update the item./ Retrieve relevant item using the component index. Read item type and criteria from memory & place on stack. Ensure the specified item type indicates criteria usage. If criteria is not 0 (i.e. a collection-wide criteria-based item)... Verify identifier inclusion in criteria root using proof. Revert if non-empty proof is supplied for a collection-wide item. Item type 4 becomes 2 and item type 5 becomes 3.
function _updateCriteriaItem( OfferItem[] memory offer, uint256 componentIndex, CriteriaResolver memory criteriaResolver ) internal pure { OfferItem memory offerItem = offer[componentIndex]; ItemType itemType = offerItem.itemType; if (!_isItemWithCriteria(itemType)) { _revertCriteriaNotEnabledForItem(); } uint256 identifierOrCriteria = offerItem.identifierOrCriteria; if (identifierOrCriteria != uint256(0)) { _verifyProof(criteriaResolver.identifier, identifierOrCriteria, criteriaResolver.criteriaProof); _revertInvalidProof(); } assembly { newItemType := sub(3, eq(itemType, 4)) } offerItem.itemType = newItemType; }
9,676,341
[ 1, 3061, 16618, 445, 358, 1089, 279, 3582, 761, 18, 225, 10067, 2398, 1021, 10067, 4191, 326, 761, 358, 1089, 18, 225, 1794, 1016, 565, 1021, 770, 434, 326, 761, 358, 1089, 18, 225, 3582, 4301, 225, 1021, 3582, 5039, 358, 999, 358, 1089, 326, 761, 18, 19, 10708, 9368, 761, 1450, 326, 1794, 770, 18, 2720, 761, 618, 471, 3582, 628, 3778, 473, 3166, 603, 2110, 18, 7693, 326, 1269, 761, 618, 8527, 3582, 4084, 18, 971, 3582, 353, 486, 374, 261, 77, 18, 73, 18, 279, 1849, 17, 26767, 3582, 17, 12261, 761, 13, 2777, 8553, 2756, 26485, 316, 3582, 1365, 1450, 14601, 18, 868, 1097, 309, 1661, 17, 5531, 14601, 353, 4580, 364, 279, 1849, 17, 26767, 761, 18, 4342, 618, 1059, 12724, 576, 471, 761, 618, 1381, 12724, 890, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2725, 7231, 1180, 12, 203, 3639, 25753, 1180, 8526, 3778, 10067, 16, 203, 3639, 2254, 5034, 1794, 1016, 16, 203, 3639, 8356, 4301, 3778, 3582, 4301, 203, 565, 262, 2713, 16618, 288, 203, 3639, 25753, 1180, 3778, 10067, 1180, 273, 10067, 63, 4652, 1016, 15533, 203, 203, 3639, 4342, 559, 23080, 273, 10067, 1180, 18, 1726, 559, 31, 203, 203, 3639, 309, 16051, 67, 291, 1180, 1190, 7231, 12, 1726, 559, 3719, 288, 203, 5411, 389, 266, 1097, 7231, 1248, 1526, 1290, 1180, 5621, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 2756, 1162, 7231, 273, 10067, 1180, 18, 5644, 1162, 7231, 31, 203, 203, 3639, 309, 261, 5644, 1162, 7231, 480, 2254, 5034, 12, 20, 3719, 288, 203, 5411, 389, 8705, 20439, 12, 9714, 4301, 18, 5644, 16, 2756, 1162, 7231, 16, 3582, 4301, 18, 9714, 20439, 1769, 203, 5411, 389, 266, 1097, 1941, 20439, 5621, 203, 3639, 289, 203, 203, 3639, 19931, 288, 203, 5411, 394, 22580, 519, 720, 12, 23, 16, 7555, 12, 1726, 559, 16, 1059, 3719, 203, 3639, 289, 203, 3639, 10067, 1180, 18, 1726, 559, 273, 394, 22580, 31, 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 ]
./partial_match/1/0x74b2a6eCc225dc85af74b5Ea12C8f26Fba86c571/sources/contracts/libraries/BytesLibrary.sol
* @dev Replace the address at the given location in a byte array if the contents at that location match the expected address./ An address is 20 bytes long
{ bytes memory expectedData = abi.encodePacked(expectedAddress); bytes memory newData = abi.encodePacked(newAddress); for (uint256 i = 0; i < 20; i++) { uint256 dataLocation = startLocation + i; require(data[dataLocation] == expectedData[i], "Bytes: Data provided does not include the expectedAddress"); data[dataLocation] = newData[i]; } }
4,114,224
[ 1, 5729, 326, 1758, 622, 326, 864, 2117, 316, 279, 1160, 526, 309, 326, 2939, 622, 716, 2117, 845, 326, 2665, 1758, 18, 19, 1922, 1758, 353, 4200, 1731, 1525, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 1731, 3778, 2665, 751, 273, 24126, 18, 3015, 4420, 329, 12, 3825, 1887, 1769, 203, 3639, 1731, 3778, 16026, 273, 24126, 18, 3015, 4420, 329, 12, 2704, 1887, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4200, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 501, 2735, 273, 787, 2735, 397, 277, 31, 203, 5411, 2583, 12, 892, 63, 892, 2735, 65, 422, 2665, 751, 63, 77, 6487, 315, 2160, 30, 1910, 2112, 1552, 486, 2341, 326, 2665, 1887, 8863, 203, 5411, 501, 63, 892, 2735, 65, 273, 16026, 63, 77, 15533, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ERC20.sol"; import "./Dubi.sol"; import "./IHodl.sol"; import "./MintMath.sol"; contract Purpose is ERC20 { // The DUBI contract, required for auto-minting DUBI on burn. Dubi private immutable _dubi; // The HODL contract, required for burning locked PRPS. IHodl private immutable _hodl; modifier onlyHodl() { require(msg.sender == _hodlAddress, "PRPS-1"); _; } constructor( uint256 initialSupply, address optIn, address dubi, address hodl, address externalAddress1, address externalAddress2, address externalAddress3 ) public ERC20( "Purpose", "PRPS", optIn, hodl, externalAddress1, externalAddress2, externalAddress3 ) { _dubi = Dubi(dubi); _hodl = IHodl(hodl); _mintInitialSupply(msg.sender, initialSupply); } /** * @dev Returns the address of the {HODL} contract used for burning locked PRPS. */ function hodl() external view returns (address) { return address(_hodl); } /** * @dev Returns the hodl balance of the given `tokenHolder` */ function hodlBalanceOf(address tokenHolder) public view returns (uint256) { // The hodl balance follows after the first 96 bits in the packed data. return uint96(_packedData[tokenHolder] >> 96); } /** * @dev Transfer `amount` PRPS from `from` to the Hodl contract. * * This can only be called by the Hodl contract. */ function hodlTransfer(address from, uint96 amount) external onlyHodl { _move(from, address(_hodl), amount); } /** * @dev Increase the hodl balance of `account` by `hodlAmount`. This is * only used as part of the migration. */ function migrateHodlBalance(address account, uint96 hodlAmount) external onlyHodl { UnpackedData memory unpacked = _unpackPackedData(_packedData[account]); unpacked.hodlBalance += hodlAmount; _packedData[account] = _packUnpackedData(unpacked); } /** * @dev Increase the hodl balance of `to` by moving `amount` PRPS from `from`'s balance. * * This can only be called by the Hodl contract. */ function increaseHodlBalance( address from, address to, uint96 amount ) external onlyHodl { UnpackedData memory unpackedDataFrom = _unpackPackedData( _packedData[from] ); UnpackedData memory unpackedDataTo; // We only need to unpack twice if from != to if (from != to) { unpackedDataTo = _unpackPackedData(_packedData[to]); } else { unpackedDataTo = unpackedDataFrom; } // `from` must have enough balance require(unpackedDataFrom.balance >= amount, "PRPS-3"); // Subtract balance from `from` unpackedDataFrom.balance -= amount; // Add to `hodlBalance` from `to` unpackedDataTo.hodlBalance += amount; // We only need to pack twice if from != to if (from != to) { _packedData[to] = _packUnpackedData(unpackedDataTo); } _packedData[from] = _packUnpackedData(unpackedDataFrom); } /** * @dev Decrease the hodl balance of `from` by `hodlAmount` and increase * the regular balance by `refundAmount. * * `refundAmount` might be less than `hodlAmount`. * * E.g. when burning fuel in locked PRPS * * This can only be called by the Hodl contract. */ function decreaseHodlBalance( address from, uint96 hodlAmount, uint96 refundAmount ) external onlyHodl { require(hodlAmount >= refundAmount, "PRPS-4"); UnpackedData memory unpackedDataFrom = _unpackPackedData( _packedData[from] ); // `from` must have enough balance require(unpackedDataFrom.hodlBalance >= hodlAmount, "PRPS-5"); // Subtract amount from hodl balance unpackedDataFrom.hodlBalance -= hodlAmount; if (refundAmount > 0) { // Add amount to balance unpackedDataFrom.balance += refundAmount; } // Write to storage _packedData[from] = _packUnpackedData(unpackedDataFrom); } /** * @dev Revert the hodl balance change caused by `from` on `to`. * * E.g. when reverting a pending hodl. * * This can only be called by the Hodl contract. */ function revertHodlBalance( address from, address to, uint96 amount ) external onlyHodl { UnpackedData memory unpackedDataFrom = _unpackPackedData( _packedData[from] ); UnpackedData memory unpackedDataTo; // We only need to unpack twice if from != to if (from != to) { unpackedDataTo = _unpackPackedData(_packedData[to]); } else { unpackedDataTo = unpackedDataFrom; } // `to` must have enough hodl balance require(unpackedDataTo.hodlBalance >= amount, "PRPS-5"); // Subtract hodl balance from `to` unpackedDataTo.hodlBalance -= amount; // Add to `balance` from `from` unpackedDataFrom.balance += amount; // We only need to pack twice if from != to if (from != to) { _packedData[to] = _packUnpackedData(unpackedDataTo); } _packedData[from] = _packUnpackedData(unpackedDataFrom); } /** * @dev Mint DUBI when burning PRPS * @param from address token holder address * @param transferAmount amount of tokens to burn * @param occupiedAmount amount of tokens that are occupied * @param createdAt equal to block.timestamp if not finalizing a pending op, otherwise * it corresponds to op.createdAt * @param finalizing boolean indicating whether this is a finalizing transaction or not. Changes * how the `amount` is interpreted. * * When burning PRPS, we first try to burn unlocked PRPS. * If burning an amount that exceeds the unlocked PRPS of `from`, we attempt to burn the * difference from locked PRPS. * * If the desired `amount` cannot be filled by taking locked and unlocked PRPS into account, * this function reverts. * * Burning locked PRPS means reducing the `hodlBalance` while burning unlocked PRPS means reducing * the regular `balance`. * * This function returns the actual unlocked PRPS that needs to be removed from `balance`. * */ function _beforeBurn( address from, UnpackedData memory unpacked, uint96 transferAmount, uint96 occupiedAmount, uint32 createdAt, FuelBurn memory fuelBurn, bool finalizing ) internal override returns (uint96) { uint96 totalDubiToMint; uint96 lockedPrpsToBurn; uint96 burnableUnlockedPrps; // Depending on whether this is a finalizing burn or not, // the amount of locked/unlocked PRPS is determined differently. if (finalizing) { // For a finalizing burn, we use the occupied amount, since we already know how much // locked PRPS we are going to burn. This amount represents the `pendingLockedPrps` // on the hodl items. lockedPrpsToBurn = occupiedAmount; // Since `transferAmount` is the total amount of PRPS getting burned, we need to subtract // the `occupiedAmount` to get the actual amount of unlocked PRPS. // Sanity check assert(transferAmount >= occupiedAmount); transferAmount -= occupiedAmount; // Set the unlocked PRPS to burn to the updated `transferAmount` burnableUnlockedPrps = transferAmount; } else { // For a direct burn, we start off with the full amounts, since we don't know the exact // amounts initially. lockedPrpsToBurn = transferAmount; burnableUnlockedPrps = unpacked.balance; } // 1) Try to burn unlocked PRPS if (burnableUnlockedPrps > 0) { // Nice, we can burn unlocked PRPS // Catch underflow i.e. don't burn more than we need to if (burnableUnlockedPrps > transferAmount) { burnableUnlockedPrps = transferAmount; } // Calculate DUBI to mint based on unlocked PRPS we can burn totalDubiToMint = MintMath.calculateDubiToMintMax( burnableUnlockedPrps ); // Subtract the amount of burned unlocked PRPS from the locked PRPS we // need to burn if this is NOT a finalizing burn, because in that case we // already have the exact amount locked PRPS we want to burn. if (!finalizing) { lockedPrpsToBurn -= burnableUnlockedPrps; } } // 2) Burn locked PRPS if there's not enough unlocked PRPS // Burn an additional amount of locked PRPS equal to the fuel if any if (fuelBurn.fuelType == FuelType.LOCKED_PRPS) { // The `burnFromLockedPrps` call will fail, if not enough PRPS can be burned. lockedPrpsToBurn += fuelBurn.amount; } if (lockedPrpsToBurn > 0) { uint96 dubiToMintFromLockedPrps = _burnFromLockedPrps({ from: from, unpacked: unpacked, lockedPrpsToBurn: lockedPrpsToBurn, createdAt: createdAt, finalizing: finalizing }); // We check 'greater than or equal' because it's possible to mint 0 new DUBI // e.g. when called right after a hodl where not enough time passed to generate new DUBI. uint96 dubiToMint = totalDubiToMint + dubiToMintFromLockedPrps; require(dubiToMint >= totalDubiToMint, "PRPS-6"); totalDubiToMint = dubiToMint; } else { // Sanity check for finalizes that don't touch locked PRPS assert(occupiedAmount == 0); } // Burn minted DUBI equal to the fuel if any if (fuelBurn.fuelType == FuelType.AUTO_MINTED_DUBI) { require(totalDubiToMint >= fuelBurn.amount, "PRPS-7"); totalDubiToMint -= fuelBurn.amount; } // Mint DUBI taking differences between burned locked/unlocked into account if (totalDubiToMint > 0) { _dubi.purposeMint(from, totalDubiToMint); } return burnableUnlockedPrps; } function _burnFromLockedPrps( address from, UnpackedData memory unpacked, uint96 lockedPrpsToBurn, uint32 createdAt, bool finalizing ) private returns (uint96) { // Reverts if the exact amount needed cannot be burned uint96 dubiToMintFromLockedPrps = _hodl.burnLockedPrps({ from: from, amount: lockedPrpsToBurn, dubiMintTimestamp: createdAt, burnPendingLockedPrps: finalizing }); require(unpacked.hodlBalance >= lockedPrpsToBurn, "PRPS-8"); unpacked.hodlBalance -= lockedPrpsToBurn; return dubiToMintFromLockedPrps; } function _callerIsDeployTimeKnownContract() internal override view returns (bool) { if (msg.sender == address(_dubi)) { return true; } return super._callerIsDeployTimeKnownContract(); } //--------------------------------------------------------------- // Fuel //--------------------------------------------------------------- /** * @dev Burns `fuel` from `from`. Can only be called by one of the deploy-time known contracts. */ function burnFuel(address from, TokenFuel memory fuel) public override { require(_callerIsDeployTimeKnownContract(), "PRPS-2"); _burnFuel(from, fuel); } function _burnFuel(address from, TokenFuel memory fuel) private { require(fuel.amount <= MAX_BOOSTER_FUEL, "PRPS-10"); require(from != address(0) && from != msg.sender, "PRPS-11"); if (fuel.tokenAlias == TOKEN_FUEL_ALIAS_UNLOCKED_PRPS) { // Burn fuel from unlocked PRPS UnpackedData memory unpacked = _unpackPackedData(_packedData[from]); require(unpacked.balance >= fuel.amount, "PRPS-7"); unpacked.balance -= fuel.amount; _packedData[from] = _packUnpackedData(unpacked); return; } if (fuel.tokenAlias == TOKEN_FUEL_ALIAS_LOCKED_PRPS) { // Burn fuel from locked PRPS UnpackedData memory unpacked = _unpackPackedData(_packedData[from]); require(unpacked.hodlBalance >= fuel.amount, "PRPS-7"); unpacked.hodlBalance -= fuel.amount; // We pass a mint timestamp, but that doesn't mean that DUBI is minted. // The returned DUBI that should be minted is ignored. // Reverts if not enough locked PRPS can be burned. _hodl.burnLockedPrps({ from: from, amount: fuel.amount, dubiMintTimestamp: uint32(block.timestamp), burnPendingLockedPrps: false }); _packedData[from] = _packUnpackedData(unpacked); return; } revert("PRPS-12"); } /** *@dev Burn the fuel of a `boostedSend` */ function _burnBoostedSendFuel( address from, BoosterFuel memory fuel, UnpackedData memory unpacked ) internal override returns (FuelBurn memory) { FuelBurn memory fuelBurn; if (fuel.unlockedPrps > 0) { require(fuel.unlockedPrps <= MAX_BOOSTER_FUEL, "PRPS-10"); require(unpacked.balance >= fuel.unlockedPrps, "PRPS-7"); unpacked.balance -= fuel.unlockedPrps; fuelBurn.amount = fuel.unlockedPrps; fuelBurn.fuelType = FuelType.UNLOCKED_PRPS; return fuelBurn; } if (fuel.lockedPrps > 0) { require(fuel.lockedPrps <= MAX_BOOSTER_FUEL, "PRPS-10"); // We pass a mint timestamp, but that doesn't mean that DUBI is minted. // The returned DUBI that should be minted is ignored. // Reverts if not enough locked PRPS can be burned. _hodl.burnLockedPrps({ from: from, amount: fuel.lockedPrps, dubiMintTimestamp: uint32(block.timestamp), burnPendingLockedPrps: false }); require(unpacked.hodlBalance >= fuel.lockedPrps, "PRPS-7"); unpacked.hodlBalance -= fuel.lockedPrps; fuelBurn.amount = fuel.lockedPrps; fuelBurn.fuelType = FuelType.LOCKED_PRPS; return fuelBurn; } // If the fuel is DUBI, then we have to reach out to the DUBI contract. if (fuel.dubi > 0) { // Reverts if the requested amount cannot be burned _dubi.burnFuel( from, TokenFuel({ tokenAlias: TOKEN_FUEL_ALIAS_DUBI, amount: fuel.dubi }) ); fuelBurn.amount = fuel.dubi; fuelBurn.fuelType = FuelType.DUBI; return fuelBurn; } return fuelBurn; } /** *@dev Burn the fuel of a `boostedBurn` */ function _burnBoostedBurnFuel( address from, BoosterFuel memory fuel, UnpackedData memory unpacked ) internal override returns (FuelBurn memory) { FuelBurn memory fuelBurn; if (fuel.unlockedPrps > 0) { require(fuel.unlockedPrps <= MAX_BOOSTER_FUEL, "PRPS-10"); require(unpacked.balance >= fuel.unlockedPrps, "PRPS-7"); unpacked.balance -= fuel.unlockedPrps; fuelBurn.amount = fuel.unlockedPrps; fuelBurn.fuelType = FuelType.UNLOCKED_PRPS; return fuelBurn; } if (fuel.lockedPrps > 0) { require(fuel.lockedPrps <= MAX_BOOSTER_FUEL, "PRPS-10"); require(unpacked.hodlBalance >= fuel.lockedPrps, "PRPS-7"); // Fuel is taken from hodl balance in _beforeBurn // unpacked.hodlBalance -= fuel.lockedPrps; fuelBurn.amount = fuel.lockedPrps; fuelBurn.fuelType = FuelType.LOCKED_PRPS; return fuelBurn; } if (fuel.intrinsicFuel > 0) { require(fuel.intrinsicFuel <= MAX_BOOSTER_FUEL, "PRPS-10"); fuelBurn.amount = fuel.intrinsicFuel; fuelBurn.fuelType = FuelType.AUTO_MINTED_DUBI; return fuelBurn; } // If the fuel is DUBI, then we have to reach out to the DUBI contract. if (fuel.dubi > 0) { // Reverts if the requested amount cannot be burned _dubi.burnFuel( from, TokenFuel({ tokenAlias: TOKEN_FUEL_ALIAS_DUBI, amount: fuel.dubi }) ); fuelBurn.amount = fuel.dubi; fuelBurn.fuelType = FuelType.DUBI; return fuelBurn; } // No fuel at all return fuelBurn; } //--------------------------------------------------------------- // Pending ops //--------------------------------------------------------------- function _getHasherContracts() internal override returns (address[] memory) { address[] memory hashers = new address[](5); hashers[0] = address(this); hashers[1] = address(_dubi); hashers[2] = _hodlAddress; hashers[3] = _externalAddress1; hashers[4] = _externalAddress2; return hashers; } /** * @dev Create a pending transfer by moving the funds of `spender` to this contract. * Special behavior applies to pending burns to account for locked PRPS. */ function _createPendingTransferInternal( OpHandle memory opHandle, address spender, address from, address to, uint256 amount, bytes memory data ) internal override returns (PendingTransfer memory) { if (opHandle.opType != OP_TYPE_BURN) { return // Nothing special to do for non-burns so just call parent implementation super._createPendingTransferInternal( opHandle, spender, from, to, amount, data ); } // When burning, we first use unlocked PRPS and match the remaining amount with locked PRPS from the Hodl contract. // Sanity check assert(amount < 2**96); uint96 transferAmount = uint96(amount); uint96 lockedPrpsAmount = transferAmount; UnpackedData memory unpacked = _unpackPackedData(_packedData[from]); // First try to move as much unlocked PRPS as possible to the PRPS address uint96 unlockedPrpsToMove = transferAmount; if (unlockedPrpsToMove > unpacked.balance) { unlockedPrpsToMove = unpacked.balance; } // Update the locked PRPS we have to use lockedPrpsAmount -= unlockedPrpsToMove; if (unlockedPrpsToMove > 0) { _move({from: from, to: address(this), amount: unlockedPrpsToMove}); } // If we still need locked PRPS, call into the Hodl contract. // This will also take pending hodls into account, if `from` has // some. if (lockedPrpsAmount > 0) { // Reverts if not the exact amount can be set to pending _hodl.setLockedPrpsToPending(from, lockedPrpsAmount); } // Create pending transfer return PendingTransfer({ spender: spender, transferAmount: transferAmount, to: to, occupiedAmount: lockedPrpsAmount, data: data }); } /** * @dev Hook that is called during revert of a pending op. * Reverts any changes to locked PRPS when 'opType' is burn. */ function _onRevertPendingOp( address user, uint8 opType, uint64 opId, uint96 transferAmount, uint96 occupiedAmount ) internal override { if (opType != OP_TYPE_BURN) { return; } // Extract the pending locked PRPS from the amount. if (occupiedAmount > 0) { _hodl.revertLockedPrpsSetToPending(user, occupiedAmount); } } //--------------------------------------------------------------- // Shared pending ops for Hodl //--------------------------------------------------------------- /** * @dev Creates a new opHandle with the given type for `user`. Hodl and Prps share the same * opCounter to enforce a consistent order in which pending ops are finalized/reverted * across contracts. This function can only be called by Hodl. */ function createNewOpHandleShared( IOptIn.OptInStatus memory optInStatus, address user, uint8 opType ) public onlyHodl returns (OpHandle memory) { return _createNewOpHandle(optInStatus, user, opType); } /** * @dev Delete the op handle with the given `opId` from `user`. Hodl and Prps share the same * opCounter to enforce a consistent order in which pending ops are finalized/reverted * across contracts. This function can only be called by Hodl. */ function deleteOpHandleShared(address user, OpHandle memory opHandle) public onlyHodl returns (bool) { _deleteOpHandle(user, opHandle); return true; } /** * @dev Get the next op id for `user`. Hodl and Prps share the same * opCounter to enforce a consistent order in which pending ops are finalized/reverted * across contracts. This function can only be called by Hodl. */ function assertFinalizeFIFOShared(address user, uint64 opId) public onlyHodl returns (bool) { _assertFinalizeFIFO(user, opId); return true; } /** * @dev Get the next op id for `user`. Hodl and Prps share the same * opCounter to enforce a consistent order in which pending ops are finalized/reverted * across contracts. This function can only be called by Hodl. */ function assertRevertLIFOShared(address user, uint64 opId) public onlyHodl returns (bool) { _assertRevertLIFO(user, opId); return true; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/introspection/IERC1820Registry.sol"; import "./IBoostableERC20.sol"; import "./BoostableERC20.sol"; /** * @dev This is a heavily modified fork of @openzeppelin/contracts/token/ERC20/ERC20.sol (3.1.0) */ abstract contract ERC20 is IERC20, IBoostableERC20, BoostableERC20, Ownable { using SafeMath for uint256; // NOTE: In contrary to the Transfer event, the Burned event always // emits the amount including the burned fuel if any. // The amount is stored in the lower 96 bits of `amountAndFuel`, // followed by 3 bits to encode the type of fuel used and finally // another 96 bits for the fuel amount. // // 0 96 99 195 256 // amount fuelType fuelAmount padding // event Burned(uint256 amountAndFuel, bytes data); enum FuelType {NONE, UNLOCKED_PRPS, LOCKED_PRPS, DUBI, AUTO_MINTED_DUBI} struct FuelBurn { FuelType fuelType; uint96 amount; } uint256 private _totalSupply; string private _name; string private _symbol; address internal immutable _hodlAddress; address internal immutable _externalAddress1; address internal immutable _externalAddress2; address internal immutable _externalAddress3; IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry( 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24 ); // Mapping of address to packed data. // For efficiency reasons the token balance is a packed uint96 alongside // other data. The packed data has the following layout: // // MSB uint256 LSB // uint64 nonce | uint96 hodlBalance | uint96 balance // // balance: the balance of a token holder that can be transferred freely // hodlBalance: the balance of a token holder that is hodled // nonce: a sequential number used for booster replay protection // // Only PRPS utilizes `hodlBalance`. For DUBI it is always 0. // mapping(address => uint256) internal _packedData; struct UnpackedData { uint96 balance; uint96 hodlBalance; uint64 nonce; } function _unpackPackedData(uint256 packedData) internal pure returns (UnpackedData memory) { UnpackedData memory unpacked; // 1) Read balance from the first 96 bits unpacked.balance = uint96(packedData); // 2) Read hodlBalance from the next 96 bits unpacked.hodlBalance = uint96(packedData >> 96); // 3) Read nonce from the next 64 bits unpacked.nonce = uint64(packedData >> (96 + 96)); return unpacked; } function _packUnpackedData(UnpackedData memory unpacked) internal pure returns (uint256) { uint256 packedData; // 1) Write balance to the first 96 bits packedData |= unpacked.balance; // 2) Write hodlBalance to the the next 96 bits packedData |= uint256(unpacked.hodlBalance) << 96; // 3) Write nonce to the next 64 bits packedData |= uint256(unpacked.nonce) << (96 + 96); return packedData; } // ERC20-allowances mapping(address => mapping(address => uint256)) private _allowances; //--------------------------------------------------------------- // Pending state for non-boosted operations while opted-in //--------------------------------------------------------------- uint8 internal constant OP_TYPE_SEND = BOOST_TAG_SEND; uint8 internal constant OP_TYPE_BURN = BOOST_TAG_BURN; struct PendingTransfer { // NOTE: For efficiency reasons balances are stored in a uint96 which is sufficient // since we only use 18 decimals. // // Two amounts are associated with a pending transfer, to allow deriving contracts // to store extra information. // // E.g. PRPS makes use of this by encoding the pending locked PRPS in the // `occupiedAmount` field. // address spender; uint96 transferAmount; address to; uint96 occupiedAmount; bytes data; } // A mapping of hash(user, opId) to pending transfers. Pending burns are also considered regular transfers. mapping(bytes32 => PendingTransfer) private _pendingTransfers; //--------------------------------------------------------------- constructor( string memory name, string memory symbol, address optIn, address hodl, address externalAddress1, address externalAddress2, address externalAddress3 ) public Ownable() BoostableERC20(optIn) { _name = name; _symbol = symbol; _hodlAddress = hodl; _externalAddress1 = externalAddress1; _externalAddress2 = externalAddress2; _externalAddress3 = externalAddress3; // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer( address(this), keccak256("BoostableERC20Token"), address(this) ); _ERC1820_REGISTRY.setInterfaceImplementer( address(this), keccak256("ERC20Token"), address(this) ); } /** * @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. */ function decimals() public pure returns (uint8) { return 18; } /** * @dev Returns the current nonce of `account` */ function getNonce(address account) external override view returns (uint64) { UnpackedData memory unpacked = _unpackPackedData(_packedData[account]); return unpacked.nonce; } /** * @dev Returns the total supply */ function totalSupply() external override(IBoostableERC20, IERC20) view returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public override(IBoostableERC20, IERC20) view returns (uint256) { // Return the balance of the holder that is not hodled (i.e. first 96 bits of the packeData) return uint96(_packedData[tokenHolder]); } /** * @dev Returns the unpacked data struct of `tokenHolder` */ function unpackedDataOf(address tokenHolder) public view returns (UnpackedData memory) { return _unpackPackedData(_packedData[tokenHolder]); } /** * @dev Mints `amount` new tokens for `to`. * * To make things more efficient, the total supply is optionally packed into the passed * amount where the first 96 bits are used for the actual amount and the following 96 bits * for the total supply. * */ function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function _mintInitialSupply(address to, uint256 amount) internal { // _mint does not update the totalSupply by default, unless the second 96 bits // passed are non-zero - in which case the non-zero value becomes the new total supply. // So in order to get the correct initial supply, we have to mirror the lower 96 bits // to the following 96 bits. amount = amount | (amount << 96); _mint(to, amount); } function _mint(address to, uint256 amount) internal { require(to != address(0), "ERC20-1"); // The actual amount to mint (=lower 96 bits) uint96 amountToMint = uint96(amount); // The new total supply, which may be 0 in which case no update is performed. uint96 updatedTotalSupply = uint96(amount >> 96); // Update state variables if (updatedTotalSupply > 0) { _totalSupply = updatedTotalSupply; } // Update packed data and check for uint96 overflow UnpackedData memory unpacked = _unpackPackedData(_packedData[to]); uint96 updatedBalance = unpacked.balance + amountToMint; // The overflow check also takes the hodlBalance into account require( updatedBalance + unpacked.hodlBalance >= unpacked.balance, "ERC20-2" ); unpacked.balance = updatedBalance; _packedData[to] = _packUnpackedData(unpacked); emit Transfer(address(0), to, amountToMint); } /** * @dev Transfer `amount` from msg.sender to `recipient` */ function transfer(address recipient, uint256 amount) public override(IBoostableERC20, IERC20) returns (bool) { _assertSenderRecipient(msg.sender, recipient); // Never create a pending transfer if msg.sender is a deploy-time known contract if (!_callerIsDeployTimeKnownContract()) { // Create pending transfer if sender is opted-in and the permaboost is active address from = msg.sender; IOptIn.OptInStatus memory optInStatus = getOptInStatus(from); if (optInStatus.isOptedIn && optInStatus.permaBoostActive) { _createPendingTransfer({ opType: OP_TYPE_SEND, spender: msg.sender, from: msg.sender, to: recipient, amount: amount, data: "", optInStatus: optInStatus }); return true; } } _move({from: msg.sender, to: recipient, amount: amount}); return true; } /** * @dev Burns `amount` of msg.sender. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public { // Create pending burn if sender is opted-in and the permaboost is active IOptIn.OptInStatus memory optInStatus = getOptInStatus(msg.sender); if (optInStatus.isOptedIn && optInStatus.permaBoostActive) { _createPendingTransfer({ opType: OP_TYPE_BURN, spender: msg.sender, from: msg.sender, to: address(0), amount: amount, data: data, optInStatus: optInStatus }); return; } _burn({ from: msg.sender, amount: amount, data: data, incrementNonce: false }); } /** * @dev Moves `amount` tokens from `sender` to `recipient`. * * Can only be used by deploy-time known contracts. * * IBoostableERC20 extension */ function boostedTransferFrom( address sender, address recipient, uint256 amount, bytes calldata data ) public override returns (bool) { _assertSenderRecipient(sender, recipient); IOptIn.OptInStatus memory optInStatus = getOptInStatus(sender); // Only transfer if `sender` is a deploy-time known contract, otherwise // revert. require( _isDeployTimeKnownContractAndCanTransfer( sender, recipient, amount, optInStatus, data ), "ERC20-17" ); _move({from: sender, to: recipient, amount: amount}); return true; } function _isDeployTimeKnownContractAndCanTransfer( address sender, address recipient, uint256 amount, IOptIn.OptInStatus memory optInStatus, bytes memory data ) private view returns (bool) { // If the caller not a deploy-time known contract, the transfer is not allowed if (!_callerIsDeployTimeKnownContract()) { return false; } if (msg.sender != _externalAddress3) { return true; } // _externalAddress3 passes a flag via `data` that indicates whether it is a boosted transaction // or not. uint8 isBoostedBits; assembly { // Load flag using a 1-byte offset, because `mload` always reads // 32-bytes at once and the first 32 bytes of `data` contain it's length. isBoostedBits := mload(add(data, 0x01)) } // Reading into a 'bool' directly doesn't work for some reason if (isBoostedBits & 1 == 1) { return true; } // If the latter, then _externalAddress3 can only transfer the funds if either: // - the permaboost is not active // - `sender` is not opted-in to begin with // // If `sender` is opted-in and the permaboost is active, _externalAddress3 cannot // take funds, except when boosted. Here the booster trusts _externalAddress3, since it already // verifies that `sender` provided a valid signature. // // This is special to _externalAddress3, other deploy-time known contracts do not make use of `data`. if (optInStatus.permaBoostActive && optInStatus.isOptedIn) { return false; } return true; } /** * @dev Verify the booster payload against the nonce that is stored in the packed data of an account. * The increment happens outside of this function, when the balance is updated. */ function _verifyNonce(BoosterPayload memory payload, uint64 currentNonce) internal pure { require(currentNonce == payload.nonce - 1, "ERC20-5"); } //--------------------------------------------------------------- // Boosted functions //--------------------------------------------------------------- /** * @dev Perform multiple `boostedSend` calls in a single transaction. * * NOTE: Booster extension */ function boostedSendBatch( BoostedSend[] memory sends, Signature[] memory signatures ) external { require( sends.length > 0 && sends.length == signatures.length, "ERC20-6" ); for (uint256 i = 0; i < sends.length; i++) { boostedSend(sends[i], signatures[i]); } } /** * @dev Perform multiple `boostedBurn` calls in a single transaction. * * NOTE: Booster extension */ function boostedBurnBatch( BoostedBurn[] memory burns, Signature[] memory signatures ) external { require( burns.length > 0 && burns.length == signatures.length, "ERC20-6" ); for (uint256 i = 0; i < burns.length; i++) { boostedBurn(burns[i], signatures[i]); } } /** * @dev Send `amount` tokens from `sender` to recipient`. * The `sender` must be opted-in and the `msg.sender` must be a trusted booster. * * NOTE: Booster extension */ function boostedSend(BoostedSend memory send, Signature memory signature) public { address from = send.sender; address to = send.recipient; UnpackedData memory unpackedFrom = _unpackPackedData(_packedData[from]); UnpackedData memory unpackedTo = _unpackPackedData(_packedData[to]); // We verify the nonce separately, since it's stored next to the balance _verifyNonce(send.boosterPayload, unpackedFrom.nonce); _verifyBoostWithoutNonce( send.sender, hashBoostedSend(send, msg.sender), send.boosterPayload, signature ); FuelBurn memory fuelBurn = _burnBoostedSendFuel( from, send.fuel, unpackedFrom ); _moveUnpacked({ from: send.sender, unpackedFrom: unpackedFrom, to: send.recipient, unpackedTo: unpackedTo, amount: send.amount, fuelBurn: fuelBurn, incrementNonce: true }); } /** * @dev Burn the fuel of a `boostedSend`. Returns a `FuelBurn` struct containing information about the burn. */ function _burnBoostedSendFuel( address from, BoosterFuel memory fuel, UnpackedData memory unpacked ) internal virtual returns (FuelBurn memory); /** * @dev Burn `amount` tokens from `account`. * The `account` must be opted-in and the `msg.sender` must be a trusted booster. * * NOTE: Booster extension */ function boostedBurn( BoostedBurn memory message, // A signature, that is compared against the function payload and only accepted if signed by 'sender' Signature memory signature ) public { address from = message.account; UnpackedData memory unpacked = _unpackPackedData(_packedData[from]); // We verify the nonce separately, since it's stored next to the balance _verifyNonce(message.boosterPayload, unpacked.nonce); _verifyBoostWithoutNonce( message.account, hashBoostedBurn(message, msg.sender), message.boosterPayload, signature ); FuelBurn memory fuelBurn = _burnBoostedBurnFuel( from, message.fuel, unpacked ); _burnUnpacked({ from: message.account, unpacked: unpacked, amount: message.amount, data: message.data, incrementNonce: true, fuelBurn: fuelBurn }); } /** * @dev Burn the fuel of a `boostedSend`. Returns a `FuelBurn` struct containing information about the burn. */ function _burnBoostedBurnFuel( address from, BoosterFuel memory fuel, UnpackedData memory unpacked ) internal virtual returns (FuelBurn memory); function burnFuel(address from, TokenFuel memory fuel) external virtual override {} //--------------------------------------------------------------- /** * @dev Get the allowance of `spender` for `holder` */ function allowance(address holder, address spender) public override(IBoostableERC20, IERC20) view returns (uint256) { return _allowances[holder][spender]; } /** * @dev Increase the allowance of `spender` by `value` for msg.sender */ function approve(address spender, uint256 value) public override(IBoostableERC20, IERC20) returns (bool) { address holder = msg.sender; _assertSenderRecipient(holder, spender); _approve(holder, spender, value); 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) { _assertSenderRecipient(msg.sender, spender); _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 virtual returns (bool) { _assertSenderRecipient(msg.sender, spender); _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20-18") ); return true; } /** * @dev Transfer `amount` from `holder` to `recipient`. * * `msg.sender` requires an allowance >= `amount` of `holder`. */ function transferFrom( address holder, address recipient, uint256 amount ) public override(IBoostableERC20, IERC20) returns (bool) { _assertSenderRecipient(holder, recipient); address spender = msg.sender; // Create pending transfer if the token holder is opted-in and the permaboost is active IOptIn.OptInStatus memory optInStatus = getOptInStatus(holder); if (optInStatus.isOptedIn && optInStatus.permaBoostActive) { // Ignore allowances if holder is opted-in require(holder == spender, "ERC20-7"); _createPendingTransfer({ opType: OP_TYPE_SEND, spender: spender, from: holder, to: recipient, amount: amount, data: "", optInStatus: optInStatus }); return true; } // Not opted-in, but we still need to check approval of the given spender _approve( holder, spender, _allowances[holder][spender].sub(amount, "ERC20-4") ); _move({from: holder, to: recipient, amount: amount}); return true; } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param incrementNonce whether to increment the nonce or not - only true for boosted burns */ function _burn( address from, uint256 amount, bytes memory data, bool incrementNonce ) internal virtual { require(from != address(0), "ERC20-8"); UnpackedData memory unpacked = _unpackPackedData(_packedData[from]); // Empty fuel burn FuelBurn memory fuelBurn; _burnUnpacked({ from: from, unpacked: unpacked, amount: amount, data: data, incrementNonce: incrementNonce, fuelBurn: fuelBurn }); } function _burnUnpacked( address from, UnpackedData memory unpacked, uint256 amount, bytes memory data, bool incrementNonce, FuelBurn memory fuelBurn ) internal { // _beforeBurn allows deriving contracts to run additional logic and affect the amount // that is actually getting burned. E.g. when burning PRPS, a portion of it might be taken // from the `hodlBalance`. Thus the returned `burnAmount` overrides `amount` and will be // subtracted from the actual `balance`. uint96 actualBurnAmount = _beforeBurn({ from: from, unpacked: unpacked, transferAmount: uint96(amount), occupiedAmount: 0, createdAt: uint32(block.timestamp), fuelBurn: fuelBurn, finalizing: false }); // Update to new balance if (incrementNonce) { // The nonce uses 64 bits, so a overflow is pretty much impossible // via increments of 1. unpacked.nonce++; } if (actualBurnAmount > 0) { require(unpacked.balance >= actualBurnAmount, "ERC20-9"); unpacked.balance -= actualBurnAmount; } // Update packed data by writing to storage _packedData[from] = _packUnpackedData(unpacked); // Total supply can be updated in batches elsewhere, shaving off another >5k gas. // _totalSupply = _totalSupply.sub(amount); // The `Burned` event is emitted with the total amount that got burned. // Furthermore, the fuel used is encoded in the upper bits. uint256 amountAndFuel; // Set first 96 bits to amount amountAndFuel |= uint96(amount); // Set next 3 bits to fuel type uint8 fuelType = uint8(fuelBurn.fuelType); amountAndFuel |= uint256(fuelType) << 96; // Set next 96 bits to fuel amount amountAndFuel |= uint256(fuelBurn.amount) << (96 + 3); emit Burned(amountAndFuel, data); // We emit a transfer event with the actual burn amount excluding burned `hodlBalance`. emit Transfer(from, address(0), actualBurnAmount); } /** * @dev Allow deriving contracts to prepare a burn. By default it behaves like an identity function * and just returns the amount passed in. */ function _beforeBurn( address from, UnpackedData memory unpacked, uint96 transferAmount, uint96 occupiedAmount, uint32 createdAt, FuelBurn memory fuelBurn, bool finalizing ) internal virtual returns (uint96) { return transferAmount; } function _move( address from, address to, uint256 amount ) internal { UnpackedData memory unpackedFrom = _unpackPackedData(_packedData[from]); UnpackedData memory unpackedTo = _unpackPackedData(_packedData[to]); // Empty fuel burn FuelBurn memory fuelBurn; _moveUnpacked({ from: from, unpackedFrom: unpackedFrom, to: to, unpackedTo: unpackedTo, amount: amount, incrementNonce: false, fuelBurn: fuelBurn }); } function _moveUnpacked( address from, UnpackedData memory unpackedFrom, address to, UnpackedData memory unpackedTo, uint256 amount, bool incrementNonce, FuelBurn memory fuelBurn ) internal { require(from != to, "ERC20-19"); // Increment nonce of sender if it's a boosted send if (incrementNonce) { // The nonce uses 64 bits, so a overflow is pretty much impossible // via increments of 1. unpackedFrom.nonce++; } // Check if sender has enough tokens uint96 transferAmount = uint96(amount); require(unpackedFrom.balance >= transferAmount, "ERC20-10"); // Subtract transfer amount from sender balance unpackedFrom.balance -= transferAmount; // Check that recipient balance doesn't overflow uint96 updatedRecipientBalance = unpackedTo.balance + transferAmount; require(updatedRecipientBalance >= unpackedTo.balance, "ERC20-12"); unpackedTo.balance = updatedRecipientBalance; _packedData[from] = _packUnpackedData(unpackedFrom); _packedData[to] = _packUnpackedData(unpackedTo); // The transfer amount does not include any used fuel emit Transfer(from, to, transferAmount); } /** * @dev See {ERC20-_approve}. */ function _approve( address holder, address spender, uint256 value ) internal { _allowances[holder][spender] = value; emit Approval(holder, spender, value); } function _assertSenderRecipient(address sender, address recipient) private pure { require(sender != address(0) && recipient != address(0), "ERC20-13"); } /** * @dev Checks whether msg.sender is a deploy-time known contract or not. */ function _callerIsDeployTimeKnownContract() internal virtual view returns (bool) { if (msg.sender == _hodlAddress) { return true; } if (msg.sender == _externalAddress1) { return true; } if (msg.sender == _externalAddress2) { return true; } if (msg.sender == _externalAddress3) { return true; } return false; } //--------------------------------------------------------------- // Pending ops //--------------------------------------------------------------- /** * @dev Create a pending transfer */ function _createPendingTransfer( uint8 opType, address spender, address from, address to, uint256 amount, bytes memory data, IOptIn.OptInStatus memory optInStatus ) private { OpHandle memory opHandle = _createNewOpHandle( optInStatus, from, opType ); PendingTransfer memory pendingTransfer = _createPendingTransferInternal( opHandle, spender, from, to, amount, data ); _pendingTransfers[_getOpKey(from, opHandle.opId)] = pendingTransfer; // Emit PendingOp event emit PendingOp(from, opHandle.opId, opHandle.opType); } /** * @dev Create a pending transfer by moving the funds of `spender` to this contract. * Deriving contracts may override this function. */ function _createPendingTransferInternal( OpHandle memory opHandle, address spender, address from, address to, uint256 amount, bytes memory data ) internal virtual returns (PendingTransfer memory) { // Move funds into this contract // Reverts if `from` has less than `amount` tokens. _move({from: from, to: address(this), amount: amount}); // Create op PendingTransfer memory pendingTransfer = PendingTransfer({ transferAmount: uint96(amount), spender: spender, occupiedAmount: 0, to: to, data: data }); return pendingTransfer; } /** * @dev Finalize a pending op */ function finalizePendingOp(address user, OpHandle memory opHandle) public { uint8 opType = opHandle.opType; // Assert that the caller (msg.sender) is allowed to finalize the given op uint32 createdAt = uint32(_assertCanFinalize(user, opHandle)); // Reverts if opId doesn't exist PendingTransfer storage pendingTransfer = _safeGetPendingTransfer( user, opHandle.opId ); // Cleanup // NOTE: We do not delete the pending transfer struct, because it only makes it // more expensive since we already hit the gas refund limit. // // delete _pendingTransfers[_getOpKey(user, opHandle.opId)]; // // The difference is ~13k gas. // // Deleting the op handle is enough to invalidate an opId forever: _deleteOpHandle(user, opHandle); // Call op type specific finalize if (opType == OP_TYPE_SEND) { _finalizeTransferOp(pendingTransfer, user, createdAt); } else if (opType == OP_TYPE_BURN) { _finalizePendingBurn(pendingTransfer, user, createdAt); } else { revert("ERC20-15"); } // Emit event emit FinalizedOp(user, opHandle.opId, opType); } /** * @dev Finalize a pending transfer */ function _finalizeTransferOp( PendingTransfer storage pendingTransfer, address from, uint32 createdAt ) private { address to = pendingTransfer.to; uint96 transferAmount = pendingTransfer.transferAmount; address _this = address(this); UnpackedData memory unpackedThis = _unpackPackedData( _packedData[_this] ); UnpackedData memory unpackedTo = _unpackPackedData(_packedData[to]); // Check that sender balance does not overflow require(unpackedThis.balance >= transferAmount, "ERC20-2"); unpackedThis.balance -= transferAmount; // Check that recipient doesn't overflow uint96 updatedBalanceRecipient = unpackedTo.balance + transferAmount; require(updatedBalanceRecipient >= unpackedTo.balance, "ERC20-2"); unpackedTo.balance = updatedBalanceRecipient; _packedData[_this] = _packUnpackedData(unpackedThis); _packedData[to] = _packUnpackedData(unpackedTo); // Transfer event is emitted with original sender emit Transfer(from, to, transferAmount); } /** * @dev Finalize a pending burn */ function _finalizePendingBurn( PendingTransfer storage pendingTransfer, address from, uint32 createdAt ) private { uint96 transferAmount = pendingTransfer.transferAmount; // We pass the packedData of `from` to `_beforeBurn`, because it PRPS needs to update // the `hodlBalance` which is NOT on the contract's own packedData. UnpackedData memory unpackedFrom = _unpackPackedData(_packedData[from]); // Empty fuel burn FuelBurn memory fuelBurn; uint96 burnAmountExcludingLockedPrps = _beforeBurn({ from: from, unpacked: unpackedFrom, transferAmount: transferAmount, occupiedAmount: pendingTransfer.occupiedAmount, createdAt: createdAt, fuelBurn: fuelBurn, finalizing: true }); // Update to new balance // NOTE: We change the balance of this contract, because that's where // the pending PRPS went to. address _this = address(this); UnpackedData memory unpackedOfContract = _unpackPackedData( _packedData[_this] ); require( unpackedOfContract.balance >= burnAmountExcludingLockedPrps, "ERC20-2" ); unpackedOfContract.balance -= burnAmountExcludingLockedPrps; _packedData[_this] = _packUnpackedData(unpackedOfContract); _packedData[from] = _packUnpackedData(unpackedFrom); // Furthermore, total supply can be updated elsewhere, shaving off another >5k gas. // _totalSupply = _totalSupply.sub(amount); // Emit events using the same `transferAmount` instead of what `_beforeBurn` // returned which is only used for updating the balance correctly. emit Burned(transferAmount, pendingTransfer.data); emit Transfer(from, address(0), transferAmount); } /** * @dev Revert a pending operation. * * Only the opted-in booster can revert a transaction if it provides a signed and still valid booster message * from the original sender. */ function revertPendingOp( address user, OpHandle memory opHandle, bytes memory boosterMessage, Signature memory signature ) public { // Prepare revert, including permission check and prevents reentrancy for same opHandle. _prepareOpRevert({ user: user, opHandle: opHandle, boosterMessage: boosterMessage, signature: signature }); // Now perform the actual revert of the pending op _revertPendingOp(user, opHandle.opType, opHandle.opId); } /** * @dev Revert a pending transfer */ function _revertPendingOp( address user, uint8 opType, uint64 opId ) private { PendingTransfer storage pendingTransfer = _safeGetPendingTransfer( user, opId ); uint96 transferAmount = pendingTransfer.transferAmount; uint96 occupiedAmount = pendingTransfer.occupiedAmount; // Move funds from this contract back to the original sender. Transfers and burns // are reverted the same way. We only transfer back the `transferAmount` - that is the amount // that actually got moved into this contract. The occupied amount is released during `onRevertPendingOp` // by the deriving contract. _move({from: address(this), to: user, amount: transferAmount}); // Call hook to allow deriving contracts to perform additional cleanup _onRevertPendingOp(user, opType, opId, transferAmount, occupiedAmount); // NOTE: we do not clean up the ops mapping, because we already hit the // gas refund limit. // delete _pendingTransfers[_getOpKey(user, opHandle.opId)]; // Emit event emit RevertedOp(user, opId, opType); } /** * @dev Hook that is called during revert of a pending transfer. * Allows deriving contracts to perform additional cleanup. */ function _onRevertPendingOp( address user, uint8 opType, uint64 opId, uint96 transferAmount, uint96 occupiedAmount ) internal virtual {} /** * @dev Safely get a pending transfer. Reverts if it doesn't exist. */ function _safeGetPendingTransfer(address user, uint64 opId) private view returns (PendingTransfer storage) { PendingTransfer storage pendingTransfer = _pendingTransfers[_getOpKey( user, opId )]; require(pendingTransfer.spender != address(0), "ERC20-16"); return pendingTransfer; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ERC20.sol"; import "./Purpose.sol"; contract Dubi is ERC20 { Purpose private immutable _prps; constructor( uint256 initialSupply, address optIn, address purpose, address hodl, address externalAddress1, address externalAddress2, address externalAddress3 ) public ERC20( "Decentralized Universal Basic Income", "DUBI", optIn, hodl, externalAddress1, externalAddress2, externalAddress3 ) { _mintInitialSupply(msg.sender, initialSupply); _prps = Purpose(purpose); } function hodlMint(address to, uint256 amount) public { require(msg.sender == _hodlAddress, "DUBI-2"); _mint(to, amount); } function purposeMint(address to, uint256 amount) public { require(msg.sender == address(_prps), "DUBI-3"); _mint(to, amount); } function _callerIsDeployTimeKnownContract() internal override view returns (bool) { if (msg.sender == address(_prps)) { return true; } return super._callerIsDeployTimeKnownContract(); } //--------------------------------------------------------------- // Fuel //--------------------------------------------------------------- /** * @dev Burns `fuel` from `from`. Can only be called by one of the deploy-time known contracts. */ function burnFuel(address from, TokenFuel memory fuel) public override { require(_callerIsDeployTimeKnownContract(), "DUBI-1"); _burnFuel(from, fuel); } function _burnFuel(address from, TokenFuel memory fuel) private { require(fuel.amount <= MAX_BOOSTER_FUEL, "DUBI-5"); require(from != address(0) && from != msg.sender, "DUBI-6"); if (fuel.tokenAlias == TOKEN_FUEL_ALIAS_DUBI) { // Burn fuel from DUBI UnpackedData memory unpacked = _unpackPackedData(_packedData[from]); require(unpacked.balance >= fuel.amount, "DUBI-7"); unpacked.balance -= fuel.amount; _packedData[from] = _packUnpackedData(unpacked); return; } revert("DUBI-8"); } /** *@dev Burn the fuel of a `boostedSend` */ function _burnBoostedSendFuel( address from, BoosterFuel memory fuel, UnpackedData memory unpacked ) internal override returns (FuelBurn memory) { FuelBurn memory fuelBurn; if (fuel.dubi > 0) { require(fuel.dubi <= MAX_BOOSTER_FUEL, "DUBI-5"); // From uses his own DUBI to fuel the boost require(unpacked.balance >= fuelBurn.amount, "DUBI-7"); unpacked.balance -= fuel.dubi; fuelBurn.amount = fuel.dubi; fuelBurn.fuelType = FuelType.DUBI; return fuelBurn; } // If the fuel is PRPS, then we have to reach out to the PRPS contract. if (fuel.unlockedPrps > 0) { // Reverts if the requested amount cannot be burned _prps.burnFuel( from, TokenFuel({ tokenAlias: TOKEN_FUEL_ALIAS_UNLOCKED_PRPS, amount: fuel.unlockedPrps }) ); fuelBurn.amount = fuel.unlockedPrps; fuelBurn.fuelType = FuelType.UNLOCKED_PRPS; return fuelBurn; } if (fuel.lockedPrps > 0) { // Reverts if the requested amount cannot be burned _prps.burnFuel( from, TokenFuel({ tokenAlias: TOKEN_FUEL_ALIAS_LOCKED_PRPS, amount: fuel.lockedPrps }) ); fuelBurn.amount = fuel.lockedPrps; fuelBurn.fuelType = FuelType.LOCKED_PRPS; return fuelBurn; } // No fuel at all return fuelBurn; } /** *@dev Burn the fuel of a `boostedBurn` */ function _burnBoostedBurnFuel( address from, BoosterFuel memory fuel, UnpackedData memory unpacked ) internal override returns (FuelBurn memory) { FuelBurn memory fuelBurn; // If the fuel is DUBI, then we can remove it directly if (fuel.dubi > 0) { require(fuel.dubi <= MAX_BOOSTER_FUEL, "DUBI-5"); require(unpacked.balance >= fuel.dubi, "DUBI-7"); unpacked.balance -= fuel.dubi; fuelBurn.amount = fuel.dubi; fuelBurn.fuelType = FuelType.DUBI; return fuelBurn; } // If the fuel is PRPS, then we have to reach out to the PRPS contract. if (fuel.unlockedPrps > 0) { // Reverts if the requested amount cannot be burned _prps.burnFuel( from, TokenFuel({ tokenAlias: TOKEN_FUEL_ALIAS_UNLOCKED_PRPS, amount: fuel.unlockedPrps }) ); fuelBurn.amount = fuel.unlockedPrps; fuelBurn.fuelType = FuelType.UNLOCKED_PRPS; return fuelBurn; } if (fuel.lockedPrps > 0) { // Reverts if the requested amount cannot be burned _prps.burnFuel( from, TokenFuel({ tokenAlias: TOKEN_FUEL_ALIAS_LOCKED_PRPS, amount: fuel.lockedPrps }) ); // No direct fuel, but we still return a indirect fuel so that it can be added // to the burn event. fuelBurn.amount = fuel.lockedPrps; fuelBurn.fuelType = FuelType.LOCKED_PRPS; return fuelBurn; } // DUBI has no intrinsic fuel if (fuel.intrinsicFuel > 0) { revert("DUBI-8"); } // No fuel at all return fuelBurn; } //--------------------------------------------------------------- // Pending ops //--------------------------------------------------------------- function _getHasherContracts() internal override returns (address[] memory) { address[] memory hashers = new address[](5); hashers[0] = address(this); hashers[1] = address(_prps); hashers[2] = _hodlAddress; hashers[3] = _externalAddress1; hashers[4] = _externalAddress2; return hashers; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IHodl { /** * @dev Lock the given amount of PRPS for the specified period (or infinitely) * for DUBI. */ function hodl( uint24 id, uint96 amountPrps, uint16 duration, address dubiBeneficiary, address prpsBeneficiary ) external; /** * @dev Release a hodl of `prpsBeneficiary` with the given `creator` and `id`. */ function release( uint24 id, address prpsBeneficiary, address creator ) external; /** * @dev Withdraw can be used to withdraw DUBI from infinitely locked PRPS. * The amount of DUBI withdrawn depends on the time passed since the last withdrawal. */ function withdraw( uint24 id, address prpsBeneficiary, address creator ) external; /** * @dev Burn `amount` of `from`'s locked and/or pending PRPS. * * This function is supposed to be only called by the PRPS contract. * * Returns the amount of DUBI that needs to be minted. */ function burnLockedPrps( address from, uint96 amount, uint32 dubiMintTimestamp, bool burnPendingLockedPrps ) external returns (uint96); /** * @dev Set `amount` of `from`'s locked PRPS to pending. * * This function is supposed to be only called by the PRPS contract. * * Returns the amount of locked PRPS that could be set to pending. */ function setLockedPrpsToPending(address from, uint96 amount) external; /** * @dev Revert `amount` of `from`'s pending locked PRPS to not pending. * * This function is supposed to be only called by the PRPS contract and returns */ function revertLockedPrpsSetToPending(address account, uint96 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // NOTE: we ignore leap-seconds etc. library MintMath { // The maximum number of seconds per month (365 * 24 * 60 * 60 / 12) uint32 public constant SECONDS_PER_MONTH = 2628000; // The maximum number of days PRPS can be finitely locked for uint16 public constant MAX_FINITE_LOCK_DURATION_DAYS = 365; // The maximum number of seconds PRPS can be finitely locked for uint32 public constant MAX_FINITE_LOCK_DURATION_SECONDS = uint32( MAX_FINITE_LOCK_DURATION_DAYS ) * 24 * 60 * 60; /** * @dev Calculates the DUBI to mint based on the given amount of PRPS and duration in days. * NOTE: We trust the caller to ensure that the duration between 1 and 365. */ function calculateDubiToMintByDays( uint256 amountPrps, uint16 durationInDays ) internal pure returns (uint96) { uint32 durationInSeconds = uint32(durationInDays) * 24 * 60 * 60; return calculateDubiToMintBySeconds(amountPrps, durationInSeconds); } /** * @dev Calculates the DUBI to mint based on the given amount of PRPS and duration in seconds. */ function calculateDubiToMintBySeconds( uint256 amountPrps, uint32 durationInSeconds ) internal pure returns (uint96) { // NOTE: We do not use safe math for efficiency reasons uint256 _percentage = percentage( durationInSeconds, MAX_FINITE_LOCK_DURATION_SECONDS, 18 // precision in WEI, 10^18 ) * 4; // A full lock grants 4%, so multiply by 4. // Multiply PRPS by the percentage and then divide by the precision (=10^8) // from the previous step uint256 _dubiToMint = (amountPrps * _percentage) / (1 ether * 100); // multiply by 100, because we deal with percentages // Assert that the calculated DUBI never overflows uint96 assert(_dubiToMint < 2**96); return uint96(_dubiToMint); } function calculateDubiToMintMax(uint96 amount) internal pure returns (uint96) { return calculateDubiToMintBySeconds( amount, MAX_FINITE_LOCK_DURATION_SECONDS ); } function calculateMintDuration(uint32 _now, uint32 lastWithdrawal) internal pure returns (uint32) { require(lastWithdrawal > 0 && lastWithdrawal <= _now, "MINT-1"); // NOTE: we don't use any safe math here for efficiency reasons. The assert above // is already a pretty good guarantee that nothing goes wrong. Also, all numbers involved // are very well smaller than uint256 in the first place. uint256 _elapsedTotal = _now - lastWithdrawal; uint256 _proRatedYears = _elapsedTotal / SECONDS_PER_MONTH / 12; uint256 _elapsedInYear = _elapsedTotal % MAX_FINITE_LOCK_DURATION_SECONDS; // // Examples (using months instead of seconds): // calculation formula: (monthsSinceWithdrawal % 12) + (_proRatedYears * 12) // 1) Burn after 11 months since last withdrawal (number of years = 11 / 12 + 1 = 1) // => (11 % 12) + (years * 12) => 23 months worth of DUBI // => 23 months // 1) Burn after 4 months since last withdrawal (number of years = 4 / 12 + 1 = 1) // => (4 % 12) + (years * 12) => 16 months worth of DUBI // => 16 months // 2) Burn 0 months after withdrawal after 4 months (number of years = 0 / 12 + 1 = 1): // => (0 % 12) + (years * 12) => 12 months worth of DUBI (+ 4 months worth of withdrawn DUBI) // => 16 months // 3) Burn after 36 months since last withdrawal (number of years = 36 / 12 + 1 = 4) // => (36 % 12) + (years * 12) => 48 months worth of DUBI // => 48 months // 4) Burn 1 month after withdrawal after 35 months (number of years = 1 / 12 + 1 = 1): // => (1 % 12) + (years * 12) => 12 month worth of DUBI (+ 35 months worth of withdrawn DUBI) // => 47 months uint32 _mintDuration = uint32( _elapsedInYear + _proRatedYears * MAX_FINITE_LOCK_DURATION_SECONDS ); return _mintDuration; } function percentage( uint256 numerator, uint256 denominator, uint256 precision ) internal pure returns (uint256) { return ((numerator * (uint256(10)**(precision + 1))) / denominator + 5) / uint256(10); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Token agnostic fuel struct that is passed around when the fuel is burned by a different (token) contract. // The contract has to explicitely support the desired token that should be burned. struct TokenFuel { // A token alias that must be understood by the target contract uint8 tokenAlias; uint96 amount; } /** * @dev Extends the interface of the ERC20 standard as defined in the EIP with * `boostedTransferFrom` to perform transfers without having to rely on an allowance. */ interface IBoostableERC20 { // ERC20 function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); // Extension /** * @dev Moves `amount` tokens from `sender` to `recipient`. * * If the caller is known by the callee, then the implementation should skip approval checks. * Also accepts a data payload, similar to ERC721's `safeTransferFrom` to pass arbitrary data. * */ function boostedTransferFrom( address sender, address recipient, uint256 amount, bytes calldata data ) external returns (bool); /** * @dev Burns `fuel` from `from`. */ function burnFuel(address from, TokenFuel memory fuel) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./Boostable.sol"; import "./BoostableLib.sol"; /** * @dev EIP712 boostable primitives related to ERC20 for the Purpose domain */ abstract contract BoostableERC20 is Boostable { /** * @dev A struct representing the payload of the ERC20 `boostedSend` function. */ struct BoostedSend { uint8 tag; address sender; address recipient; uint256 amount; bytes data; BoosterFuel fuel; BoosterPayload boosterPayload; } /** * @dev A struct representing the payload of the ERC20 `boostedBurn` function. */ struct BoostedBurn { uint8 tag; address account; uint256 amount; bytes data; BoosterFuel fuel; BoosterPayload boosterPayload; } uint8 internal constant BOOST_TAG_SEND = 0; uint8 internal constant BOOST_TAG_BURN = 1; bytes32 internal constant BOOSTED_SEND_TYPEHASH = keccak256( "BoostedSend(uint8 tag,address sender,address recipient,uint256 amount,bytes data,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)" ); bytes32 internal constant BOOSTED_BURN_TYPEHASH = keccak256( "BoostedBurn(uint8 tag,address account,uint256 amount,bytes data,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)" ); constructor(address optIn) public Boostable(optIn) {} /** * @dev Returns the hash of `boostedSend`. */ function hashBoostedSend(BoostedSend memory send, address booster) internal view returns (bytes32) { return BoostableLib.hashWithDomainSeparator( _DOMAIN_SEPARATOR, keccak256( abi.encode( BOOSTED_SEND_TYPEHASH, BOOST_TAG_SEND, send.sender, send.recipient, send.amount, keccak256(send.data), BoostableLib.hashBoosterFuel(send.fuel), BoostableLib.hashBoosterPayload( send.boosterPayload, booster ) ) ) ); } /** * @dev Returns the hash of `boostedBurn`. */ function hashBoostedBurn(BoostedBurn memory burn, address booster) internal view returns (bytes32) { return BoostableLib.hashWithDomainSeparator( _DOMAIN_SEPARATOR, keccak256( abi.encode( BOOSTED_BURN_TYPEHASH, BOOST_TAG_BURN, burn.account, burn.amount, keccak256(burn.data), BoostableLib.hashBoosterFuel(burn.fuel), BoostableLib.hashBoosterPayload( burn.boosterPayload, booster ) ) ) ); } /** * @dev Tries to interpret the given boosterMessage and * return it's hash plus creation timestamp. */ function decodeAndHashBoosterMessage( address targetBooster, bytes memory boosterMessage ) external override view returns (bytes32, uint64) { require(boosterMessage.length > 0, "PB-7"); uint8 tag = _readBoosterTag(boosterMessage); if (tag == BOOST_TAG_SEND) { BoostedSend memory send = abi.decode(boosterMessage, (BoostedSend)); return ( hashBoostedSend(send, targetBooster), send.boosterPayload.timestamp ); } if (tag == BOOST_TAG_BURN) { BoostedBurn memory burn = abi.decode(boosterMessage, (BoostedBurn)); return ( hashBoostedBurn(burn, targetBooster), burn.boosterPayload.timestamp ); } // Unknown tag, so just return an empty result return ("", 0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ProtectedBoostable.sol"; /** * @dev Purpose Boostable primitives using the EIP712 standard */ abstract contract Boostable is ProtectedBoostable { // "Purpose", "Dubi" and "Hodl" are all under the "Purpose" umbrella constructor(address optIn) public ProtectedBoostable( optIn, keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256("Purpose"), keccak256("1"), _getChainId(), address(this) ) ) ) {} // Fuel alias constants - used when fuel is burned from external contract calls uint8 internal constant TOKEN_FUEL_ALIAS_UNLOCKED_PRPS = 0; uint8 internal constant TOKEN_FUEL_ALIAS_LOCKED_PRPS = 1; uint8 internal constant TOKEN_FUEL_ALIAS_DUBI = 2; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; struct BoosterFuel { uint96 dubi; uint96 unlockedPrps; uint96 lockedPrps; uint96 intrinsicFuel; } struct BoosterPayload { address booster; uint64 timestamp; uint64 nonce; // Fallback for 'personal_sign' when e.g. using hardware wallets that don't support // EIP712 signing (yet). bool isLegacySignature; } // Library for Boostable hash functions that are completely inlined. library BoostableLib { bytes32 private constant BOOSTER_PAYLOAD_TYPEHASH = keccak256( "BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)" ); bytes32 internal constant BOOSTER_FUEL_TYPEHASH = keccak256( "BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)" ); /** * @dev Returns the hash of the packed DOMAIN_SEPARATOR and `messageHash` and is used for verifying * a signature. */ function hashWithDomainSeparator( bytes32 domainSeparator, bytes32 messageHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", domainSeparator, messageHash) ); } /** * @dev Returns the hash of `payload` using the provided booster (i.e. `msg.sender`). */ function hashBoosterPayload(BoosterPayload memory payload, address booster) internal pure returns (bytes32) { return keccak256( abi.encode( BOOSTER_PAYLOAD_TYPEHASH, booster, payload.timestamp, payload.nonce, payload.isLegacySignature ) ); } function hashBoosterFuel(BoosterFuel memory fuel) internal pure returns (bytes32) { return keccak256( abi.encode( BOOSTER_FUEL_TYPEHASH, fuel.dubi, fuel.unlockedPrps, fuel.lockedPrps, fuel.intrinsicFuel ) ); } /** * @dev Returns the tag found in the given `boosterMessage`. */ function _readBoosterTag(bytes memory boosterMessage) internal pure returns (uint8) { // The tag is either the 32th byte or the 64th byte depending on whether // the booster message contains dynamic bytes or not. // // If it contains a dynamic byte array, then the first word points to the first // data location. // // Therefore, we read the 32th byte and check if it's >= 32 and if so, // simply read the (32 + first word)th byte to get the tag. // // This imposes a limit on the number of tags we can support (<32), but // given that it is very unlikely for so many tags to exist it is fine. // // Read the 32th byte to get the tag, because it is a uint8 padded to 32 bytes. // i.e. // -----------------------------------------------------------------v // 0x0000000000000000000000000000000000000000000000000000000000000001 // ... // uint8 tag = uint8(boosterMessage[31]); if (tag >= 32) { // Read the (32 + tag) byte. E.g. if tag is 32, then we read the 64th: // -------------------------------------------------------------------- // 0x0000000000000000000000000000000000000000000000000000000000000020 | // 0000000000000000000000000000000000000000000000000000000000000001 < // ... // tag = uint8(boosterMessage[31 + tag]); } return tag; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./EIP712Boostable.sol"; import "./IOptIn.sol"; import "./ProtectedBoostableLib.sol"; abstract contract ProtectedBoostable is EIP712Boostable { //--------------------------------------------------------------- // State for non-boosted operations while opted-in and the OPT_IN permaboost is active //--------------------------------------------------------------- uint256 private constant MAX_PENDING_OPS = 25; // A mapping of account to an opCounter. mapping(address => OpCounter) internal _opCounters; // A mapping of account to an array containing all it's pending ops. mapping(address => OpHandle[]) internal _pendingOpsByAddress; // A mapping of keccak256(address,opId) to a struct holding metadata like the associated user account and creation timestamp. mapping(bytes32 => OpMetadata) internal _opMetadata; // Event that is emitted whenever a pending op is created // NOTE: returning an OpHandle in the event flattens it into an array for some reason // i.e. emit PendingOp(0x123.., OpHandle(1, 0)) => { from: 0x123, opHandle: ['1', '0']} event PendingOp(address from, uint64 opId, uint8 opType); // Event that is emitted whenever a pending op is finalized event FinalizedOp(address from, uint64 opId, uint8 opType); // Event that is emitted whenever a pending op is reverted event RevertedOp(address from, uint64 opId, uint8 opType); constructor(address optIn, bytes32 domainSeparator) public EIP712Boostable(optIn, domainSeparator) {} //--------------------------------------------------------------- // Pending ops //--------------------------------------------------------------- /** * @dev Returns the metadata of an op. Returns a zero struct if it doesn't exist. */ function getOpMetadata(address user, uint64 opId) public virtual view returns (OpMetadata memory) { return _opMetadata[_getOpKey(user, opId)]; } /** * @dev Returns the metadata of an op. Returns a zero struct if it doesn't exist. */ function getOpCounter(address user) public virtual view returns (OpCounter memory) { return _opCounters[user]; } /** * @dev Returns the metadata of an op. Reverts if it doesn't exist or * the opType mismatches. */ function safeGetOpMetadata(address user, OpHandle memory opHandle) public virtual view returns (OpMetadata memory) { OpMetadata storage metadata = _opMetadata[_getOpKey( user, opHandle.opId )]; // If 'createdAt' is zero, then it's non-existent for us require(metadata.createdAt > 0, "PB-1"); require(metadata.opType == opHandle.opType, "PB-2"); return metadata; } /** * @dev Get the next op id for `user` */ function _getNextOpId(address user) internal returns (uint64) { OpCounter storage counter = _opCounters[user]; // NOTE: we always increase by 1, so it cannot overflow as long as this // is the only place increasing the counter. uint64 nextOpId = counter.value + 1; // This also updates the nextFinalize/Revert values if (counter.nextFinalize == 0) { // Only gets updated if currently pointing to "nothing", because FIFO counter.nextFinalize = nextOpId; } // nextRevert is always updated to the new opId, because LIFO counter.nextRevert = nextOpId; counter.value = nextOpId; // NOTE: It is safe to downcast to uint64 since it's practically impossible to overflow. return nextOpId; } /** * @dev Creates a new opHandle with the given type for `user`. */ function _createNewOpHandle( IOptIn.OptInStatus memory optInStatus, address user, uint8 opType ) internal virtual returns (OpHandle memory) { uint64 nextOpId = _getNextOpId(user); OpHandle memory opHandle = OpHandle({opId: nextOpId, opType: opType}); // NOTE: we have a hard limit of 25 pending OPs and revert if that // limit is exceeded. require(_pendingOpsByAddress[user].length < MAX_PENDING_OPS, "PB-3"); address booster = optInStatus.optedInTo; _pendingOpsByAddress[user].push(opHandle); _opMetadata[_getOpKey(user, nextOpId)] = OpMetadata({ createdAt: uint64(block.timestamp), booster: booster, opType: opType }); return opHandle; } /** * @dev Delete the given `opHandle` from `user`. */ function _deleteOpHandle(address user, OpHandle memory opHandle) internal virtual { OpHandle[] storage _opHandles = _pendingOpsByAddress[user]; OpCounter storage opCounter = _opCounters[user]; ProtectedBoostableLib.deleteOpHandle( user, opHandle, _opHandles, opCounter, _opMetadata ); } /** * @dev Assert that the caller is allowed to finalize a pending op. * * Returns the user and createdAt timestamp of the op on success in order to * save some gas by minimizing redundant look-ups. */ function _assertCanFinalize(address user, OpHandle memory opHandle) internal returns (uint64) { OpMetadata memory metadata = safeGetOpMetadata(user, opHandle); uint64 createdAt = metadata.createdAt; // First check if the user is still opted-in. If not, then anyone // can finalize since it is no longer associated with the original booster. IOptIn.OptInStatus memory optInStatus = getOptInStatus(user); if (!optInStatus.isOptedIn) { return createdAt; } // Revert if not FIFO order _assertFinalizeFIFO(user, opHandle.opId); return ProtectedBoostableLib.assertCanFinalize(metadata, optInStatus); } /** * @dev Asserts that the caller (msg.sender) is allowed to revert a pending operation. * The caller must be opted-in by user and provide a valid signature from the user * that hasn't expired yet. */ function _assertCanRevert( address user, OpHandle memory opHandle, uint64 opTimestamp, bytes memory boosterMessage, Signature memory signature ) internal { // Revert if not LIFO order _assertRevertLIFO(user, opHandle.opId); IOptIn.OptInStatus memory optInStatus = getOptInStatus(user); require( optInStatus.isOptedIn && msg.sender == optInStatus.optedInTo, "PB-6" ); // In order to verify the boosterMessage, we need the hash and timestamp of when it // was signed. To interpret the boosterMessage, consult all available hasher contracts and // take the first non-zero result. address[] memory hasherContracts = _getHasherContracts(); // Call external library function, which performs the actual assertion. The reason // why it is not inlined, is that the need to reduce bytecode size. ProtectedBoostableLib.verifySignatureForRevert( user, opTimestamp, optInStatus, boosterMessage, hasherContracts, signature ); } function _getHasherContracts() internal virtual returns (address[] memory); /** * @dev Asserts that the given opId is the next to be finalized for `user`. */ function _assertFinalizeFIFO(address user, uint64 opId) internal virtual { OpCounter storage counter = _opCounters[user]; require(counter.nextFinalize == opId, "PB-9"); } /** * @dev Asserts that the given opId is the next to be reverted for `user`. */ function _assertRevertLIFO(address user, uint64 opId) internal virtual { OpCounter storage counter = _opCounters[user]; require(counter.nextRevert == opId, "PB-10"); } /** * @dev Prepare an op revert. * - Asserts that the caller is allowed to revert the given op * - Deletes the op handle to minimize risks of reentrancy */ function _prepareOpRevert( address user, OpHandle memory opHandle, bytes memory boosterMessage, Signature memory signature ) internal { OpMetadata memory metadata = safeGetOpMetadata(user, opHandle); _assertCanRevert( user, opHandle, metadata.createdAt, boosterMessage, signature ); // Delete opHandle, which prevents reentrancy since `safeGetOpMetadata` // will fail afterwards. _deleteOpHandle(user, opHandle); } /** * @dev Returns the hash of (user, opId) which is used as a look-up * key in the `_opMetadata` mapping. */ function _getOpKey(address user, uint64 opId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(user, opId)); } /** * @dev Deriving contracts can override this function to accept a boosterMessage for a given booster and * interpret it into a hash and timestamp. */ function decodeAndHashBoosterMessage( address targetBooster, bytes memory boosterMessage ) external virtual view returns (bytes32, uint64) {} /** * @dev Returns the tag found in the given `boosterMesasge`. */ function _readBoosterTag(bytes memory boosterMessage) internal pure returns (uint8) { // The tag is either the 32th byte or the 64th byte depending on whether // the booster message contains dynamic bytes or not. // // If it contains a dynamic byte array, then the first word points to the first // data location. // // Therefore, we read the 32th byte and check if it's >= 32 and if so, // simply read the (32 + first word)th byte to get the tag. // // This imposes a limit on the number of tags we can support (<32), but // given that it is very unlikely for so many tags to exist it is fine. // // Read the 32th byte to get the tag, because it is a uint8 padded to 32 bytes. // i.e. // -----------------------------------------------------------------v // 0x0000000000000000000000000000000000000000000000000000000000000001 // ... // uint8 tag = uint8(boosterMessage[31]); if (tag >= 32) { // Read the (32 + tag) byte. E.g. if tag is 32, then we read the 64th: // -------------------------------------------------------------------- // 0x0000000000000000000000000000000000000000000000000000000000000020 | // 0000000000000000000000000000000000000000000000000000000000000001 < // ... // tag = uint8(boosterMessage[31 + tag]); } return tag; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./IOptIn.sol"; import "./BoostableLib.sol"; import "./IBoostableERC20.sol"; /** * @dev Boostable base contract * * All deriving contracts are expected to implement EIP712 for the message signing. * */ abstract contract EIP712Boostable { using ECDSA for bytes32; // solhint-disable-next-line var-name-mixedcase IOptIn internal immutable _OPT_IN; // solhint-disable-next-line var-name-mixedcase bytes32 internal immutable _DOMAIN_SEPARATOR; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 private constant BOOSTER_PAYLOAD_TYPEHASH = keccak256( "BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)" ); bytes32 internal constant BOOSTER_FUEL_TYPEHASH = keccak256( "BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)" ); // The boost fuel is capped to 10 of the respective token that will be used for payment. uint96 internal constant MAX_BOOSTER_FUEL = 10 ether; // A magic booster permission prefix bytes6 private constant MAGIC_BOOSTER_PERMISSION_PREFIX = "BOOST-"; constructor(address optIn, bytes32 domainSeparator) public { _OPT_IN = IOptIn(optIn); _DOMAIN_SEPARATOR = domainSeparator; } // A mapping of mappings to keep track of used nonces by address to // protect against replays. Each 'Boostable' contract maintains it's own // state for nonces. mapping(address => uint64) private _nonces; //--------------------------------------------------------------- function getNonce(address account) external virtual view returns (uint64) { return _nonces[account]; } function getOptInStatus(address account) internal view returns (IOptIn.OptInStatus memory) { return _OPT_IN.getOptInStatus(account); } /** * @dev Called by every 'boosted'-function to ensure that `msg.sender` (i.e. a booster) is * allowed to perform the call for `from` (the origin) by verifying that `messageHash` * has been signed by `from`. Additionally, `from` provides a nonce to prevent * replays. Boosts cannot be verified out of order. * * @param from the address that the boost is made for * @param messageHash the reconstructed message hash based on the function input * @param payload the booster payload * @param signature the signature of `from` */ function verifyBoost( address from, bytes32 messageHash, BoosterPayload memory payload, Signature memory signature ) internal { uint64 currentNonce = _nonces[from]; require(currentNonce == payload.nonce - 1, "AB-1"); _nonces[from] = currentNonce + 1; _verifyBoostWithoutNonce(from, messageHash, payload, signature); } /** * @dev Verify a boost without verifying the nonce. */ function _verifyBoostWithoutNonce( address from, bytes32 messageHash, BoosterPayload memory payload, Signature memory signature ) internal view { // The sender must be the booster specified in the payload require(msg.sender == payload.booster, "AB-2"); (bool isOptedInToSender, uint256 optOutPeriod) = _OPT_IN.isOptedInBy( msg.sender, from ); // `from` must be opted-in to booster require(isOptedInToSender, "AB-3"); // The given timestamp must not be greater than `block.timestamp + 1 hour` // and at most `optOutPeriod(booster)` seconds old. uint64 _now = uint64(block.timestamp); uint64 _optOutPeriod = uint64(optOutPeriod); bool notTooFarInFuture = payload.timestamp <= _now + 1 hours; bool belowMaxAge = true; // Calculate the absolute difference. Because of the small tolerance, `payload.timestamp` // may be greater than `_now`: if (payload.timestamp <= _now) { belowMaxAge = _now - payload.timestamp <= _optOutPeriod; } // Signature must not be expired require(notTooFarInFuture && belowMaxAge, "AB-4"); // NOTE: Currently, hardware wallets (e.g. Ledger, Trezor) do not support EIP712 signing (specifically `signTypedData_v4`). // However, a user can still sign the EIP712 hash with the caveat that it's signed using `personal_sign` which prepends // the prefix '"\x19Ethereum Signed Message:\n" + len(message)'. // // To still support that, we add the prefix to the hash if `isLegacySignature` is true. if (payload.isLegacySignature) { messageHash = messageHash.toEthSignedMessageHash(); } // Valid, if the recovered address from `messageHash` with the given `signature` matches `from`. address signer = ecrecover( messageHash, signature.v, signature.r, signature.s ); if (!payload.isLegacySignature && signer != from) { // As a last resort we try anyway, in case the caller simply forgot the `isLegacySignature` flag. signer = ecrecover( messageHash.toEthSignedMessageHash(), signature.v, signature.r, signature.s ); } require(from == signer, "AB-5"); } /** * @dev Returns the hash of `payload` using the provided booster (i.e. `msg.sender`). */ function hashBoosterPayload(BoosterPayload memory payload, address booster) internal pure returns (bytes32) { return keccak256( abi.encode( BOOSTER_PAYLOAD_TYPEHASH, booster, payload.timestamp, payload.nonce ) ); } function _getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; struct Signature { bytes32 r; bytes32 s; uint8 v; } interface IOptIn { struct OptInStatus { bool isOptedIn; bool permaBoostActive; address optedInTo; uint32 optOutPeriod; } function getOptInStatusPair(address accountA, address accountB) external view returns (OptInStatus memory, OptInStatus memory); function getOptInStatus(address account) external view returns (OptInStatus memory); function isOptedInBy(address _sender, address _account) external view returns (bool, uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./IOptIn.sol"; struct OpHandle { uint8 opType; uint64 opId; } struct OpMetadata { uint8 opType; // the operation type uint64 createdAt; // the creation timestamp of an op address booster; // the booster at the time of when the op has been created } struct OpCounter { // The current value of the counter uint64 value; // Contains the opId that is to be finalized next - i.e. FIFO order uint64 nextFinalize; // Contains the opId that is to be reverted next - i.e. LIFO order uint64 nextRevert; } // Library containing public functions for pending ops - those will never be inlined // to reduce the bytecode size of individual contracts. library ProtectedBoostableLib { using ECDSA for bytes32; function deleteOpHandle( address user, OpHandle memory opHandle, OpHandle[] storage opHandles, OpCounter storage opCounter, mapping(bytes32 => OpMetadata) storage opMetadata ) public { uint256 length = opHandles.length; assert(length > 0); uint64 minOpId; // becomes next LIFO uint64 maxOpId; // becomes next FIFO // Pending ops are capped to MAX_PENDING_OPS. We always perform // MIN(length, MAX_PENDING_OPS) look-ups to do a "swap-and-pop" and // for updating the opCounter LIFO/FIFO pointers. for (uint256 i = 0; i < length; i++) { uint64 currOpId = opHandles[i].opId; if (currOpId == opHandle.opId) { // Overwrite item at i with last opHandles[i] = opHandles[length - 1]; // Continue, to ignore this opId when updating // minOpId and maxOpId. continue; } // Update minOpId if (minOpId == 0 || currOpId < minOpId) { minOpId = currOpId; } // Update maxOpId if (currOpId > maxOpId) { maxOpId = currOpId; } } // Might be 0 when everything got finalized/reverted opCounter.nextFinalize = minOpId; // Might be 0 when everything got finalized/reverted opCounter.nextRevert = maxOpId; // Remove the last item opHandles.pop(); // Remove metadata delete opMetadata[_getOpKey(user, opHandle.opId)]; } function assertCanFinalize( OpMetadata memory metadata, IOptIn.OptInStatus memory optInStatus ) public view returns (uint64) { // Now there are three valid scenarios remaining: // // - msg.sender is the original booster // - op is expired // - getBoosterAddress returns a different booster than the original booster // // In the second and third case, anyone can call finalize. address originalBooster = metadata.booster; if (originalBooster == msg.sender) { return metadata.createdAt; // First case } address currentBooster = optInStatus.optedInTo; uint256 optOutPeriod = optInStatus.optOutPeriod; bool isExpired = block.timestamp >= metadata.createdAt + optOutPeriod; if (isExpired) { return metadata.createdAt; // Second case } if (currentBooster != originalBooster) { return metadata.createdAt; // Third case } revert("PB-4"); } function verifySignatureForRevert( address user, uint64 opTimestamp, IOptIn.OptInStatus memory optInStatus, bytes memory boosterMessage, address[] memory hasherContracts, Signature memory signature ) public { require(hasherContracts.length > 0, "PB-12"); // Result of hasher contract call uint64 signedAt; bytes32 boosterHash; bool signatureVerified; for (uint256 i = 0; i < hasherContracts.length; i++) { // Call into the hasher contract and take the first non-zero result. // The contract must implement the following function: // // decodeAndHashBoosterMessage( // address targetBooster, // bytes memory boosterMessage // ) // // If it doesn't, then the call will fail (success=false) and we try the next one. // If it succeeds (success = true), then we try to decode the result. // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory result) = address(hasherContracts[i]) .call( // keccak256("decodeAndHashBoosterMessage(address,bytes)") abi.encodeWithSelector( 0xaf6eec54, msg.sender, /* msg.sender becomes the target booster */ boosterMessage ) ); if (!success) { continue; } // The result is exactly 2 words long = 512 bits = 64 bytes // 32 bytes for the expected message hash // 8 bytes (padded to 32 bytes) for the expected timestamp if (result.length != 64) { continue; } // NOTE: A contract with malintent could return any hash that we would // try to recover against. But there is no harm done in doing so since // the user must have signed it. // // However, it might return an unrelated timestamp, that the user hasn't // signed - so it could prolong the expiry of a signature which is a valid // concern whose risk we minimize by using also the op timestamp which guarantees // that a signature eventually expires. // Decode and recover signer (boosterHash, signedAt) = abi.decode(result, (bytes32, uint64)); address signer = ecrecover( boosterHash, signature.v, signature.r, signature.s ); if (user != signer) { // NOTE: Currently, hardware wallets (e.g. Ledger, Trezor) do not support EIP712 signing (specifically `signTypedData_v4`). // However, a user can still sign the EIP712 hash with the caveat that it's signed using `personal_sign` which prepends // the prefix '"\x19Ethereum Signed Message:\n" + len(message)'. // // To still support that, we also add the prefix and try to use the recovered address instead: signer = ecrecover( boosterHash.toEthSignedMessageHash(), signature.v, signature.r, signature.s ); } // If we recovered `user` from the signature, then we have a valid signature. if (user == signer) { signatureVerified = true; break; } // Keep trying } // Revert if signature couldn't be verified with any of the returned hashes require(signatureVerified, "PB-8"); // Lastly, the current time must not be older than: // MIN(opTimestamp, signedAt) + optOutPeriod * 3 uint64 _now = uint64(block.timestamp); // The maximum age is equal to whichever is lowest: // opTimestamp + optOutPeriod * 3 // signedAt + optOutPeriod * 3 uint64 maximumAge; if (opTimestamp > signedAt) { maximumAge = signedAt + uint64(optInStatus.optOutPeriod * 3); } else { maximumAge = opTimestamp + uint64(optInStatus.optOutPeriod * 3); } require(_now <= maximumAge, "PB-11"); } function _getOpKey(address user, uint64 opId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(user, opId)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
Check if sender has enough tokens
uint96 transferAmount = uint96(amount);
491,295
[ 1, 1564, 309, 5793, 711, 7304, 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, 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, 2254, 10525, 7412, 6275, 273, 2254, 10525, 12, 8949, 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 ]
./full_match/56/0x7fF40BAeFDFC4D776AcD69F33c839151070534FA/sources/contracts/MTCRewardContract_prod_02102023.sol
Check available amount Transfer tokens to the user
function claimN(uint256 _amount) external nonReentrant { address account = msg.sender; require(_amount > 0, string(abi.encodePacked("Amount must be greater than zero. Amount was: ", uint256ToString(_amount)))); uint256 amountInWei = _amount.mul(DECIMALS); uint256 accountBalance = acceptedToken.allowance(address(this), account); require(accountBalance >= amountInWei, string(abi.encodePacked("Insufficient balance for claim. Amount was: ", uint256ToString(amountInWei), "; Balance : ", uint256ToString(accountBalance)))); acceptedToken.safeTransferFrom(address(this), account, amountInWei); acceptedToken.safeDecreaseAllowance(account, amountInWei); }
3,254,279
[ 1, 1564, 2319, 3844, 12279, 2430, 358, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7516, 50, 12, 11890, 5034, 389, 8949, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 1758, 2236, 273, 1234, 18, 15330, 31, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 533, 12, 21457, 18, 3015, 4420, 329, 2932, 6275, 1297, 506, 6802, 2353, 3634, 18, 16811, 1703, 30, 3104, 2254, 5034, 5808, 24899, 8949, 3719, 10019, 203, 203, 3639, 2254, 5034, 3844, 382, 3218, 77, 273, 389, 8949, 18, 16411, 12, 23816, 55, 1769, 203, 3639, 2254, 5034, 2236, 13937, 273, 8494, 1345, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 2236, 1769, 203, 3639, 2583, 12, 4631, 13937, 1545, 3844, 382, 3218, 77, 16, 533, 12, 21457, 18, 3015, 4420, 329, 2932, 5048, 11339, 11013, 364, 7516, 18, 16811, 1703, 30, 3104, 2254, 5034, 5808, 12, 8949, 382, 3218, 77, 3631, 13636, 30918, 294, 3104, 2254, 5034, 5808, 12, 4631, 13937, 3719, 10019, 203, 203, 3639, 8494, 1345, 18, 4626, 5912, 1265, 12, 2867, 12, 2211, 3631, 2236, 16, 3844, 382, 3218, 77, 1769, 203, 3639, 8494, 1345, 18, 4626, 23326, 448, 7009, 1359, 12, 4631, 16, 3844, 382, 3218, 77, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-04-20 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // .;dkkkkkkkkkkkkkkkkkkd' .:xkkkkkkkkd, .:dk0XXXXXXXK0xdl,. .lxkkkkkkkkkkkkkkkkkk:.,okkkkkkko. .cxkkkkkkxc. ;dkkkkkko. // // ;xNMMMMMMMMMMMMMMMMMMMX: .:kNWMMMMMMMMWx. .l0NWWWWWMMMMMMMMMWNO;..lKWMMMMMMMMMMMMMMMMMMMKkKWMMMMMMMK, .c0WMMMMMMMMX: .;xXWMMMMMNo. // // .,lddddddddddddddddxKMMMK; .,lddddddx0WMMMX; .;llc::;;::cox0XWMMMMMWXdcoddddddddddddddddONMW0ddddddxXMMMK, .:odddddONMMMMO' .,lddddd0WWd. // // .. .dWWKl. . :XMMMWx. ... .,oKWMMMMWx. ,KMNc .kMMM0, .. .xWMMMWx'. 'kNk. // // .. .dKo' .. .xWMMMK; .. .'.. ,OWWMMWx. ,Okc' .kMMMK, .. ,0MMMMXl. .dNO' // // .. .:ooo;......,' . :XMMMWd. . .l0XXOc. ;xKMWNo. ,looc'......'... .kMMMK, .. cXMMM0, .oNK; // // .. '0MMMk. .. .kWMMMK,.' ;KMMMWNo. .;kNkc,. .dWMMK: .. .kMMMK, .. .dWMXc cXK: // // .. '0MMMXkxxxxxxxxd' . .:. cXMMMWd,' '0MMMMM0l;;;;;;:c;. .. .dWMMW0xxxxxxxxx; .kMMMK, .. 'ONd. :KXc // // .. '0MMMMMMMMMMMMMNc .. :O: .kMMMMK:. 'd0NWMWWWWWWWNXOl'... .dWMMMMMMMMMMMMWl .kMMMK, . :d' ;0No. // // .. .lkkkkkkkkkKWMMNc . .dNd. cNMMMWo.. .':dOXWMMMMMMMWXk:. :xkkkkkkkk0NMMWl .kMMMK, . . 'ONd. // // .. .oNMXd... '0M0' .kMMMM0, .. .;o0NMMMMMMWx. ,0MN0: .kMMMK, .. .kW0' // // .. cKk, . lNMNl cNMMMNo .',.. .;xXWMMMWx. 'O0c'. .kMMMK, .. .xWMO. // // .. .,ccc,.....,,. .. .kMMMk. .OMMMW0;'d0XX0xc,. :d0MMWx. ':cc:'....';. .. .kMMMK, .. .oNMMO. // // .. '0MMMk. .. ,kKKKk' lNMMMN0KWWWMMMWNKl. cXMWx. .dWMMX: .. .kMMMK, .. .OMMMO. // // .. '0MMMk'.......... ..... 'OMMKo:::::cxNMMMKl'. .OMWx. .dWMMXc.......... .kMMMK:.........,' .OMMMO. // // .. '0MMMNXKKKKKKKKd. lNM0' ;XMMMWN0c .OMWd. .dWMMWXKKKKKKKK0c .kMMMWXKKKKKKKKK0: .OMMMO. // // .. 'OWWWWWWWWWWMMNc 'llc' . '0MNc .kWMMMMX: ,KXx:. .oNWWWWWWWWWWMMWl .xWWWWWWWWWWWMMMN: .OMMMO. // // .. ,:::::::::cOWO. .xWWO' . oNMO' .lkOOx;. .'cd,... .::::::::::dXMWl '::::::::::xWMMX: .OMMWx. // // .. dNl ,0Xd. .. ,0MNo. . ..'. .. ,0WK: :NWOo, .OWKo. // // .' .oO, .co, .. .oOc.... ... .. ,xo,.. ckl..'. 'dd' // // ............................. .......... . .. . ..................... ..................... ......... // // // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * The contracts below implement a lazy-minted, randomized collection of ERC721A. * It requires that the creator knows the total number of NFTs they want and all belong to a token * directory, commonly will be an IPFS hash, with all the metadata from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint: * One allows the owner or alternate signer to approve single-use signatures for specific wallet addresses * The other allows a general mint, multi-use signature that anyone can use. * * Minting from this collection is always random, this can be done with either a reveal mechanism that * has an optional random offset, or on-chain randomness for revealed collections, or a mix of both! * * Only with a reveal mechanism, does the price of minting utilize ERC721A improvements. */ /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address internal _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. * * This ERC721A is set up to better handle batch transactions. It has two layers of optimization: * * First, it assumes tokens are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..) * which allows for up to 5 times cheaper MINT gas fees, but does increase first time TRANSFER gas fees. * Because of this, methods have also been optimized to only call ownerOf() once as it is not a direct lookup. * * Second, it allows a permanent switch to non-sequential mint with still reduced fees because the {_mint} * only updates {_owners} and not {_balances} so that a batch mint method can update _balances a single time. * * Additionally assumes that an owner cannot have more than 2**128 - 1 (max value of uint128) of supply. */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct AddressData { uint128 balance; uint128 numberMinted; } // Token name string internal _name; // Token symbol string internal _symbol; // Tracking total minted // Only used when `_isSequential` is false uint256 internal _totalMinted; // Tracking total burned uint256 internal _totalBurned; // Tracking the next sequential mint uint256 internal _nextSequential; // This ensures that ownerOf() can still run in constant time with a max runtime // of checking 5 values, but is up to 5 times cheaper on batch mints. uint256 internal constant SEQ_MINT_LIMIT = 5; // Tracking if the collection is still sequentially minted bool internal _notSequentialMint; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping from token ID to burned // This is necessary because to optimize gas fees for multiple mints a token with // `_owners[tokenId] = address(0)` is not necessarily a token with no owner. mapping(uint256 => bool) internal _burned; // Mapping owner address to token count mapping(address => AddressData) internal _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner].balance; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); if (_owners[tokenId] != address(0)) { return _owners[tokenId]; } if (tokenId < _nextSequential) { uint256 lowestTokenToCheck; if (tokenId >= SEQ_MINT_LIMIT) { lowestTokenToCheck = tokenId - SEQ_MINT_LIMIT + 1; } for (uint256 i = tokenId - 1; i >= lowestTokenToCheck; i--) { if (_owners[i] != address(0)) { return _owners[i]; } } } return address(0); } /** * @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 Returns the total current supply of the contract. * * WARNING - Underlying variables do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalSupply() public view virtual returns (uint256) { return totalMinted() - _totalBurned; } /** * @dev Returns the total ever minted from this contract. * * WARNING - Underlying variable do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalMinted() public view virtual returns (uint256) { if (_notSequentialMint) { return _totalMinted; } return _nextSequential; } /** * @dev returns how many tokens the given address has minted. */ function mintCount(address addr) external view returns (uint256) { return _balances[addr].numberMinted; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @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 { address owner = ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); require(owner == from, "ERC721: transfer of token that is not own"); _transferIgnoreOwner(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * This was modified to not call _safeTransfer because that would require fetching * ownerOf() twice which is more expensive than doing it together. * * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { address owner = ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); require(owner == from, "ERC721: transfer of token that is not own"); _safeTransferIgnoreOwner(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 This is for functions which already get the owner of the tokenId and can do the check * for `ownerOf(tokenId) == from` because ownerOf() in 721A is potentially an expensive function * and should not be called twice if not needed * * WARNING this method does not check for tokenOwner. This is done because with the * gas optimization calling ownerOf can be an expensive calculation and should only be done once (in the outer most layer) */ function _safeTransferIgnoreOwner( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transferIgnoreOwner(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) { if (_burned[tokenId]) { return false; } if (tokenId < _nextSequential) { return true; } return _owners[tokenId] != address(0); } /** * @dev Returns whether `sender` is allowed to manage `tokenId`. * This is for functions which already get the owner of the tokenId because ownerOf() in * 721A is potentially an expensive function and should not be called twice if not needed * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner( address sender, uint256 tokenId, address owner ) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); return (sender == owner || getApproved(tokenId) == sender || isApprovedForAll(owner, sender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * WARNING - this method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on batch transactions * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. * * WARNING: This method does not update totalSupply, please update that externally. Doing so * will allow us to save gas on batch transactions */ 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 * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(_notSequentialMint, "_notSequentialMint must be true"); require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } // Sequential mint doesn't match _beforeTokenTransfer and instead has a different optional override. function _beforeSequentialMint( address to, uint256 starting, uint256 quantity ) internal virtual {} /** * @dev Mints from `_nextSequential` to `_nextSequential + quantity` and transfers it to `to`. * * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _safeMintSequential(address to, uint256 quantity) internal virtual { require(!_notSequentialMint, "_notSequentialMint must be false"); require(to != address(0), "ERC721: mint to the zero address"); _beforeSequentialMint(to, _nextSequential, quantity); uint256 lastNum = _nextSequential + quantity; // ensures ownerOf runs quickly even if user is minting a large number like 100 for (uint256 i = _nextSequential; i < lastNum; i += SEQ_MINT_LIMIT) { _owners[i] = to; } // Gas is cheaper to have two separate for loops for (uint256 i = _nextSequential; i < lastNum; i++) { require( _checkOnERC721Received(address(0), to, i, ""), "ERC721: transfer to non ERC721Receiver implementer" ); emit Transfer(address(0), to, i); } _balances[to] = AddressData( _balances[to].balance + uint128(quantity), _balances[to].numberMinted + uint128(quantity) ); _nextSequential = lastNum; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. Since owners[tokenId] can be * the zero address for batch mints, this has been changed to modify _burned mapping instead * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "Caller is not owner nor approved" ); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId, owner); _balances[owner].balance -= 1; _totalBurned += 1; _burned[tokenId] = true; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); _transferIgnoreOwner(from, to, tokenId); } /** * @dev This is for functions which already get the owner of the tokenId and can do the check * for `ownerOf(tokenId) == from` because ownerOf() in 721A is potentially an expensive function * and should not be called twice if not needed * * WARNING this method does not check for tokenOwner. This is done because with the * gas optimization calling ownerOf can be an expensive calculation and should only be done once (in the outer most layer) */ function _transferIgnoreOwner( address from, address to, uint256 tokenId ) internal virtual { require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId, from); _balances[from].balance -= 1; _balances[to].balance += 1; _owners[tokenId] = to; uint256 nextTokenId = tokenId + 1; if (nextTokenId < _nextSequential) { if (_owners[nextTokenId] == address(0)) { _owners[nextTokenId] = from; } } emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) internal virtual { if (_tokenApprovals[tokenId] != to) { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); } } /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * ERC165 bytes to add to interface array - set in parent contract * implementing this standard * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; * _registerInterface(_INTERFACE_ID_ERC2981); */ /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param _tokenId - the NFT asset queried for royalty information * @param _salePrice - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } /** * @dev External interface of the EaselyPayout contract */ interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable( address primaryPayout, address[] memory royalties, uint256[] memory bps ) external payable; } /** * @dev Extension of the ERC721 contract that integrates a marketplace so that simple lazy-sales * do not have to be done on another contract. This saves gas fees on secondary sales because * buyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying. * * Easely will help power the lazy-selling as well as lazy minting that take place on * directly on the collection, which is why we take a cut of these transactions. Our cut can * be publically seen in the connected EaselyPayout contract and cannot exceed 5%. * * Owners also set a dual signer which they can change at any time. This dual signer helps enable * sales for large batches of addresses without needing to manually sign hundreds or thousands of hashes. * It also makes phishing scams harder as both signatures need to be compromised before an unwanted sale can occur. * * Owner also has an option to allow token owners to loan their tokens to other users which makes the token * untradeable until the original owner reclaims the token. */ abstract contract ERC721Marketplace is ERC721A, Ownable { using ECDSA for bytes32; using Strings for uint256; // Allows token owners to loan tokens to other addresses. bool public loaningActive; /* see {IEaselyPayout} for more */ address public constant PAYOUT_CONTRACT_ADDRESS = 0xa95850bB73459ADB9587A97F103a4A7CCe59B56E; uint256 private constant TIME_PER_DECREMENT = 300; /* Basis points or BPS are 1/100th of a percent, so 10000 basis points accounts for 100% */ uint256 public constant BPS_TOTAL = 10000; /* Max basis points for the owner for secondary sales of this collection */ uint256 public constant MAX_SECONDARY_BPS = 1000; /* Default payout percent if there is no signature set */ uint256 private constant DEFAULT_PAYOUT_BPS = 500; /* Signer for initializing splits to ensure splits were agreed upon by both parties */ address private constant VERIFIED_CONTRACT_SIGNER = 0x1BAAd9BFa20Eb279d2E3f3e859e3ae9ddE666c52; /* * Optional addresses to distribute referral commission for this collection * * Referral commission is taken from easely's cut */ address public referralAddress; /* * Optional addresses to distribute partnership comission for this collection * * Partnership commission is taken in addition to easely's cut */ address public partnershipAddress; /* Optional addresses to distribute revenue of primary sales of this collection */ address public revenueShareAddress; /* Enables dual address signatures to lazy mint */ address public dualSignerAddress; struct WithdrawSplits { /* Optional basis points for the owner for secondary sales of this collection */ uint64 ownerRoyaltyBPS; /* Basis points for easely's payout contract */ uint64 payoutBPS; /* Optional basis points for revenue sharing the owner wants to set up */ uint64 revenueShareBPS; /* * Optional basis points for collections that have been referred. * * Contracts with this will have a reduced easely's payout cut so that * the creator's cut is unaffected */ uint32 referralBPS; /* * Optional basis points for collections that require partnerships * * Contracts with this will have this fee on top of easely's payout cut because the partnership * will offer advanced web3 integration of this contract in some form beyond what easely provides. */ uint32 partnershipBPS; } WithdrawSplits public splits; mapping(uint256 => address) internal _tokenOwnersOnLoan; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) internal _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) internal _cancelledOrFinalizedSales; // Events related to lazy selling event SaleCancelled(address indexed seller, bytes32 hash); event SaleCompleted( address indexed seller, address indexed buyer, uint256 indexed tokenId, uint256 price, bytes32 hash ); // Events related to loaning event LoaningActive(bool active); event Loan( address indexed from, address indexed to, uint256 indexed tokenId ); event LoanRetrieved( address indexed from, address indexed to, uint256 indexed tokenId ); // Miscellaneous events event VersionChanged(address indexed seller, uint256 version); event DualSignerChanged(address newSigner); event BalanceWithdrawn(uint256 balance); event RoyaltyUpdated(uint256 bps); event WithdrawSplitsSet( address indexed revenueShareAddress, address indexed referralAddress, address indexed partnershipAddress, uint256 payoutBPS, uint256 revenueShareBPS, uint256 referralBPS, uint256 partnershipBPS ); /** * @dev initializes all of the addresses and percentage of withdrawn funds that * each address will get. These addresses and BPS splits must be signed by both the * verified easely wallet and the creator of the contract. If a signature is missing * the contract has a default of 5% to the easely payout wallet. */ function _initWithdrawSplits( address creator_, address revenueShareAddress_, address referralAddress_, address partnershipAddress_, uint256 payoutBPS_, uint256 ownerRoyaltyBPS_, uint256 revenueShareBPS_, uint256 referralBPS_, uint256 partnershipBPS_, bytes[2] memory signatures ) internal virtual { revenueShareAddress = revenueShareAddress_; require( ownerRoyaltyBPS_ <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries" ); if (signatures[1].length == 0) { require( DEFAULT_PAYOUT_BPS + revenueShareBPS_ <= BPS_TOTAL, "BPS splits too high" ); splits = WithdrawSplits( uint64(ownerRoyaltyBPS_), uint64(DEFAULT_PAYOUT_BPS), uint64(revenueShareBPS_), uint32(0), uint32(0) ); emit WithdrawSplitsSet( revenueShareAddress_, address(0), address(0), DEFAULT_PAYOUT_BPS, revenueShareBPS_, 0, 0 ); } else { require( payoutBPS_ + referralBPS_ + partnershipBPS_ + revenueShareBPS_ <= BPS_TOTAL, "BPS splits too high" ); bytes memory encoded = abi.encode( "InitializeSplits", creator_, revenueShareAddress_, referralAddress_, partnershipAddress_, payoutBPS_, revenueShareBPS_, referralBPS_, partnershipBPS_ ); bytes32 hash = ECDSA.toEthSignedMessageHash(keccak256(encoded)); require( hash.recover(signatures[0]) == creator_, "Not signed by creator" ); require( hash.recover(signatures[1]) == VERIFIED_CONTRACT_SIGNER, "Not signed by verified address" ); referralAddress = referralAddress_; partnershipAddress = partnershipAddress_; splits = WithdrawSplits( uint64(ownerRoyaltyBPS_), uint64(payoutBPS_), uint64(revenueShareBPS_), uint32(referralBPS_), uint32(partnershipBPS_) ); emit WithdrawSplitsSet( revenueShareAddress_, referralAddress_, partnershipAddress_, payoutBPS_, revenueShareBPS_, referralBPS_, partnershipBPS_ ); } emit RoyaltyUpdated(ownerRoyaltyBPS_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev see {IERC2981-supportsInterface} */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = (_salePrice * splits.ownerRoyaltyBPS) / BPS_TOTAL; return (owner(), royalty); } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * This function, while callable by anybody will always ONLY withdraw the * contract's balance to: * * the owner's account * the addresses the owner has set up for revenue share * the easely payout contract cut - capped at 5% but can be lower for some users * * This is callable by anybody so that Easely can set up automatic payouts * after a contract has reached a certain minimum to save creators the gas fees * involved in withdrawing balances. */ function withdrawBalance(uint256 withdrawAmount) external { if (withdrawAmount > address(this).balance) { withdrawAmount = address(this).balance; } uint256 payoutBasis = withdrawAmount / BPS_TOTAL; if (splits.revenueShareBPS > 0) { payable(revenueShareAddress).transfer( payoutBasis * splits.revenueShareBPS ); } if (splits.referralBPS > 0) { payable(referralAddress).transfer(payoutBasis * splits.referralBPS); } if (splits.partnershipBPS > 0) { payable(partnershipAddress).transfer( payoutBasis * splits.partnershipBPS ); } payable(PAYOUT_CONTRACT_ADDRESS).transfer( payoutBasis * splits.payoutBPS ); uint256 remainingAmount = withdrawAmount - payoutBasis * (splits.revenueShareBPS + splits.partnershipBPS + splits.referralBPS + splits.payoutBPS); payable(owner()).transfer(remainingAmount); emit BalanceWithdrawn(withdrawAmount); } /** * @dev Allows the owner to change who the dual signer is */ function setDualSigner(address alt) external onlyOwner { dualSignerAddress = alt; emit DualSignerChanged(alt); } /** * @dev see {_setSecondary} */ function setRoyaltiesBPS(uint256 newBPS) external onlyOwner { require( newBPS <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries" ); splits.ownerRoyaltyBPS = uint64(newBPS); emit RoyaltyUpdated(newBPS); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; emit VersionChanged(_msgSender(), version); } /** * @dev To be updated by contract owner to allow for the loan functionality to be toggled */ function setLoaningActive(bool _loaningActive) public onlyOwner { loaningActive = _loaningActive; emit LoaningActive(_loaningActive); } /** * @dev Returns who is loaning the given tokenId */ function tokenOwnerOnLoan(uint256 tokenId) external view returns (address) { require(_exists(tokenId), "This token does not exist"); return _tokenOwnersOnLoan[tokenId]; } /** * @notice Allow owner to loan their tokens to other addresses */ function loan(uint256 tokenId, address receiver) external { address msgSender = msg.sender; require(loaningActive, "Loans not active"); // Transfer the token // _safeTransfer checks that msgSender is the tokenOwner _safeTransfer(msgSender, receiver, tokenId, ""); // Add it to the mapping of originally loaned tokens _tokenOwnersOnLoan[tokenId] = msgSender; emit Loan(msgSender, receiver, tokenId); } /** * @notice Allow owner to loan their tokens to other addresses */ function retrieveLoan(uint256 tokenId) external { address borrowerAddress = ownerOf(tokenId); address msgSender = msg.sender; require( _tokenOwnersOnLoan[tokenId] == msgSender, "Sender is not the token loaner" ); // Remove it from the array of loaned out tokens delete _tokenOwnersOnLoan[tokenId]; // Transfer the token back _safeTransfer(borrowerAddress, msgSender, tokenId, ""); emit LoanRetrieved(borrowerAddress, msgSender, tokenId); } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = splits.ownerRoyaltyBPS; return ownerBPS; } /** * @dev See {ERC721-_beforeTokenTransfer}. * * makes sure tokens on loan can't be transferred */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721A) { super._beforeTokenTransfer(from, to, tokenId); require( _tokenOwnersOnLoan[tokenId] == address(0), "Cannot transfer token on loan" ); } /** * @dev Checks if an address is either the owner, or the approved alternate signer. */ function _checkValidSigner(address signer) internal view { require( signer == owner() || signer == dualSignerAddress, "Not valid signer." ); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps ) ); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheckForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForSale( owner, version, nonce, tokenId, pricesAndTimestamps ) ); } /** * @dev Current price for a sale which is calculated for the case of a descending sale. So * the ending price must be less than the starting price and the timestamp is active. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require( startingTimestamp < endingTimestamp, "Must end after it starts" ); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / TIME_PER_DECREMENT; if (decrements == 0) { return startingPrice; } // decrements will equal 0 before totalDecrements does so we will not divide by 0 uint256 totalDecrements = (endingTimestamp - startingTimestamp) / TIME_PER_DECREMENT; return startingPrice - (diff / totalDecrements) * decrements; } /** * @dev Checks if a hash has been signed by a signer, and if this contract has a dual signer, * that the dual signer has also signed the hash */ function _checkHashAndSignatures( bytes32 hash, address signer, bytes memory signature, bytes memory dualSignature ) internal view { require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require( hash.recover(signature) == signer, "Not signed by current owner" ); require( dualSignerAddress == address(0) || hash.recover(dualSignature) == dualSignerAddress, "Not signed by dual signer" ); } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token, but doing so will * invalidate the ability for others to buy. */ function hashToSignToSellToken( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require(_msgSender() == ownerOf(tokenId), "Not the owner of the token"); return _hashForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); } /** * @dev Usable to cancel hashes generated from {hashToSignToSellToken} */ function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. Tokens not owned by the contract owner are all considered secondary sales and * will give a cut to the owner of the contract based on the secondaryOwnerBPS. */ function buyToken( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, bytes memory signature, bytes memory dualSignature ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require( _addressToActiveVersion[seller] == version, "Incorrect signature version" ); require(msg.value >= currentPrice, "Not enough ETH to buy"); bytes32 hash = _hashToCheckForSale( seller, version, nonce, tokenId, pricesAndTimestamps ); _checkHashAndSignatures(hash, seller, signature, dualSignature); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(seller, _msgSender(), tokenId, currentPrice, hash); _safeTransfer(seller, _msgSender(), tokenId, ""); if (seller != owner()) { IEaselyPayout(PAYOUT_CONTRACT_ADDRESS).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); } payable(_msgSender()).transfer(msg.value - currentPrice); } } /** * @dev This implements a lazy-minted, randomized collection of ERC721A. * It requires that the creator knows the total number of NFTs they want and all belong to a token * directory, commonly will be an IPFS hash, with all the metadata from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint: * One allows the owner or alternate signer to approve single-use signatures for specific wallet addresses * The other allows a general mint, multi-use signature that anyone can use. * * Minting from this collection is always random, this can be done with either a reveal mechanism that * has an optional random offset, or on-chain randomness for revealed collections, or a mix of both! * * Only with a reveal mechanism, does the price of minting utilize ERC721A improvements. */ contract ERC721ARandomizedCollection is ERC721Marketplace { using ECDSA for bytes32; using Strings for uint256; bool public burnable; // This returns whether or not a collection has been locked yet bool public isLocked; /* * If this is set to true the owner must complete a signature for each address on the allowlist. * If it is false, only the dualSignerAddress is required, which can be a programatic signer the * owner is associted with that can easily sign tens of thousands of signatures. */ bool private requireOwnerOnAllowlist; bool private hasInit = false; uint256 public maxSupply; // Limits how much any single transaction can be uint256 public transactionMax; // Limits how much any single wallet can mint on a collection. uint256 public maxMint; // Used to shuffle tokenURI upon reveal uint256 public offset; // This limit is necessary for onchain randomness uint256 public constant MAX_SUPPLY_LIMIT = 10**9; // Mapping to enable constant time onchain randomness uint256[MAX_SUPPLY_LIMIT] private indices; string public tokenDirectory; // Randomized Collection Events event Minted( address indexed buyer, uint256 amount, uint256 unitPrice, bytes32 hash ); event TokensRevealed(string tokenDirectory); event TokenSupplyLocked(uint256 supply); event TokenDirectoryLocked(); event RequireOwnerOnAllowList(bool required); /** * @dev Constructor function */ constructor( bool[2] memory bools, address[4] memory addresses, uint256[8] memory uints, string[3] memory strings, bytes[2] memory signatures ) ERC721A(strings[0], strings[1]) { _init(bools, addresses, uints, strings, signatures); } function init( bool[2] memory bools, address[4] memory addresses, uint256[8] memory uints, string[3] memory strings, bytes[2] memory signatures ) external { _init(bools, addresses, uints, strings, signatures); } function _init( bool[2] memory bools, address[4] memory addresses, uint256[8] memory uints, string[3] memory strings, bytes[2] memory signatures ) internal { require(!hasInit, "Already has be initiated"); hasInit = true; burnable = bools[0]; _notSequentialMint = bools[1]; _owner = msg.sender; _initWithdrawSplits( _owner, addresses[0], // revenue share address addresses[1], // referral address addresses[2], // partnership address uints[0], // payout BPS uints[1], // owner secondary BPS uints[2], // revenue share BPS uints[3], // referral BPS uints[4], // partnership BPS signatures ); dualSignerAddress = addresses[3]; maxSupply = uints[5]; require(maxSupply < MAX_SUPPLY_LIMIT, "Collection is too big"); // Do not allow more than 500 mints a transaction so users cannot exceed gas limit if (uints[6] == 0 || uints[6] >= 500) { transactionMax = 500; } else { transactionMax = uints[6]; } maxMint = uints[7]; _name = strings[0]; _symbol = strings[1]; tokenDirectory = strings[2]; if (_notSequentialMint) { emit TokensRevealed(tokenDirectory); } } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } /** * @dev sets if the owner's signature is also necessary for dual signing. * * This is normally turned off because the dual signer can be an automated * process that can sign hundreds to thousands of sale permits instantly which * would be tedious for a human-operated wallet. */ function setRequireOwnerOnAllowlist(bool required) external onlyOwner { requireOwnerOnAllowlist = required; emit RequireOwnerOnAllowList(required); } /** * @dev If this collection was created with burnable on, owners of tokens * can use this method to burn their tokens. Easely will keep track of * burns in case creators want to reward users for burning tokens. */ function burn(uint256 tokenId) external { require(burnable, "Tokens from this collection are not burnable"); _burn(tokenId); } /** * @dev Method used if the creator wants to keep their collection hidden until * a later release date. On reveal, a collection no longer uses the mint savings * of ERC721A in favor of enabling on-chain randomness minting since the metadata * is no longer hidden. * * Additionally, this method has the option to set a random offset once upon reveal * but once that offset is set it cannot be changed to maintain user consistency. * * This method does not lock the tokenURI as there are cases when the initial metadata is * inaccurate and may need to be updated. The owner of the collection should call {lockTokenURI} * when they are certain of their metadata. */ function changeTokenURI( string calldata revealTokenDirectory, bool shouldOffset ) external onlyOwner { require(!isLocked, "The token URI has been locked"); if (shouldOffset && offset == 0) { offset = _random(maxSupply - 1) + 1; } tokenDirectory = revealTokenDirectory; _notSequentialMint = true; _totalMinted = _nextSequential; emit TokensRevealed(revealTokenDirectory); } /** * Prevents token metadata in this collection from ever changing. * * IMPORTANT - this function can only be called ONCE, if a wrong token directory * is submitted by the owner, it can NEVER be switched to a different one. */ function lockTokenURI() external onlyOwner { require(!isLocked, "Contract already locked"); isLocked = true; emit TokenDirectoryLocked(); } /** * Stops tokens from ever being minted past the current supply. * * IMPORTANT - this function can NEVER be undone. It is for collections * that have not sold out, and the owner choosing to essentially "burn" * the unminted tokens to give more value to the ones already minted. */ function lockTokenSupply() external onlyOwner { require(_notSequentialMint, "The token URI has not been set yet"); // This will lock the unminted tokens at reveal time maxSupply = _totalMinted; emit TokenSupplyLocked(_totalMinted); } /** * @dev tokenURI of a tokenId, will change to include the tokeId and an offset in * the URI once the collection has been revealed. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_notSequentialMint) { return string(abi.encodePacked(_baseURI(), tokenDirectory)); } require(_exists(tokenId), "URI query for nonexistent token"); uint256 offsetId = (tokenId + offset) % maxSupply; return string( abi.encodePacked( _baseURI(), tokenDirectory, "/", offsetId.toString() ) ); } /** * @dev Hash that the owner or alternate wallet must sign to enable a {mintAllow} for a user * @return Hash of message prefix and order hash per Ethereum format */ function _hashForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), allowedAddress, nonce, version, price, amount ) ); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForAllowList} to see the hash that needs to be signed. */ function _hashToCheckForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForAllowList(allowedAddress, nonce, version, price, amount) ); } /** * @dev Hash that the owner or approved alternate signer then sign that the approved buyer * can use in order to call the {mintAllow} method. */ function hashToSignForAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external view returns (bytes32) { _checkValidSigner(_msgSender()); return _hashForAllowList(allowedAddress, version, nonce, price, amount); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mintAllow} method. */ function cancelAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows a user with an approved signature to mint at a price and quantity specified by the * contract. A user is still limited by totalSupply, transactionMax, and mintMax if populated. * signing with amount = 0 will allow any buyAmount less than the other limits. */ function mintAllow( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount, uint256 buyAmount, bytes memory signature, bytes memory dualSignature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount <= amount && buyAmount > 0, "Invalid buyAmount"); require(buyAmount <= transactionMax, "Over transaction limit"); require( version == _addressToActiveVersion[owner()], "This presale version is disabled" ); require(allowedAddress == _msgSender(), "Invalid sender"); require(!Address.isContract(_msgSender()), "Cannot mint from contract"); uint256 totalPrice = price * buyAmount; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); require(!_cancelledOrFinalizedSales[hash], "Signature not active"); if (hash.recover(signature) != owner()) { require( !requireOwnerOnAllowlist && dualSignerAddress != address(0) && hash.recover(dualSignature) == dualSignerAddress, "Not signed by dual signer or owner" ); } _cancelledOrFinalizedSales[hash] = true; _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, price, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /** * @dev Hash that the owner or alternate wallet must sign to enable {mint} for all users */ function _hashForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), amount, pricesAndTimestamps, version ) ); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForMint} to see the hash that needs to be signed. */ function _hashToCheckForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForMint(version, amount, pricesAndTimestamps) ); } /** * @dev Hash that the owner or approved alternate signer then sign that buyers use * in order to call the {mint} method. */ function hashToSignForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { _checkValidSigner(_msgSender()); require(amount <= transactionMax, "Over transaction limit"); return _hashForMint(version, amount, pricesAndTimestamps); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mint} method. */ function cancelMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows anyone to buy an amount of tokens at a price which matches * the signature that the owner or alternate signer has approved */ function mint( uint256 version, uint256 amount, uint256 buyAmount, uint256[4] memory pricesAndTimestamps, bytes memory signature, bytes memory dualSignature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount != 0, "Invalid buyAmount"); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require(version == _addressToActiveVersion[owner()], "Invalid version"); require(!Address.isContract(_msgSender()), "Cannot mint from contract"); uint256 unitPrice = _currentPrice(pricesAndTimestamps); uint256 totalPrice = buyAmount * unitPrice; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); _checkHashAndSignatures(hash, owner(), signature, dualSignature); _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, unitPrice, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /// @notice Generates a pseudo random index of our tokens that has not been used so far function _mintRandomIndex(address buyer, uint256 amount) internal { // number of tokens left to create uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) { // generate a random index uint256 index = _random(supplyLeft); uint256 tokenAtPlace = indices[index]; uint256 tokenId; // if we havent stored a replacement token... if (tokenAtPlace == 0) { //... we just return the current index tokenId = index; } else { // else we take the replace we stored with logic below tokenId = tokenAtPlace; } // get the highest token id we havent handed out uint256 lastTokenAvailable = indices[supplyLeft - 1]; // we need to store a replacement token for the next time we roll the same index // if the last token is still unused... if (lastTokenAvailable == 0) { // ... we store the last token as index indices[index] = supplyLeft - 1; } else { // ... we store the token that was stored for the last token indices[index] = lastTokenAvailable; } _safeMint(buyer, tokenId + _nextSequential); supplyLeft--; } _balances[buyer] = AddressData( _balances[buyer].balance + uint128(amount), _balances[buyer].numberMinted + uint128(amount) ); } /// @notice Generates a pseudo random number based on arguments with decent entropy /// @param max The maximum value we want to receive /// @return A random number less than the max function _random(uint256 max) internal view returns (uint256) { if (max == 0) { return 0; } uint256 rand = uint256( keccak256( abi.encode( msg.sender, block.difficulty, block.timestamp, blockhash(block.number - 1) ) ) ); return rand % max; } /** * @dev Wrapper around {_mintRandomIndex} that incrementally if the collection has not * been revealed yet, which also checks the buyer has not exceeded maxMint count */ function _mintRandom(address buyer, uint256 amount) internal { require( maxMint == 0 || _balances[buyer].numberMinted + amount <= maxMint, "Buyer over mint maximum" ); if (_notSequentialMint) { _mintRandomIndex(buyer, amount); _totalMinted += amount; } else { _safeMintSequential(buyer, amount); } } }
* @dev helper method get secondary BPS into array form/
function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = splits.ownerRoyaltyBPS; return ownerBPS; }
6,735,448
[ 1, 4759, 707, 336, 9946, 605, 5857, 1368, 526, 646, 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, 389, 8443, 38, 5857, 1435, 2713, 1476, 1135, 261, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 2254, 5034, 8526, 3778, 3410, 38, 5857, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 3639, 3410, 38, 5857, 63, 20, 65, 273, 11019, 18, 8443, 54, 13372, 15006, 38, 5857, 31, 203, 3639, 327, 3410, 38, 5857, 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 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import { IFarmtroller } from './interfaces/IFarmtroller.sol'; import "hardhat/console.sol"; // We need to import the helper functions from the contract that we copy/pasted. import { Base64 } from "./libraries/Base64.sol"; contract Farmers is ERC721URIStorage, Ownable { using SafeMath for uint256; //Keeps track of how many minted uint256 public tokenIds = 0; //Keep track of circulating supply. Minted - Burned uint256 public supply = 0; //base URI string baseUri = ''; IFarmtroller Farmtroller; //price to mint. This should start at 2 avax and grow once funds have been invested along with the NAV //creates urgency to mint and rewards early adopters uint256 public constant firstFarmerPrice = 2000000000000000000; //2 AVAX bool invested = false; //max to purchase at a time uint256 public constant maxFarmerPurchase = 10; //determine how many there will uint256 public MAX_FARMERS; mapping (uint256 => uint256) used; bool public saleIsActive = false; event NFTMinted( address sender, uint256 tokenId ); event NFTBurned( uint256 tokenId ); constructor(uint256 maxNftSupply) ERC721("AVAX Farmers", "FRMR") { MAX_FARMERS = maxNftSupply; } function setFarmtroller(address payable _farmtroller) external onlyOwner { Farmtroller = IFarmtroller(_farmtroller); } function invested() external onlyOwner{ invested = true; } //withdrawas funds in contract to Farmtroller to be invested function withdraw() external onlyOwner { uint balance = address(this).balance; payable(address(Farmtroller)).transfer(balance); } function getSupply() external view returns(uint256) { return supply; } function numberMinted() external view returns(uint256) { return tokenIds; } function bal(address _address) external view returns (uint256) { return balanceOf(_address); } // Pause sale if active, make active if paused function flipSaleState() external onlyOwner { saleIsActive = !saleIsActive; } function _getBatchPrice(uint256 _n) public view returns (uint256) { uint256 totalPrice = 0; uint256 index = tokenIds; if(!invested){ totalPrice = _n.mul(firstFarmerPrice); } else { totalPrice = _n.mul(Farmtorller.NAV()); } console.log('total Price: ', totalPrice); return totalPrice; } function _imageId(uint256 _id) internal view returns (uint256) { //check mapping and find a image not yet used //means the id has not been used uint256 id = _id; while(used[id] != 0){ } return id; } function _enoughRandom() internal view returns (uint256) { if (MAX_FARMERS - tokenIds == 0) return 0; return uint256( keccak256( abi.encodePacked( block.difficulty, block.timestamp, msg.sender, blockhash(block.number) ) ) ) % (MAX_FARMERS); } //Mints nft'S //@dev still need to determine how to host Json with Moralis and include each item ID function mintFarmer(uint numberOfTokens) external payable { require(saleIsActive, "Sale must be active to mint Farmer"); require(numberOfTokens <= maxFarmerPurchase, "Can only mint 10 tokens at a time"); require(_getBatchPrice(numberOfTokens) <= msg.value, "AVAX value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint256 newItemId = tokenIds; require(newItemId < MAX_FARMERS, "All NFT's have been Minted"); //Need to generate name and image //uint256 id = _enoughRandom(); //uint256 imageId = _imageId(id); //encode the JSON file //poosibly take the newItemID and insert it into Moralis hosted url that points to specific image string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', // We set the title of our NFT . newItemId, '", "description": "A NFT collection to harvest the fields of AVAX and beyond.", "image":', baseUri, newItemId,'}' ) ) ) ); // Just like before, we prepend data:application/json;base64, to our data. string memory finalTokenUri = string( abi.encodePacked("data:application/json;base64,", json) ); _safeMint(msg.sender, newItemId); _setTokenURI(newItemId, finalTokenUri); tokenIds ++; supply ++; emit NFTMinted(msg.sender, newItemId); console.log("An NFT w/ ID %s has been minted to %s", newItemId, msg.sender); } payable(address(Farmtroller)).transfer(address(this).balance); } function burn(uint256 _tokenId) external { require(ownerOf(_tokenId) == msg.sender); _burn(_tokenId); //pull funds from Farmtroller based off of current value of the NFT Farmtroller.burningToken(msg.sender); //send funds equal to NFT NAV - royalty fee that goes to tresury to msg.sender supply -= 1; emit NFTBurned(_tokenId); } // Need this to receive ETH when `borrowEthExample` executes receive() external payable {} }
withdrawas funds in contract to Farmtroller to be invested
function withdraw() external onlyOwner { uint balance = address(this).balance; payable(address(Farmtroller)).transfer(balance); }
5,401,076
[ 1, 1918, 9446, 345, 284, 19156, 316, 6835, 358, 478, 297, 1010, 1539, 358, 506, 2198, 3149, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 3903, 1338, 5541, 288, 203, 3639, 2254, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 8843, 429, 12, 2867, 12, 17393, 1010, 1539, 13, 2934, 13866, 12, 12296, 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 ]
// File: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.8; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/access/Roles.sol /** * @title Roles * @notice copied from openzeppelin-solidity * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts/access/WhitelistAdminRole.sol /** * @title WhitelistAdminRole * @notice copied from openzeppelin-solidity * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: contracts/access/WhitelistedRole.sol /** * @title WhitelistedRole * @notice copied from openzeppelin-solidity * @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 Context, WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(_msgSender()), "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 onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(_msgSender()); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } } // File: contracts/oracle/ICADConversionOracle.sol /** * @title ICADRateOracle * @notice provides interface for converting USD stable coins to CAD */ interface ICADConversionOracle { /** * @notice convert USD amount to CAD amount * @param amount amount of USD in 18 decimal places * @return amount of CAD in 18 decimal places */ function usdToCad(uint256 amount) external view returns (uint256); /** * @notice convert Dai amount to CAD amount * @param amount amount of dai in 18 decimal places * @return amount of CAD in 18 decimal places */ function daiToCad(uint256 amount) external view returns (uint256); /** * @notice convert USDC amount to CAD amount * @param amount amount of USDC in 6 decimal places * @return amount of CAD in 18 decimal places */ function usdcToCad(uint256 amount) external view returns (uint256); /** * @notice convert USDT amount to CAD amount * @param amount amount of USDT in 6 decimal places * @return amount of CAD in 18 decimal places */ function usdtToCad(uint256 amount) external view returns (uint256); /** * @notice convert CAD amount to USD amount * @param amount amount of CAD in 18 decimal places * @return amount of USD in 18 decimal places */ function cadToUsd(uint256 amount) external view returns (uint256); /** * @notice convert CAD amount to Dai amount * @param amount amount of CAD in 18 decimal places * @return amount of Dai in 18 decimal places */ function cadToDai(uint256 amount) external view returns (uint256); /** * @notice convert CAD amount to USDC amount * @param amount amount of CAD in 18 decimal places * @return amount of USDC in 6 decimal places */ function cadToUsdc(uint256 amount) external view returns (uint256); /** * @notice convert CAD amount to USDT amount * @param amount amount of CAD in 18 decimal places * @return amount of USDT in 6 decimal places */ function cadToUsdt(uint256 amount) external view returns (uint256); } // File: contracts/oracle/ManagedCADChainlinkRateOracle.sol /** * @title ManagedCADChainlinkRateOracle * @notice Provides a USD/CAD rate source managed by admin, and Chainlink powered DAI/USDC/USDT conversion rates. * USDC is treated as always 1 USD, and used as anchor to calculate Dai and USDT rates */ contract ManagedCADChainlinkRateOracle is ICADConversionOracle, WhitelistedRole { using SafeMath for uint256; event ManagedRateUpdated(uint256 value, uint256 timestamp); // exchange rate stored as an integer uint256 public _USDToCADRate; // specifies how many decimal places have been converted into integer uint256 public _granularity; // specifies the time the exchange was last updated uint256 public _timestamp; // Chainlink price feed for Dai/Eth pair AggregatorV3Interface public daiEthPriceFeed; // Chainlink price feed for USDC/Eth pair AggregatorV3Interface public usdcEthPriceFeed; // Chainlink price feed for USDT/Eth pair AggregatorV3Interface public usdtEthPriceFeed; constructor( uint256 value, uint256 granularity, address daiEthAggregatorAddress, address usdcEthAggregatorAddress, address usdtEthAggregatorAddress ) public { _USDToCADRate = value; _granularity = granularity; _timestamp = block.timestamp; daiEthPriceFeed = AggregatorV3Interface(daiEthAggregatorAddress); usdcEthPriceFeed = AggregatorV3Interface(usdcEthAggregatorAddress); usdtEthPriceFeed = AggregatorV3Interface(usdtEthAggregatorAddress); _addWhitelisted(msg.sender); } /** * @notice admin can update the exchange rate * @param value the new exchange rate * @param granularity number of decimal places the exchange value is accurate to * @return true if success */ function updateManagedRate(uint256 value, uint256 granularity) external onlyWhitelisted returns (bool) { require(value > 0, "Exchange rate cannot be zero"); require(granularity > 0, "Granularity cannot be zero"); _USDToCADRate = value; _granularity = granularity; _timestamp = block.timestamp; emit ManagedRateUpdated(value, granularity); return true; } /** * @notice return the current managed values * @return latest USD to CAD exchange rate, granularity, and timestamp */ function getManagedRate() external view returns (uint256, uint256, uint256) { return (_USDToCADRate, _granularity, _timestamp); } /** * @notice convert USD amount to CAD amount * @param amount amount of USD in 18 decimal places * @return amount of CAD in 18 decimal places */ function usdToCad(uint256 amount) public view virtual override returns (uint256) { return amount.mul(_USDToCADRate).div(10 ** _granularity); } /** * @notice convert Dai amount to CAD amount * @param amount amount of dai in 18 decimal places * @return amount of CAD in 18 decimal places */ function daiToCad(uint256 amount) external view virtual override returns (uint256) { (, int256 daiEthPrice, , uint256 daiEthTimeStamp,) = daiEthPriceFeed.latestRoundData(); require(daiEthTimeStamp > 0, "Dai Chainlink Oracle data temporarily incomplete"); require(daiEthPrice > 0, "Invalid Chainlink Oracle Dai price"); (, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData(); require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete"); require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price"); return amount.mul(_USDToCADRate).mul(uint256(daiEthPrice)).div(uint256(usdcEthPrice)).div(10 ** _granularity); } /** * @notice convert USDC amount to CAD amount * @param amount amount of USDC in 6 decimal places * @return amount of CAD in 18 decimal places */ function usdcToCad(uint256 amount) external view virtual override returns (uint256) { // USDT has 6 decimals return usdToCad(amount.mul(1e12)); } /** * @notice convert USDT amount to CAD amount * @param amount amount of USDT in 6 decimal places * @return amount of CAD in 18 decimal places */ function usdtToCad(uint256 amount) external view virtual override returns (uint256) { (, int256 usdtEthPrice, , uint256 usdtEthTimeStamp,) = usdtEthPriceFeed.latestRoundData(); require(usdtEthTimeStamp > 0, "USDT Chainlink Oracle data temporarily incomplete"); require(usdtEthPrice > 0, "Invalid Chainlink Oracle USDT price"); (, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData(); require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete"); require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price"); // USDT has 6 decimals return amount.mul(1e12).mul(_USDToCADRate).mul(uint256(usdtEthPrice)).div(uint256(usdcEthPrice)).div(10 ** _granularity); } /** * @notice convert CAD amount to USD amount * @param amount amount of CAD in 18 decimal places * @return amount of USD in 18 decimal places */ function cadToUsd(uint256 amount) public view virtual override returns (uint256) { return amount.mul(10 ** _granularity).div(_USDToCADRate); } /** * @notice convert CAD amount to Dai amount * @param amount amount of CAD in 18 decimal places * @return amount of Dai in 18 decimal places */ function cadToDai(uint256 amount) external view virtual override returns (uint256) { (, int256 daiEthPrice, , uint256 daiEthTimeStamp,) = daiEthPriceFeed.latestRoundData(); require(daiEthTimeStamp > 0, "Dai Chainlink Oracle data temporarily incomplete"); require(daiEthPrice > 0, "Invalid Chainlink Oracle Dai price"); (, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData(); require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete"); require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price"); return amount.mul(10 ** _granularity).mul(uint256(usdcEthPrice)).div(uint256(daiEthPrice)).div(_USDToCADRate); } /** * @notice convert CAD amount to USDC amount * @param amount amount of CAD in 18 decimal places * @return amount of USDC in 6 decimal places */ function cadToUsdc(uint256 amount) external view virtual override returns (uint256) { return cadToUsd(amount).div(1e12); } /** * @notice convert CAD amount to USDT amount * @param amount amount of CAD in 18 decimal places * @return amount of USDT in 6 decimal places */ function cadToUsdt(uint256 amount) external view virtual override returns (uint256) { (, int256 usdtEthPrice, , uint256 usdtEthTimeStamp,) = usdtEthPriceFeed.latestRoundData(); require(usdtEthTimeStamp > 0, "USDT Chainlink Oracle data temporarily incomplete"); require(usdtEthPrice > 0, "Invalid Chainlink Oracle USDT price"); (, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData(); require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete"); require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price"); return amount.mul(10 ** _granularity).mul(uint256(usdcEthPrice)).div(uint256(usdtEthPrice)).div(_USDToCADRate).div(1e12); } }
* @notice convert CAD amount to USDT amount @param amount amount of CAD in 18 decimal places @return amount of USDT in 6 decimal places/
function cadToUsdt(uint256 amount) external view virtual override returns (uint256) { (, int256 usdtEthPrice, , uint256 usdtEthTimeStamp,) = usdtEthPriceFeed.latestRoundData(); require(usdtEthTimeStamp > 0, "USDT Chainlink Oracle data temporarily incomplete"); require(usdtEthPrice > 0, "Invalid Chainlink Oracle USDT price"); (, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData(); require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete"); require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price"); return amount.mul(10 ** _granularity).mul(uint256(usdcEthPrice)).div(uint256(usdtEthPrice)).div(_USDToCADRate).div(1e12); }
295,939
[ 1, 6283, 385, 1880, 3844, 358, 11836, 9081, 3844, 225, 3844, 377, 3844, 434, 385, 1880, 316, 6549, 6970, 12576, 327, 3844, 434, 11836, 9081, 316, 1666, 6970, 12576, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 28451, 774, 3477, 7510, 12, 11890, 5034, 3844, 13, 3903, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 261, 16, 509, 5034, 584, 7510, 41, 451, 5147, 16, 269, 2254, 5034, 584, 7510, 41, 451, 21536, 16, 13, 273, 584, 7510, 41, 451, 5147, 8141, 18, 13550, 11066, 751, 5621, 203, 3639, 2583, 12, 407, 7510, 41, 451, 21536, 405, 374, 16, 315, 3378, 9081, 7824, 1232, 28544, 501, 18917, 14715, 8863, 203, 3639, 2583, 12, 407, 7510, 41, 451, 5147, 405, 374, 16, 315, 1941, 7824, 1232, 28544, 11836, 9081, 6205, 8863, 203, 203, 3639, 261, 16, 509, 5034, 584, 7201, 41, 451, 5147, 16, 269, 2254, 5034, 584, 7201, 41, 451, 21536, 16, 13, 273, 584, 7201, 41, 451, 5147, 8141, 18, 13550, 11066, 751, 5621, 203, 3639, 2583, 12, 407, 7201, 41, 451, 21536, 405, 374, 16, 315, 3378, 5528, 4105, 7824, 1232, 28544, 501, 18917, 14715, 8863, 203, 3639, 2583, 12, 407, 7201, 41, 451, 5147, 405, 374, 16, 315, 1941, 7824, 1232, 28544, 11836, 5528, 4105, 6205, 8863, 203, 203, 3639, 327, 3844, 18, 16411, 12, 2163, 2826, 389, 75, 27234, 2934, 16411, 12, 11890, 5034, 12, 407, 7201, 41, 451, 5147, 13, 2934, 2892, 12, 11890, 5034, 12, 407, 7510, 41, 451, 5147, 13, 2934, 2892, 24899, 3378, 40, 774, 39, 1880, 4727, 2934, 2892, 12, 21, 73, 2138, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; import "./TransferDefinition.sol"; /// @title HashlockTransfer /// @author Connext <[email protected]> /// @notice This contract allows users to claim a payment locked in /// the application if they provide the correct preImage. The payment is /// reverted if not unlocked by the timelock if one is provided. contract HashlockTransfer is TransferDefinition { struct TransferState { bytes32 lockHash; uint256 expiry; // If 0, then no timelock is enforced } struct TransferResolver { bytes32 preImage; } // Provide registry information string public constant override Name = "HashlockTransfer"; string public constant override StateEncoding = "tuple(bytes32 lockHash, uint256 expiry)"; string public constant override ResolverEncoding = "tuple(bytes32 preImage)"; function EncodedCancel() external pure override returns(bytes memory) { TransferResolver memory resolver; resolver.preImage = bytes32(0); return abi.encode(resolver); } function create(bytes calldata encodedBalance, bytes calldata encodedState) external view override returns (bool) { // Decode parameters TransferState memory state = abi.decode(encodedState, (TransferState)); Balance memory balance = abi.decode(encodedBalance, (Balance)); require( balance.amount[0] > 0, "HashlockTransfer: ZER0_SENDER_BALANCE" ); require( balance.amount[1] == 0, "HashlockTransfer: NONZERO_RECIPIENT_BALANCE" ); require( state.lockHash != bytes32(0), "HashlockTransfer: EMPTY_LOCKHASH" ); require( state.expiry == 0 || state.expiry > block.timestamp, "HashlockTransfer: EXPIRED_TIMELOCK" ); // Valid transfer state return true; } function resolve( bytes calldata encodedBalance, bytes calldata encodedState, bytes calldata encodedResolver ) external view override returns (Balance memory) { TransferState memory state = abi.decode(encodedState, (TransferState)); TransferResolver memory resolver = abi.decode(encodedResolver, (TransferResolver)); Balance memory balance = abi.decode(encodedBalance, (Balance)); // If you pass in bytes32(0), payment is canceled // If timelock is nonzero and has expired, payment must be canceled // otherwise resolve will revert if (resolver.preImage != bytes32(0)) { // Payment must not be expired require(state.expiry == 0 || state.expiry > block.timestamp, "HashlockTransfer: PAYMENT_EXPIRED"); // Check hash for normal payment unlock bytes32 generatedHash = sha256(abi.encode(resolver.preImage)); require( state.lockHash == generatedHash, "HashlockTransfer: INVALID_PREIMAGE" ); // Update state balance.amount[1] = balance.amount[0]; balance.amount[0] = 0; } // To cancel, the preImage must be empty (not simply incorrect) // There are no additional state mutations, and the preImage is // asserted by the `if` statement return balance; } }
Decode parameters Valid transfer state
function create(bytes calldata encodedBalance, bytes calldata encodedState) external view override returns (bool) { TransferState memory state = abi.decode(encodedState, (TransferState)); Balance memory balance = abi.decode(encodedBalance, (Balance)); require( balance.amount[0] > 0, "HashlockTransfer: ZER0_SENDER_BALANCE" ); require( balance.amount[1] == 0, "HashlockTransfer: NONZERO_RECIPIENT_BALANCE" ); require( state.lockHash != bytes32(0), "HashlockTransfer: EMPTY_LOCKHASH" ); require( state.expiry == 0 || state.expiry > block.timestamp, "HashlockTransfer: EXPIRED_TIMELOCK" ); return true; }
957,983
[ 1, 6615, 1472, 2364, 7412, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 12, 3890, 745, 892, 3749, 13937, 16, 1731, 745, 892, 3749, 1119, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 12279, 1119, 3778, 919, 273, 24126, 18, 3922, 12, 10787, 1119, 16, 261, 5912, 1119, 10019, 203, 3639, 30918, 3778, 11013, 273, 24126, 18, 3922, 12, 10787, 13937, 16, 261, 13937, 10019, 203, 203, 3639, 2583, 12, 203, 5411, 11013, 18, 8949, 63, 20, 65, 405, 374, 16, 203, 5411, 315, 2310, 739, 5912, 30, 2285, 654, 20, 67, 1090, 18556, 67, 38, 1013, 4722, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 11013, 18, 8949, 63, 21, 65, 422, 374, 16, 203, 5411, 315, 2310, 739, 5912, 30, 18708, 24968, 67, 862, 7266, 1102, 2222, 67, 38, 1013, 4722, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 919, 18, 739, 2310, 480, 1731, 1578, 12, 20, 3631, 203, 5411, 315, 2310, 739, 5912, 30, 8984, 67, 6589, 15920, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 919, 18, 22409, 422, 374, 747, 919, 18, 22409, 405, 1203, 18, 5508, 16, 203, 5411, 315, 2310, 739, 5912, 30, 31076, 5879, 67, 4684, 6589, 6, 203, 3639, 11272, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-21 */ /** *Submitted for verification at Etherscan.io on 2021-10-03 */ // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; // Contract logic @ line 607 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; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } 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; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } 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"); 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); } } } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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 functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } 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 { if (returndata.length > 0) { 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); } } interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } abstract contract ERC20 is IERC20 { using SafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account_, uint256 ammount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address( this ), account_, ammount_); _totalSupply = _totalSupply.add(ammount_); _balances[account_] = _balances[account_].add(ammount_); emit Transfer(address( this ), account_, ammount_); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } interface IERC2612Permit { function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); } library Counters { using SafeMath for uint256; struct Counter { uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } 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 { 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)); } 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"); } } } library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } } interface ITreasury { function deposit( uint _amount, address _token, uint _profit ) external returns ( bool ); function valueOf( address _token, uint _amount ) external view returns ( uint value_ ); function mintRewards( address _to, uint _amount ) external; } interface IBondCalculator { function valuation( address _LP, uint _amount ) external view returns ( uint ); function markdown( address _LP ) external view returns ( uint ); } interface IStaking { function stake( uint _amount, address _recipient ) external returns ( bool ); } interface IStakingHelper { function stake( uint _amount, address _recipient ) external; } interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } contract OlympusBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable OHM; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints OHM when receives principle address public immutable bondCalculator; // calculates value of LP tokens AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout address public stakingHelper; // to stake and claim if no staking warmup bool public useHelper; Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint payout; // OHM remaining to be paid uint vesting; // Blocks left to vest uint lastBlock; // Last interaction uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _OHM, address _principle, address _treasury, address _bondCalculator, address _feed ) { require( _OHM != address(0) ); OHM = _OHM; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt ) external onlyPolicy() { require( terms.controlVariable == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 10000, "Vesting must be longer than 36 hours" ); terms.vestingTerm = _input; } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyPolicy() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice set contract for auto stake * @param _staking address * @param _helper bool */ function setStaking( address _staking, bool _helper ) external onlyPolicy() { require( _staking != address(0) ); if ( _helper ) { useHelper = true; stakingHelper = _staking; } else { useHelper = false; staking = _staking; } } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor ) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOf( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 OHM ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastBlock: block.number, pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( OHM ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake if ( useHelper ) { // use if staking warmup is 0 IERC20( OHM ).approve( stakingHelper, _amount ); IStakingHelper( stakingHelper ).stake( _amount, _recipient ); } else { IERC20( OHM ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient ); } } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer ); if( adjustment.rate != 0 && block.number >= blockCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = block.number; } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( OHM ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice() .mul( IBondCalculator( bondCalculator ).markdown( principle ) ) .mul( uint( assetPrice() ) ) .div( 1e12 ); } /** * @notice calculate current ratio of debt to OHM supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), IERC20( OHM ).totalSupply() ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint blocksSinceLast = block.number.sub( lastDecay ); decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of OHM available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } }
* @notice get asset price from chainlink/
function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; }
515,718
[ 1, 588, 3310, 6205, 628, 2687, 1232, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3310, 5147, 1435, 1071, 1476, 1135, 261, 474, 13, 288, 203, 3639, 261, 269, 509, 6205, 16, 269, 269, 262, 273, 6205, 8141, 18, 13550, 11066, 751, 5621, 203, 3639, 327, 6205, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xEa4a3Dbaa54d98757E68FAC3d5f1b0d0C0DF9B11/sources/project_/contracts/BakaCoin.sol
_mint(AIRDROP_ADDRESS_1, MAX_AIR_DROP_ROUND_1); _mint(AIRDROP_ADDRESS_2, MAX_AIR_DROP_ROUND_2); _mint(AIRDROP_ADDRESS_3, MAX_AIR_DROP_ROUND_3); _mint(AIRDROP_ADDRESS_4, MAX_AIR_DROP_ROUND_4);
constructor() ERC20("BakaCoin", "BAKA") { _mint(AIRDROP_ADDRESS, MAX_TOTAL_AIR_DROP + MAX_TOTAL_LIQUID); _mint(LP_ADDRESS, MAX_TOTAL_SUPPLY - MAX_TOTAL_AIR_DROP - MAX_TOTAL_LIQUID); setAddressForMarketing(0xD270D2Dd7A58bDbb7D5673b3ba29Ba69CE176c69); setSupport(0xD270D2Dd7A58bDbb7D5673b3ba29Ba69CE176c69); }
3,290,532
[ 1, 67, 81, 474, 12, 37, 7937, 18768, 67, 15140, 67, 21, 16, 4552, 67, 37, 7937, 67, 18768, 67, 15092, 67, 21, 1769, 389, 81, 474, 12, 37, 7937, 18768, 67, 15140, 67, 22, 16, 4552, 67, 37, 7937, 67, 18768, 67, 15092, 67, 22, 1769, 389, 81, 474, 12, 37, 7937, 18768, 67, 15140, 67, 23, 16, 4552, 67, 37, 7937, 67, 18768, 67, 15092, 67, 23, 1769, 389, 81, 474, 12, 37, 7937, 18768, 67, 15140, 67, 24, 16, 4552, 67, 37, 7937, 67, 18768, 67, 15092, 67, 24, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 38, 581, 69, 27055, 3113, 315, 12536, 47, 37, 7923, 288, 203, 3639, 389, 81, 474, 12, 37, 7937, 18768, 67, 15140, 16, 4552, 67, 28624, 67, 37, 7937, 67, 18768, 397, 4552, 67, 28624, 67, 2053, 53, 3060, 1769, 203, 3639, 389, 81, 474, 12, 14461, 67, 15140, 16, 4552, 67, 28624, 67, 13272, 23893, 300, 4552, 67, 28624, 67, 37, 7937, 67, 18768, 300, 4552, 67, 28624, 67, 2053, 53, 3060, 1769, 203, 203, 3639, 444, 1887, 1290, 3882, 21747, 12, 20, 17593, 5324, 20, 40, 22, 40, 72, 27, 37, 8204, 70, 4331, 70, 27, 40, 4313, 9036, 70, 23, 12124, 5540, 38, 69, 8148, 1441, 28493, 71, 8148, 1769, 203, 3639, 444, 6289, 12, 20, 17593, 5324, 20, 40, 22, 40, 72, 27, 37, 8204, 70, 4331, 70, 27, 40, 4313, 9036, 70, 23, 12124, 5540, 38, 69, 8148, 1441, 28493, 71, 8148, 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 ]
./partial_match/4/0xC2c08CeE7B15869B4AC336BE0925540b0ae75bc9/sources/MultiCollateralSynth.sol
* @notice _transferToFeeAddress function non-dUSD synths are exchanged into dUSD via synthInitiatedExchange notify feePool to record amount as fee paid to feePool / dUSD can be transferred to FEE_ADDRESS directly else exchange synth into dUSD and send to FEE_ADDRESS
function _transferToFeeAddress(address to, uint256 value) internal returns (bool) { uint256 amountInUSD; if (currencyKey == "dUSD") { amountInUSD = value; super._internalTransfer(messageSender, to, value); amountInUSD = exchanger().exchange( messageSender, currencyKey, value, "dUSD", FEE_ADDRESS ); } return true; }
8,589,759
[ 1, 67, 13866, 774, 14667, 1887, 445, 1661, 17, 72, 3378, 40, 6194, 451, 87, 854, 431, 6703, 1368, 302, 3378, 40, 3970, 6194, 451, 2570, 10206, 11688, 5066, 14036, 2864, 358, 1409, 3844, 487, 14036, 30591, 358, 14036, 2864, 342, 302, 3378, 40, 848, 506, 906, 4193, 358, 478, 9383, 67, 15140, 5122, 469, 7829, 6194, 451, 1368, 302, 3378, 40, 471, 1366, 358, 478, 9383, 67, 15140, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 774, 14667, 1887, 12, 2867, 358, 16, 2254, 5034, 460, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2254, 5034, 3844, 382, 3378, 40, 31, 203, 203, 3639, 309, 261, 7095, 653, 422, 315, 72, 3378, 40, 7923, 288, 203, 5411, 3844, 382, 3378, 40, 273, 460, 31, 203, 5411, 2240, 6315, 7236, 5912, 12, 2150, 12021, 16, 358, 16, 460, 1769, 203, 5411, 3844, 382, 3378, 40, 273, 431, 343, 11455, 7675, 16641, 12, 203, 7734, 883, 12021, 16, 203, 7734, 5462, 653, 16, 203, 7734, 460, 16, 203, 7734, 315, 72, 3378, 40, 3113, 203, 7734, 478, 9383, 67, 15140, 203, 5411, 11272, 203, 3639, 289, 203, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-01-15 */ // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: original_contracts/lib/IExchange.sol pragma solidity 0.6.10; /** * @dev This interface should be implemented by all exchanges which needs to integrate with the paraswap protocol */ interface IExchange { /** * @dev The function which performs the swap on an exchange. * Exchange needs to implement this method in order to support swapping of tokens through it * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Amount of source tokens to be swapped * @param toAmount Minimum destination token amount expected out of this swap * @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap * @param payload Any exchange specific data which is required can be passed in this argument in encoded format which * will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism */ function swap( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, address exchange, bytes calldata payload) external payable returns (uint256); /** * @dev The function which performs the swap on an exchange. * Exchange needs to implement this method in order to support swapping of tokens through it * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Max Amount of source tokens to be swapped * @param toAmount Destination token amount expected out of this swap * @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap * @param payload Any exchange specific data which is required can be passed in this argument in encoded format which * will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism */ function buy( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, address exchange, bytes calldata payload) external payable returns (uint256); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: original_contracts/ITokenTransferProxy.sol pragma solidity 0.6.10; interface ITokenTransferProxy { function transferFrom( address token, address from, address to, uint256 amount ) external; function freeGSTTokens(uint256 tokensToFree) external; } // File: original_contracts/lib/Utils.sol pragma solidity 0.6.10; library Utils { using SafeMath for uint256; using SafeERC20 for IERC20; address constant ETH_ADDRESS = address( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); uint256 constant MAX_UINT = 2 ** 256 - 1; struct Route { address payable exchange; address targetExchange; uint percent; bytes payload; uint256 networkFee;//Network fee is associated with 0xv3 trades } struct Path { address to; uint256 totalNetworkFee;//Network fee is associated with 0xv3 trades Route[] routes; } struct BuyRoute { address payable exchange; address targetExchange; uint256 fromAmount; uint256 toAmount; bytes payload; uint256 networkFee;//Network fee is associated with 0xv3 trades } function ethAddress() internal pure returns (address) {return ETH_ADDRESS;} function maxUint() internal pure returns (uint256) {return MAX_UINT;} function approve( address addressToApprove, address token, uint256 amount ) internal { if (token != ETH_ADDRESS) { IERC20 _token = IERC20(token); uint allowance = _token.allowance(address(this), addressToApprove); if (allowance < amount) { _token.safeApprove(addressToApprove, 0); _token.safeIncreaseAllowance(addressToApprove, MAX_UINT); } } } function transferTokens( address token, address payable destination, uint256 amount ) internal { if (amount > 0) { if (token == ETH_ADDRESS) { destination.transfer(amount); } else { IERC20(token).safeTransfer(destination, amount); } } } function tokenBalance( address token, address account ) internal view returns (uint256) { if (token == ETH_ADDRESS) { return account.balance; } else { return IERC20(token).balanceOf(account); } } /** * @dev Helper method to refund gas using gas tokens */ function refundGas( address tokenProxy, uint256 initialGas, uint256 mintPrice ) internal { uint256 mintBase = 32254; uint256 mintToken = 36543; uint256 freeBase = 14154; uint256 freeToken = 6870; uint256 reimburse = 24000; uint256 tokens = initialGas.sub( gasleft()).add(freeBase).div(reimburse.mul(2).sub(freeToken) ); uint256 mintCost = mintBase.add(tokens.mul(mintToken)); uint256 freeCost = freeBase.add(tokens.mul(freeToken)); uint256 maxreimburse = tokens.mul(reimburse); uint256 efficiency = maxreimburse.mul(tx.gasprice).mul(100).div( mintCost.mul(mintPrice).add(freeCost.mul(tx.gasprice)) ); if (efficiency > 100) { freeGasTokens(tokenProxy, tokens); } } /** * @dev Helper method to free gas tokens */ function freeGasTokens(address tokenProxy, uint256 tokens) internal { uint256 tokensToFree = tokens; uint256 safeNumTokens = 0; uint256 gas = gasleft(); if (gas >= 27710) { safeNumTokens = gas.sub(27710).div(1148 + 5722 + 150); } if (tokensToFree > safeNumTokens) { tokensToFree = safeNumTokens; } ITokenTransferProxy(tokenProxy).freeGSTTokens(tokensToFree); } } // File: original_contracts/lib/cofix/ICoFiXRouter.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.10; interface ICoFiXRouter { function factory() external pure returns (address); function WETH() external pure returns (address); // All pairs: {ETH <-> ERC20 Token} /// @dev Maker add liquidity to pool, get pool token (mint XToken to maker) (notice: msg.value = amountETH + oracle fee) /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The dealine of this request /// @return liquidity The real liquidity or XToken minted from pool function addLiquidity( address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (uint liquidity); /// @dev Maker add liquidity to pool, get pool token (mint XToken) and stake automatically (notice: msg.value = amountETH + oracle fee) /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The dealine of this request /// @return liquidity The real liquidity or XToken minted from pool function addLiquidityAndStake( address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (uint liquidity); /// @dev Maker remove liquidity from pool to get ERC20 Token back (maker burn XToken) (notice: msg.value = oracle fee) /// @param token The address of ERC20 Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountTokenMin The minimum amount of Token wanted to get from pool /// @param to The target address receiving the Token /// @param deadline The dealine of this request /// @return amountToken The real amount of Token transferred from the pool function removeLiquidityGetToken( address token, uint liquidity, uint amountTokenMin, address to, uint deadline ) external payable returns (uint amountToken); /// @dev Maker remove liquidity from pool to get ETH back (maker burn XToken) (notice: msg.value = oracle fee) /// @param token The address of ERC20 Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountETHMin The minimum amount of ETH wanted to get from pool /// @param to The target address receiving the ETH /// @param deadline The dealine of this request /// @return amountETH The real amount of ETH transferred from the pool function removeLiquidityGetETH( address token, uint liquidity, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountETH); /// @dev Trader swap exact amount of ETH for ERC20 Tokens (notice: msg.value = amountIn + oracle fee) /// @param token The address of ERC20 Token /// @param amountIn The exact amount of ETH a trader want to swap into pool /// @param amountOutMin The minimum amount of Token a trader want to swap out of pool /// @param to The target address receiving the Token /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The dealine of this request /// @return _amountIn The real amount of ETH transferred into pool /// @return _amountOut The real amount of Token transferred out of pool function swapExactETHForTokens( address token, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); /// @dev Trader swap exact amount of ERC20 Tokens for ETH (notice: msg.value = oracle fee) /// @param token The address of ERC20 Token /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param amountOutMin The mininum amount of ETH a trader want to swap out of pool /// @param to The target address receiving the ETH /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The dealine of this request /// @return _amountIn The real amount of Token transferred into pool /// @return _amountOut The real amount of ETH transferred out of pool function swapExactTokensForETH( address token, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); /// @dev Trader swap exact amount of ERC20 Tokens for other ERC20 Tokens (notice: msg.value = oracle fee) /// @param tokenIn The address of ERC20 Token a trader want to swap into pool /// @param tokenOut The address of ERC20 Token a trader want to swap out of pool /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param amountOutMin The mininum amount of ETH a trader want to swap out of pool /// @param to The target address receiving the Token /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The dealine of this request /// @return _amountIn The real amount of Token transferred into pool /// @return _amountOut The real amount of Token transferred out of pool function swapExactTokensForTokens( address tokenIn, address tokenOut, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); /// @dev Trader swap ETH for exact amount of ERC20 Tokens (notice: msg.value = amountInMax + oracle fee) /// @param token The address of ERC20 Token /// @param amountInMax The max amount of ETH a trader want to swap into pool /// @param amountOutExact The exact amount of Token a trader want to swap out of pool /// @param to The target address receiving the Token /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The dealine of this request /// @return _amountIn The real amount of ETH transferred into pool /// @return _amountOut The real amount of Token transferred out of pool function swapETHForExactTokens( address token, uint amountInMax, uint amountOutExact, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); /// @dev Trader swap ERC20 Tokens for exact amount of ETH (notice: msg.value = oracle fee) /// @param token The address of ERC20 Token /// @param amountInMax The max amount of Token a trader want to swap into pool /// @param amountOutExact The exact amount of ETH a trader want to swap out of pool /// @param to The target address receiving the ETH /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The dealine of this request /// @return _amountIn The real amount of Token transferred into pool /// @return _amountOut The real amount of ETH transferred out of pool function swapTokensForExactETH( address token, uint amountInMax, uint amountOutExact, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); } // File: openzeppelin-solidity/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: original_contracts/lib/TokenFetcher.sol pragma solidity 0.6.10; contract TokenFetcher is Ownable { /** * @dev Allows owner of the contract to transfer any tokens which are assigned to the contract * This method is for safety if by any chance tokens or ETHs are assigned to the contract by mistake * @dev token Address of the token to be transferred * @dev destination Recepient of the token * @dev amount Amount of tokens to be transferred */ function transferTokens( address token, address payable destination, uint256 amount ) external onlyOwner { Utils.transferTokens(token, destination, amount); } } // File: original_contracts/lib/cofix/CoFiX.sol pragma solidity 0.6.10; pragma experimental ABIEncoderV2; contract CoFiX is IExchange, TokenFetcher { using SafeMath for uint256; using Address for address; address public rewardReceiver; constructor(address _rewardReceiver) public { rewardReceiver = _rewardReceiver; } /** * @dev Fallback method to allow exchanges to transfer back ethers for a particular swap */ receive() external payable { } function setRewardReceiver(address _rewardReceiver) external onlyOwner { rewardReceiver = _rewardReceiver; } function swap( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, address exchange, bytes calldata payload ) external override payable returns (uint256) { Utils.approve(address(exchange), address(fromToken), fromAmount); if (address(fromToken) == Utils.ethAddress()) { ICoFiXRouter(exchange).swapExactETHForTokens{value: msg.value}( address(toToken), fromAmount, toAmount, address(this), rewardReceiver, now ); } else if (address(toToken) == Utils.ethAddress()) { ICoFiXRouter(exchange).swapExactTokensForETH{value: msg.value}( address(fromToken), fromAmount, toAmount, address(this), rewardReceiver, now ); } else { ICoFiXRouter(exchange).swapExactTokensForTokens{value: msg.value}( address(fromToken), address(toToken), fromAmount, toAmount, address(this), rewardReceiver, now ); } uint256 receivedAmount = Utils.tokenBalance( address(toToken), address(this) ); Utils.transferTokens(address(toToken), msg.sender, receivedAmount); return receivedAmount; } function buy( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, address exchange, bytes calldata payload ) external override payable returns (uint256) { revert("METHOD NOT SUPPORTED"); } }
All pairs: {ETH <-> ERC20 Token}
interface ICoFiXRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (uint liquidity); function addLiquidityAndStake( address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (uint liquidity); function removeLiquidityGetToken( address token, uint liquidity, uint amountTokenMin, address to, uint deadline ) external payable returns (uint amountToken); function removeLiquidityGetETH( address token, uint liquidity, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountETH); function swapExactETHForTokens( address token, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); function swapExactTokensForETH( address token, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); function swapExactTokensForTokens( address tokenIn, address tokenOut, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); function swapETHForExactTokens( address token, uint amountInMax, uint amountOutExact, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); function swapTokensForExactETH( address token, uint amountInMax, uint amountOutExact, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); }
15,175,242
[ 1, 1595, 5574, 30, 288, 1584, 44, 411, 2122, 4232, 39, 3462, 3155, 97, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 467, 4249, 42, 77, 60, 8259, 288, 203, 565, 445, 3272, 1435, 3903, 16618, 1135, 261, 2867, 1769, 203, 565, 445, 678, 1584, 44, 1435, 3903, 16618, 1135, 261, 2867, 1769, 203, 203, 203, 565, 445, 527, 48, 18988, 24237, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 3844, 1584, 44, 16, 203, 3639, 2254, 3844, 1345, 16, 203, 3639, 2254, 4501, 372, 24237, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 4501, 372, 24237, 1769, 203, 203, 565, 445, 527, 48, 18988, 24237, 1876, 510, 911, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 3844, 1584, 44, 16, 203, 3639, 2254, 3844, 1345, 16, 203, 3639, 2254, 4501, 372, 24237, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 4501, 372, 24237, 1769, 203, 203, 565, 445, 1206, 48, 18988, 24237, 967, 1345, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 4501, 372, 24237, 16, 203, 3639, 2254, 3844, 1345, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 3844, 1345, 1769, 203, 203, 565, 445, 1206, 48, 18988, 24237, 967, 1584, 44, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 4501, 372, 24237, 16, 203, 3639, 2254, 3844, 1584, 44, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 3844, 1584, 44, 2 ]
pragma solidity ^0.4.19; /** * @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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title EjectableOwnable * @dev The EjectableOwnable contract provides the function to remove the ownership of the contract. */ contract EjectableOwnable is Ownable { /** * @dev Remove the ownership by setting the owner address to null, * after calling this function, all onlyOwner function will be be able to be called by anyone anymore, * the contract will achieve truly decentralisation. */ function removeOwnership() onlyOwner public { owner = 0x0; } } /** * @title JointOwnable * @dev Extension for the Ownable contract, where the owner can assign at most 2 other addresses * to manage some functions of the contract, using the eitherOwner modifier. * Note that onlyOwner modifier would still be accessible only for the original owner. */ contract JointOwnable is Ownable { event AnotherOwnerAssigned(address indexed anotherOwner); address public anotherOwner1; address public anotherOwner2; /** * @dev Throws if called by any account other than the owner or anotherOwner. */ modifier eitherOwner() { require(msg.sender == owner || msg.sender == anotherOwner1 || msg.sender == anotherOwner2); _; } /** * @dev Allows the current owner to assign another owner. * @param _anotherOwner The address to another owner. */ function assignAnotherOwner1(address _anotherOwner) onlyOwner public { require(_anotherOwner != 0); AnotherOwnerAssigned(_anotherOwner); anotherOwner1 = _anotherOwner; } /** * @dev Allows the current owner to assign another owner. * @param _anotherOwner The address to another owner. */ function assignAnotherOwner2(address _anotherOwner) onlyOwner public { require(_anotherOwner != 0); AnotherOwnerAssigned(_anotherOwner); anotherOwner2 = _anotherOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @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; } } /** * @title PullPayment * @dev Base contract supporting async send for pull payments. Inherit from this * contract and use asyncSend instead of send. */ contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; /** * @dev withdraw accumulated balance, called by payee. */ function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } } /** * @title A simplified interface of ERC-721, but without approval functions */ contract ERC721 { // Events event Transfer(address indexed from, address indexed to, uint tokenId); // ERC20 compatible functions // function name() public view returns (string); // function symbol() public view returns (string); function totalSupply() public view returns (uint); function balanceOf(address _owner) public view returns (uint); // Functions that define ownership function ownerOf(uint _tokenId) external view returns (address); function transfer(address _to, uint _tokenId) external; } contract DungeonStructs { /** * @dev The main Dungeon struct. Every dungeon in the game is represented by this structure. * A dungeon is consists of an unlimited number of floors for your heroes to challenge, * the power level of a dungeon is encoded in the floorGenes. Some dungeons are in fact more "challenging" than others, * the secret formula for that is left for user to find out. * * Each dungeon also has a "training area", heroes can perform trainings and upgrade their stat, * and some dungeons are more effective in the training, which is also a secret formula! * * When player challenge or do training in a dungeon, the fee will be collected as the dungeon rewards, * which will be rewarded to the player who successfully challenged the current floor. * * Each dungeon fits in fits into three 256-bit words. */ struct Dungeon { // Each dungeon has an ID which is the index in the storage array. // The timestamp of the block when this dungeon is created. uint32 creationTime; // The status of the dungeon, each dungeon can have 5 status, namely: // 0: Active | 1: Transport Only | 2: Challenge Only | 3: Train Only | 4: InActive uint8 status; // The dungeon's difficulty, the higher the difficulty, // normally, the "rarer" the seedGenes, the higher the diffculty, // and the higher the contribution fee it is to challenge, train, and transport to the dungeon, // the formula for the contribution fee is in DungeonChallenge and DungeonTraining contracts. // A dungeon's difficulty never change. uint8 difficulty; // The dungeon's capacity, maximum number of players allowed to stay on this dungeon. // The capacity of the newbie dungeon (Holyland) is set at 0 (which is infinity). // Using 16-bit unsigned integers can have a maximum of 65535 in capacity. // A dungeon's capacity never change. uint16 capacity; // The current floor number, a dungeon is consists of an umlimited number of floors, // when there is heroes successfully challenged a floor, the next floor will be // automatically generated. Using 32-bit unsigned integer can have a maximum of 4 billion floors. uint32 floorNumber; // The timestamp of the block when the current floor is generated. uint32 floorCreationTime; // Current accumulated rewards, successful challenger will get a large proportion of it. uint128 rewards; // The seed genes of the dungeon, it is used as the base gene for first floor, // some dungeons are rarer and some are more common, the exact details are, // of course, top secret of the game! // A dungeon's seedGenes never change. uint seedGenes; // The genes for current floor, it encodes the difficulty level of the current floor. // We considered whether to store the entire array of genes for all floors, but // in order to save some precious gas we're willing to sacrifice some functionalities with that. uint floorGenes; } /** * @dev The main Hero struct. Every hero in the game is represented by this structure. */ struct Hero { // Each hero has an ID which is the index in the storage array. // The timestamp of the block when this dungeon is created. uint64 creationTime; // The timestamp of the block where a challenge is performed, used to calculate when a hero is allowed to engage in another challenge. uint64 cooldownStartTime; // Every time a hero challenge a dungeon, its cooldown index will be incremented by one. uint32 cooldownIndex; // The seed of the hero, the gene encodes the power level of the hero. // This is another top secret of the game! Hero's gene can be upgraded via // training in a dungeon. uint genes; } } /** * @title The ERC-721 compliance token contract for the Dungeon tokens. * @dev See the DungeonStructs contract to see the details of the Dungeon token data structure. */ contract DungeonToken is ERC721, DungeonStructs, Pausable, JointOwnable { /** * @notice Limits the number of dungeons the contract owner can ever create. */ uint public constant DUNGEON_CREATION_LIMIT = 1024; /** * @dev The Mint event is fired whenever a new dungeon is created. */ event Mint(address indexed owner, uint newTokenId, uint difficulty, uint capacity, uint seedGenes); /** * @dev The NewDungeonFloor event is fired whenever a new dungeon floor is added. */ event NewDungeonFloor(uint timestamp, uint indexed dungeonId, uint32 newFloorNumber, uint128 newRewards , uint newFloorGenes); /** * @dev Transfer event as defined in current draft of ERC721. Emitted every time a token * ownership (Dungeon Master) is assigned, including token creation. */ event Transfer(address indexed from, address indexed to, uint tokenId); /** * @dev Name of token. */ string public constant name = "Dungeon"; /** * @dev Symbol of token. */ string public constant symbol = "DUNG"; /** * @dev An array containing the Dungeon struct, which contains all the dungeons in existance. * The ID for each dungeon is the index of this array. */ Dungeon[] public dungeons; /** * @dev A mapping from token IDs to the address that owns them. */ mapping(uint => address) tokenIndexToOwner; /** * @dev A mapping from owner address to count of tokens that address owns. */ mapping(address => uint) ownershipTokenCount; /** * Each non-fungible token owner can own more than one token at one time. * Because each token is referenced by its unique ID, however, * it can get difficult to keep track of the individual tokens that a user may own. * To do this, the contract keeps a record of the IDs of each token that each user owns. */ mapping(address => uint[]) public ownerTokens; /** * @dev Returns the total number of tokens currently in existence. */ function totalSupply() public view returns (uint) { return dungeons.length; } /** * @dev Returns the number of tokens owned by a specific address. * @param _owner The owner address to check. */ function balanceOf(address _owner) public view returns (uint) { return ownershipTokenCount[_owner]; } /** * @dev Checks if a given address is the current owner of a particular token. * @param _claimant The address we are validating against. * @param _tokenId Token ID */ function _owns(address _claimant, uint _tokenId) internal view returns (bool) { return tokenIndexToOwner[_tokenId] == _claimant; } /** * @dev Returns the address currently assigned ownership of a given token. */ function ownerOf(uint _tokenId) external view returns (address) { require(tokenIndexToOwner[_tokenId] != address(0)); return tokenIndexToOwner[_tokenId]; } /** * @dev Assigns ownership of a specific token to an address. */ function _transfer(address _from, address _to, uint _tokenId) internal { // Increment the ownershipTokenCount. ownershipTokenCount[_to]++; // Transfer ownership. tokenIndexToOwner[_tokenId] = _to; // Add the _tokenId to ownerTokens[_to] ownerTokens[_to].push(_tokenId); // When creating new token, _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // Remove the _tokenId from ownerTokens[_from] uint[] storage fromTokens = ownerTokens[_from]; bool iFound = false; for (uint i = 0; i < fromTokens.length - 1; i++) { if (iFound) { fromTokens[i] = fromTokens[i + 1]; } else if (fromTokens[i] == _tokenId) { iFound = true; fromTokens[i] = fromTokens[i + 1]; } } fromTokens.length--; } // Emit the Transfer event. Transfer(_from, _to, _tokenId); } /** * @dev External function to transfers a token to another address. * @param _to The address of the recipient, can be a user or contract. * @param _tokenId The ID of the token to transfer. */ function transfer(address _to, uint _tokenId) whenNotPaused 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 token. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /** * @dev Get an array of IDs of each token that an user owns. */ function getOwnerTokens(address _owner) external view returns(uint[]) { return ownerTokens[_owner]; } /** * @dev The external function that creates a new dungeon and stores it, only contract owners * can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT. * Will generate a Mint event, a NewDungeonFloor event, and a Transfer event. * @param _difficulty The difficulty of the new dungeon. * @param _capacity The capacity of the new dungeon. * @param _seedGenes The seed genes of the new dungeon. * @param _firstFloorGenes The genes of the first dungeon floor. * @return The dungeon ID of the new dungeon. */ function createDungeon(uint _difficulty, uint _capacity, uint _seedGenes, uint _firstFloorGenes, address _owner) eitherOwner external returns (uint) { // Ensure the total supply is within the fixed limit. require(totalSupply() < DUNGEON_CREATION_LIMIT); // UPDATE STORAGE // Create a new dungeon. dungeons.push(Dungeon(uint32(now), 0, uint8(_difficulty), uint16(_capacity), 0, 0, 0, _seedGenes, 0)); // Token id is the index in the storage array. uint newTokenId = dungeons.length - 1; // Emit the token mint event. Mint(_owner, newTokenId, _difficulty, _capacity, _seedGenes); // Initialize the fist floor, this will emit the NewDungeonFloor event. addDungeonNewFloor(newTokenId, 0, _firstFloorGenes); // This will assign ownership, and also emit the Transfer event. _transfer(0, _owner, newTokenId); return newTokenId; } /** * @dev The external function to set dungeon status by its ID, * refer to DungeonStructs for more information about dungeon status. * Only contract owners can alter dungeon state. */ function setDungeonStatus(uint _id, uint _newStatus) eitherOwner tokenExists(_id) external { dungeons[_id].status = uint8(_newStatus); } /** * @dev The external function to add additional dungeon rewards by its ID, * only contract owners can alter dungeon state. */ function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner tokenExists(_id) external { dungeons[_id].rewards += uint128(_additinalRewards); } /** * @dev The external function to add another dungeon floor by its ID, * only contract owners can alter dungeon state. * Will generate both a NewDungeonFloor event. */ function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner tokenExists(_id) public { Dungeon storage dungeon = dungeons[_id]; dungeon.floorNumber++; dungeon.floorCreationTime = uint32(now); dungeon.rewards = uint128(_newRewards); dungeon.floorGenes = _newFloorGenes; // Emit the NewDungeonFloor event. NewDungeonFloor(now, _id, dungeon.floorNumber, dungeon.rewards, dungeon.floorGenes); } /* ======== MODIFIERS ======== */ /** * @dev Throws if _dungeonId is not created yet. */ modifier tokenExists(uint _tokenId) { require(_tokenId < totalSupply()); _; } } /** * @title The ERC-721 compliance token contract for the Hero tokens. * @dev See the DungeonStructs contract to see the details of the Hero token data structure. */ contract HeroToken is ERC721, DungeonStructs, Pausable, JointOwnable { /** * @dev The Mint event is fired whenever a new hero is created. */ event Mint(address indexed owner, uint newTokenId, uint _genes); /** * @dev Transfer event as defined in current draft of ERC721. Emitted every time a token * ownership is assigned, including token creation. */ event Transfer(address indexed from, address indexed to, uint tokenId); /** * @dev Name of token. */ string public constant name = "Hero"; /** * @dev Symbol of token. */ string public constant symbol = "HERO"; /** * @dev An array containing the Hero struct, which contains all the heroes in existance. * The ID for each hero is the index of this array. */ Hero[] public heroes; /** * @dev A mapping from token IDs to the address that owns them. */ mapping(uint => address) tokenIndexToOwner; /** * @dev A mapping from owner address to count of tokens that address owns. */ mapping(address => uint) ownershipTokenCount; /** * Each non-fungible token owner can own more than one token at one time. * Because each token is referenced by its unique ID, however, * it can get difficult to keep track of the individual tokens that a user may own. * To do this, the contract keeps a record of the IDs of each token that each user owns. */ mapping(address => uint[]) public ownerTokens; /** * @dev Returns the total number of tokens currently in existence. */ function totalSupply() public view returns (uint) { return heroes.length; } /** * @dev Returns the number of tokens owned by a specific address. * @param _owner The owner address to check. */ function balanceOf(address _owner) public view returns (uint) { return ownershipTokenCount[_owner]; } /** * @dev Checks if a given address is the current owner of a particular token. * @param _claimant The address we are validating against. * @param _tokenId Token ID */ function _owns(address _claimant, uint _tokenId) internal view returns (bool) { return tokenIndexToOwner[_tokenId] == _claimant; } /** * @dev Returns the address currently assigned ownership of a given token. */ function ownerOf(uint _tokenId) external view returns (address) { require(tokenIndexToOwner[_tokenId] != address(0)); return tokenIndexToOwner[_tokenId]; } /** * @dev Assigns ownership of a specific token to an address. */ function _transfer(address _from, address _to, uint _tokenId) internal { // Increment the ownershipTokenCount. ownershipTokenCount[_to]++; // Transfer ownership. tokenIndexToOwner[_tokenId] = _to; // Add the _tokenId to ownerTokens[_to] ownerTokens[_to].push(_tokenId); // When creating new token, _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // Remove the _tokenId from ownerTokens[_from] uint[] storage fromTokens = ownerTokens[_from]; bool iFound = false; for (uint i = 0; i < fromTokens.length - 1; i++) { if (iFound) { fromTokens[i] = fromTokens[i + 1]; } else if (fromTokens[i] == _tokenId) { iFound = true; fromTokens[i] = fromTokens[i + 1]; } } fromTokens.length--; } // Emit the Transfer event. Transfer(_from, _to, _tokenId); } /** * @dev External function to transfers a token to another address. * @param _to The address of the recipient, can be a user or contract. * @param _tokenId The ID of the token to transfer. */ function transfer(address _to, uint _tokenId) whenNotPaused 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 token. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /** * @dev Get an array of IDs of each token that an user owns. */ function getOwnerTokens(address _owner) external view returns(uint[]) { return ownerTokens[_owner]; } /** * @dev An external function that creates a new hero and stores it, * only contract owners can create new token. * method doesn't do any checking and should only be called when the * input data is known to be valid. * @param _genes The gene of the new hero. * @param _owner The inital owner of this hero. * @return The hero ID of the new hero. */ function createHero(uint _genes, address _owner) eitherOwner external returns (uint) { // UPDATE STORAGE // Create a new hero. heroes.push(Hero(uint64(now), 0, 0, _genes)); // Token id is the index in the storage array. uint newTokenId = heroes.length - 1; // Emit the token mint event. Mint(_owner, newTokenId, _genes); // This will assign ownership, and also emit the Transfer event. _transfer(0, _owner, newTokenId); return newTokenId; } /** * @dev The external function to set the hero genes by its ID, * only contract owners can alter hero state. */ function setHeroGenes(uint _id, uint _newGenes) eitherOwner tokenExists(_id) external { heroes[_id].genes = _newGenes; } /** * @dev Set the cooldownStartTime for the given hero. Also increments the cooldownIndex. */ function triggerCooldown(uint _id) eitherOwner tokenExists(_id) external { Hero storage hero = heroes[_id]; hero.cooldownStartTime = uint64(now); hero.cooldownIndex++; } /* ======== MODIFIERS ======== */ /** * @dev Throws if _dungeonId is not created yet. */ modifier tokenExists(uint _tokenId) { require(_tokenId < totalSupply()); _; } } /** * SECRET */ contract ChallengeScienceInterface { /** * @dev given genes of current floor and dungeon seed, return a genetic combination - may have a random factor. * @param _floorGenes Genes of floor. * @param _seedGenes Seed genes of dungeon. * @return The resulting genes. */ function mixGenes(uint _floorGenes, uint _seedGenes) external returns (uint); } /** * SECRET */ contract TrainingScienceInterface { /** * @dev given genes of hero and current floor, return a genetic combination - may have a random factor. * @param _heroGenes Genes of hero. * @param _floorGenes Genes of current floor. * @param _equipmentId Equipment index to train for, 0 is train all attributes. * @return The resulting genes. */ function mixGenes(uint _heroGenes, uint _floorGenes, uint _equipmentId) external returns (uint); } /** * @title DungeonBase * @dev Base contract for Ether Dungeon. It implements all necessary sub-classes, * holds all the base storage variables, and some commonly used functions. */ contract DungeonBase is EjectableOwnable, Pausable, PullPayment, DungeonStructs { /* ======== TOKEN CONTRACTS ======== */ /** * @dev The address of the ERC721 token contract managing all Dungeon tokens. */ DungeonToken public dungeonTokenContract; /** * @dev The address of the ERC721 token contract managing all Hero tokens. */ HeroToken public heroTokenContract; /* ======== CLOSED SOURCE CONTRACTS ======== */ /** * @dev The address of the ChallengeScience contract that handles the floor generation mechanics after challenge success. */ ChallengeScienceInterface challengeScienceContract; /** * @dev The address of the TrainingScience contract that handles the hero training mechanics. */ TrainingScienceInterface trainingScienceContract; /* ======== CONSTANTS ======== */ uint16[32] EQUIPMENT_POWERS = [ 1, 2, 4, 5, 16, 17, 18, 19, 0, 0, 0, 0, 0, 0, 0, 0, 4, 16, 32, 33, 0, 0, 0, 0, 32, 64, 0, 0, 128, 0, 0, 0 ]; uint SUPER_HERO_MULTIPLIER = 32; /* ======== SETTER FUNCTIONS ======== */ /** * @dev Set the address of the dungeon token contract. * @param _newDungeonTokenContract An address of a DungeonToken contract. */ function setDungeonTokenContract(address _newDungeonTokenContract) onlyOwner external { dungeonTokenContract = DungeonToken(_newDungeonTokenContract); } /** * @dev Set the address of the hero token contract. * @param _newHeroTokenContract An address of a HeroToken contract. */ function setHeroTokenContract(address _newHeroTokenContract) onlyOwner external { heroTokenContract = HeroToken(_newHeroTokenContract); } /** * @dev Set the address of the secret dungeon challenge formula contract. * @param _newChallengeScienceAddress An address of a ChallengeScience contract. */ function setChallengeScienceContract(address _newChallengeScienceAddress) onlyOwner external { challengeScienceContract = ChallengeScienceInterface(_newChallengeScienceAddress); } /** * @dev Set the address of the secret hero training formula contract. * @param _newTrainingScienceAddress An address of a TrainingScience contract. */ function setTrainingScienceContract(address _newTrainingScienceAddress) onlyOwner external { trainingScienceContract = TrainingScienceInterface(_newTrainingScienceAddress); } /* ======== MODIFIERS ======== */ /** * @dev Throws if _dungeonId is not created yet. */ modifier dungeonExists(uint _dungeonId) { require(_dungeonId < dungeonTokenContract.totalSupply()); _; } /* ======== HELPER FUNCTIONS ======== */ /** * @dev An internal function to calculate the top 5 heroes power of a player. */ function _getTop5HeroesPower(address _address, uint _dungeonId) internal view returns (uint) { uint heroCount = heroTokenContract.balanceOf(_address); if (heroCount == 0) { return 0; } // Compute all hero powers for further calculation. uint[] memory heroPowers = new uint[](heroCount); for (uint i = 0; i < heroCount; i++) { uint heroId = heroTokenContract.ownerTokens(_address, i); uint genes; (,,, genes) = heroTokenContract.heroes(heroId); // Power of dungeonId = 0 (no super hero boost). heroPowers[i] = _getHeroPower(genes, _dungeonId); } // Calculate the top 5 heroes power. uint result; uint curMax; uint curMaxIndex; for (uint j; j < 5; j++){ for (uint k = 0; k < heroPowers.length; k++) { if (heroPowers[k] > curMax) { curMax = heroPowers[k]; curMaxIndex = k; } } result += curMax; heroPowers[curMaxIndex] = 0; curMax = 0; curMaxIndex = 0; } return result; } /** * @dev An internal function to calculate the power of a hero, * it calculates the base equipment power, stats power, and "Super" multiplier. */ function _getHeroPower(uint _genes, uint _dungeonId) internal view returns (uint) { uint difficulty; (,, difficulty,,,,,,) = dungeonTokenContract.dungeons(_dungeonId); // Calculate total stats power. uint statsPower; for (uint i = 0; i < 4; i++) { statsPower += _genes % 32 + 1; _genes /= 32 ** 4; } // Calculate total equipment power. uint equipmentPower; uint superRank = _genes % 32; for (uint j = 4; j < 12; j++) { uint curGene = _genes % 32; equipmentPower += EQUIPMENT_POWERS[curGene]; _genes /= 32 ** 4; if (superRank != curGene) { superRank = 0; } } // Calculate super power boost. bool isSuper = superRank >= 16; uint superBoost; if (isSuper) { superBoost = (difficulty - 1) * SUPER_HERO_MULTIPLIER; } return statsPower + equipmentPower + superBoost; } /** * @dev An internal function to calculate the difficulty of a dungeon floor. */ function _getDungeonPower(uint _genes) internal view returns (uint) { // Calculate total dungeon power. uint dungeonPower; for (uint j = 0; j < 12; j++) { dungeonPower += EQUIPMENT_POWERS[_genes % 32]; _genes /= 32 ** 4; } return dungeonPower; } } contract DungeonTransportation is DungeonBase { /** * @dev The PlayerTransported event is fired when user transported to another dungeon. */ event PlayerTransported(uint timestamp, address indexed playerAddress, uint indexed originDungeonId, uint indexed destinationDungeonId); /* ======== GAME SETTINGS ======== */ /** * @notice The actual fee contribution required to call transport() is calculated by this feeMultiplier, * times the dungeon difficulty of destination dungeon. The payment is accumulated to the rewards of the origin dungeon, * and a large proportion will be claimed by whoever successfully challenged the floor. * 1000 szabo = 0.001 ether */ uint public transportationFeeMultiplier = 500 szabo; /* ======== STORAGE ======== */ /** * @dev A mapping from token IDs to the address that owns them. */ mapping(address => uint) public playerToDungeonID; /** * @dev A mapping from owner address to count of tokens that address owns. */ mapping(uint => uint) public dungeonPlayerCount; /** * @dev The main external function to call when a player transport to another dungeon. * Will generate a PlayerTransported event. */ function transport(uint _destinationDungeonId) whenNotPaused dungeonCanTransport(_destinationDungeonId) external payable { uint originDungeonId = playerToDungeonID[msg.sender]; // Disallow transport to the same dungeon. require(_destinationDungeonId != originDungeonId); // Get the dungeon details from the token contract. uint difficulty; uint capacity; (,, difficulty, capacity,,,,,) = dungeonTokenContract.dungeons(_destinationDungeonId); // Disallow weaker user to transport to "difficult" dungeon. uint top5HeroesPower = _getTop5HeroesPower(msg.sender, _destinationDungeonId); require(top5HeroesPower >= difficulty * 12); // Checks for payment, any exceeding funds will be transferred back to the player. uint baseFee = difficulty * transportationFeeMultiplier; uint additionalFee = top5HeroesPower / 48 * transportationFeeMultiplier; uint requiredFee = baseFee + additionalFee; require(msg.value >= requiredFee); // ** STORAGE UPDATE ** // Increment the accumulated rewards for the dungeon. dungeonTokenContract.addDungeonRewards(originDungeonId, requiredFee); // Calculate any excess funds and make it available to be withdrawed by the player. asyncSend(msg.sender, msg.value - requiredFee); _transport(originDungeonId, _destinationDungeonId); } /** * Private function to assigns location of a player */ function _transport(uint _originDungeonId, uint _destinationDungeonId) private { // If a player do not have any hero, claim first hero. if (heroTokenContract.balanceOf(msg.sender) == 0) { claimHero(); } // ** STORAGE UPDATE ** // Update the ownershipTokenCount. dungeonPlayerCount[_originDungeonId]--; dungeonPlayerCount[_destinationDungeonId]++; // ** STORAGE UPDATE ** // Update player location. playerToDungeonID[msg.sender] = _destinationDungeonId; // Emit the DungeonChallenged event. PlayerTransported(now, msg.sender, _originDungeonId, _destinationDungeonId); } /* ======== OWNERSHIP FUNCTIONS ======== */ /** * @notice Used in transport, challenge and train, to get the genes of a specific hero, * a claim a hero if didn't have any. */ function _getHeroGenesOrClaimFirstHero(uint _heroId) internal returns (uint heroId, uint heroGenes) { heroId = _heroId; // If a player do not have any hero, claim first hero first. if (heroTokenContract.balanceOf(msg.sender) == 0) { heroId = claimHero(); } (,,,heroGenes) = heroTokenContract.heroes(heroId); } /** * @dev Claim a new hero with empty genes. */ function claimHero() public returns (uint) { // If a player do not tranport to any dungeon yet, and it is the first time claiming the hero, // set the dungeon location, increment the #0 Holyland player count by 1. if (playerToDungeonID[msg.sender] == 0 && heroTokenContract.balanceOf(msg.sender) == 0) { dungeonPlayerCount[0]++; } return heroTokenContract.createHero(0, msg.sender); } /* ======== SETTER FUNCTIONS ======== */ /** * @dev Updates the fee contribution multiplier required for calling transport(). */ function setTransportationFeeMultiplier(uint _newTransportationFeeMultiplier) onlyOwner external { transportationFeeMultiplier = _newTransportationFeeMultiplier; } /* ======== MODIFIERS ======== */ /** * @dev Throws if dungeon status do not allow transportation, also check for dungeon existence. * Also check if the capacity of the destination dungeon is reached. */ modifier dungeonCanTransport(uint _destinationDungeonId) { require(_destinationDungeonId < dungeonTokenContract.totalSupply()); uint status; uint capacity; (,status,,capacity,,,,,) = dungeonTokenContract.dungeons(_destinationDungeonId); require(status == 0 || status == 1); // Check if the capacity of the destination dungeon is reached. // Capacity 0 = Infinity require(capacity == 0 || dungeonPlayerCount[_destinationDungeonId] < capacity); _; } } contract DungeonChallenge is DungeonTransportation { /** * @dev The DungeonChallenged event is fired when user finished a dungeon challenge. */ event DungeonChallenged(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint indexed heroId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newFloorGenes, uint successRewards, uint masterRewards); /* ======== GAME SETTINGS ======== */ /** * @notice The actual fee contribution required to call challenge() is calculated by this feeMultiplier, * times the dungeon difficulty. The payment is accumulated to the dungeon rewards, * and a large proportion will be claimed by whoever successfully challenged the floor. * 1 finney = 0.001 ether */ uint public challengeFeeMultiplier = 1 finney; /** * @dev The percentage for which successful challenger be rewarded of the dungeons' accumulated rewards. * The remaining rewards subtract dungeon master rewards will be used as the base rewards for new floor. */ uint public challengeRewardsPercent = 64; /** * @dev The developer fee for owner * Note that when Ether Dungeon becomes truly decentralised, contract ownership will be ejected, * and the master rewards will be rewarded to the dungeon owner (Dungeon Masters). */ uint public masterRewardsPercent = 8; /** * @dev The cooldown time period where a hero can engage in challenge again. * This settings will likely be changed to 20 minutes when multiple heroes system is launched in Version 1. */ uint public challengeCooldownTime = 3 minutes; /** * @dev The preparation time period where a new dungeon is created, before it can be challenged. * This settings will likely be changed to a smaller period (e.g. 20-30 minutes) . */ uint public dungeonPreparationTime = 60 minutes; /** * @dev The challenge rewards percentage used right after the preparation period. */ uint public rushTimeChallengeRewardsPercent = 30; /** * @dev The number of floor in which the rushTimeChallengeRewardsPercent be applied. */ uint public rushTimeFloorCount = 30; /** * @dev The main external function to call when a player challenge a dungeon, * it determines whether if the player successfully challenged the current floor. * Will generate a DungeonChallenged event. */ function challenge(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanChallenge(_dungeonId) heroAllowedToChallenge(_heroId) external payable { // Get the dungeon details from the token contract. uint difficulty; uint seedGenes; (,, difficulty,,,,, seedGenes,) = dungeonTokenContract.dungeons(_dungeonId); // Checks for payment, any exceeding funds will be transferred back to the player. uint requiredFee = difficulty * challengeFeeMultiplier; require(msg.value >= requiredFee); // ** STORAGE UPDATE ** // Increment the accumulated rewards for the dungeon. dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee); // Calculate any excess funds and make it available to be withdrawed by the player. asyncSend(msg.sender, msg.value - requiredFee); // Split the challenge function into multiple parts because of stack too deep error. _challengePart2(_dungeonId, _heroId); } /** * Split the challenge function into multiple parts because of stack too deep error. */ function _challengePart2(uint _dungeonId, uint _heroId) private { uint floorNumber; uint rewards; uint floorGenes; (,,,, floorNumber,, rewards,, floorGenes) = dungeonTokenContract.dungeons(_dungeonId); // Get the hero gene, or claim first hero. uint heroGenes; (_heroId, heroGenes) = _getHeroGenesOrClaimFirstHero(_heroId); bool success = _getChallengeSuccess(heroGenes, _dungeonId, floorGenes); uint newFloorGenes; uint masterRewards; uint successRewards; uint newRewards; // Whether a challenge is success or not is determined by a simple comparison between hero power and floor power. if (success) { newFloorGenes = _getNewFloorGene(_dungeonId); masterRewards = rewards * masterRewardsPercent / 100; if (floorNumber < rushTimeFloorCount) { // rush time right after prepration period successRewards = rewards * rushTimeChallengeRewardsPercent / 100; // The dungeon rewards for new floor as total rewards - challenge rewards - devleoper fee. newRewards = rewards * (100 - rushTimeChallengeRewardsPercent - masterRewardsPercent) / 100; } else { successRewards = rewards * challengeRewardsPercent / 100; newRewards = rewards * (100 - challengeRewardsPercent - masterRewardsPercent) / 100; } // TRIPLE CONFIRM sanity check. require(successRewards + masterRewards + newRewards <= rewards); // ** STORAGE UPDATE ** // Add new floor with the new floor genes and new rewards. dungeonTokenContract.addDungeonNewFloor(_dungeonId, newRewards, newFloorGenes); // Mark the challenge rewards available to be withdrawed by the player. asyncSend(msg.sender, successRewards); // Mark the master rewards available to be withdrawed by the dungeon master. asyncSend(dungeonTokenContract.ownerOf(_dungeonId), masterRewards); } // ** STORAGE UPDATE ** // Trigger the cooldown for the hero. heroTokenContract.triggerCooldown(_heroId); // Emit the DungeonChallenged event. DungeonChallenged(now, msg.sender, _dungeonId, _heroId, heroGenes, floorNumber, floorGenes, success, newFloorGenes, successRewards, masterRewards); } /** * Split the challenge function into multiple parts because of stack too deep error. */ function _getChallengeSuccess(uint _heroGenes, uint _dungeonId, uint _floorGenes) private view returns (bool) { // Determine if the player challenge successfuly the dungeon or not. uint heroPower = _getHeroPower(_heroGenes, _dungeonId); uint floorPower = _getDungeonPower(_floorGenes); return heroPower > floorPower; } /** * Split the challenge function into multiple parts because of stack too deep error. */ function _getNewFloorGene(uint _dungeonId) private returns (uint) { uint seedGenes; uint floorGenes; (,,,,,, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_dungeonId); // Calculate the new floor gene. uint floorPower = _getDungeonPower(floorGenes); // Call the external closed source secret function that determines the resulting floor "genes". uint newFloorGenes = challengeScienceContract.mixGenes(floorGenes, seedGenes); uint newFloorPower = _getDungeonPower(newFloorGenes); // If the power decreased, rollback to the current floor genes. if (newFloorPower < floorPower) { newFloorGenes = floorGenes; } return newFloorGenes; } /* ======== SETTER FUNCTIONS ======== */ /** * @dev Updates the fee contribution multiplier required for calling challenge(). */ function setChallengeFeeMultiplier(uint _newChallengeFeeMultiplier) onlyOwner external { challengeFeeMultiplier = _newChallengeFeeMultiplier; } /** * @dev Updates the challenge rewards pecentage. */ function setChallengeRewardsPercent(uint _newChallengeRewardsPercent) onlyOwner external { challengeRewardsPercent = _newChallengeRewardsPercent; } /** * @dev Updates the master rewards percentage. */ function setMasterRewardsPercent(uint _newMasterRewardsPercent) onlyOwner external { masterRewardsPercent = _newMasterRewardsPercent; } /** * @dev Updates the challenge cooldown time. */ function setChallengeCooldownTime(uint _newChallengeCooldownTime) onlyOwner external { challengeCooldownTime = _newChallengeCooldownTime; } /** * @dev Updates the challenge cooldown time. */ function setDungeonPreparationTime(uint _newDungeonPreparationTime) onlyOwner external { dungeonPreparationTime = _newDungeonPreparationTime; } /** * @dev Updates the rush time challenge rewards percentage. */ function setRushTimeChallengeRewardsPercent(uint _newRushTimeChallengeRewardsPercent) onlyOwner external { rushTimeChallengeRewardsPercent = _newRushTimeChallengeRewardsPercent; } /** * @dev Updates the rush time floor count. */ function setRushTimeFloorCount(uint _newRushTimeFloorCount) onlyOwner external { rushTimeFloorCount = _newRushTimeFloorCount; } /* ======== MODIFIERS ======== */ /** * @dev Throws if dungeon status do not allow challenge, also check for dungeon existence. * Also check if the user is in the dungeon. * Also check if the dungeon is not in preparation period. */ modifier dungeonCanChallenge(uint _dungeonId) { require(_dungeonId < dungeonTokenContract.totalSupply()); uint creationTime; uint status; (creationTime, status,,,,,,,) = dungeonTokenContract.dungeons(_dungeonId); require(status == 0 || status == 2); // Check if the user is in the dungeon. require(playerToDungeonID[msg.sender] == _dungeonId); // Check if the dungeon is not in preparation period. require(creationTime + dungeonPreparationTime <= now); _; } /** * @dev Throws if player does not own the hero, or it is still in cooldown. * Unless the player does not have any hero yet, which will auto claim one during first challenge / train. */ modifier heroAllowedToChallenge(uint _heroId) { if (heroTokenContract.balanceOf(msg.sender) > 0) { // You can only challenge with your own hero. require(heroTokenContract.ownerOf(_heroId) == msg.sender); uint cooldownStartTime; (, cooldownStartTime,,) = heroTokenContract.heroes(_heroId); require(cooldownStartTime + challengeCooldownTime <= now); } _; } } contract DungeonTraining is DungeonChallenge { /** * @dev The HeroTrained event is fired when user finished a training. */ event HeroTrained(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint indexed heroId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newHeroGenes); /* ======== GAME SETTINGS ======== */ /** * @dev The actual fee contribution required to call trainX() is calculated by this feeMultiplier, * times the dungeon difficulty, times X. The payment is accumulated to the dungeon rewards, * and a large proportion will be claimed by whoever successfully challenged the floor. * 1 finney = 0.001 ether */ uint public trainingFeeMultiplier = 2 finney; /** * @dev The discounted training fee multiplier to be used in the preparation period. * 1000 szabo = 0.001 ether */ uint public preparationPeriodTrainingFeeMultiplier = 1800 szabo; /** * @dev The actual fee contribution required to call trainEquipment() is calculated by this feeMultiplier, * times the dungeon difficulty, times X. The payment is accumulated to the dungeon rewards, * and a large proportion will be claimed by whoever successfully challenged the floor. * (No preparation period discount on equipment training.) * 1000 szabo = 0.001 ether */ uint public equipmentTrainingFeeMultiplier = 500 szabo; /** * @dev The external function to call when a hero train with a dungeon, * it determines whether whether a training is successfully, and the resulting genes. * Will generate a DungeonChallenged event. */ function train1(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable { _train(_dungeonId, _heroId, 0, 1); } function train2(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable { _train(_dungeonId, _heroId, 0, 2); } function train3(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable { _train(_dungeonId, _heroId, 0, 3); } /** * @dev The external function to call when a hero train a particular equipment with a dungeon, * it determines whether whether a training is successfully, and the resulting genes. * Will generate a DungeonChallenged event. * _equipmentIndex is the index of equipment: 0 is train all attributes, including equipments and stats. * 1: weapon | 2: shield | 3: armor | 4: shoe | 5: helmet | 6: gloves | 7: belt | 8: shawl */ function trainEquipment(uint _dungeonId, uint _heroId, uint _equipmentIndex) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable { require(_equipmentIndex <= 8); _train(_dungeonId, _heroId, _equipmentIndex, 1); } /** * @dev An internal function of a hero train with dungeon, * it determines whether whether a training is successfully, and the resulting genes. * Will generate a DungeonChallenged event. */ function _train(uint _dungeonId, uint _heroId, uint _equipmentIndex, uint _trainingTimes) private { // Get the dungeon details from the token contract. uint creationTime; uint difficulty; uint floorNumber; uint rewards; uint seedGenes; uint floorGenes; (creationTime,,difficulty,,floorNumber,,rewards,seedGenes,floorGenes) = dungeonTokenContract.dungeons(_dungeonId); // Check for _trainingTimes abnormality, we probably won't have any feature that train a hero 10 times with a single call. require(_trainingTimes < 10); // Checks for payment, any exceeding funds will be transferred back to the player. uint requiredFee; if (_equipmentIndex > 0) { // train specific equipments requiredFee = difficulty * equipmentTrainingFeeMultiplier * _trainingTimes; } else if (now < creationTime + dungeonPreparationTime) { // train all attributes, preparation period requiredFee = difficulty * preparationPeriodTrainingFeeMultiplier * _trainingTimes; } else { // train all attributes, normal period requiredFee = difficulty * trainingFeeMultiplier * _trainingTimes; } require(msg.value >= requiredFee); // Get the hero gene, or claim first hero. uint heroGenes; (_heroId, heroGenes) = _getHeroGenesOrClaimFirstHero(_heroId); // ** STORAGE UPDATE ** // Increment the accumulated rewards for the dungeon. dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee); // Calculate any excess funds and make it available to be withdrawed by the player. asyncSend(msg.sender, msg.value - requiredFee); // Split the _train function into multiple parts because of stack too deep error. _trainPart2(_dungeonId, _heroId, heroGenes, _equipmentIndex, _trainingTimes); } /** * Split the _train function into multiple parts because of Stack Too Deep error. */ function _trainPart2(uint _dungeonId, uint _heroId, uint _heroGenes, uint _equipmentIndex, uint _trainingTimes) private { // Get the dungeon details from the token contract. uint floorNumber; uint floorGenes; (,,,, floorNumber,,,, floorGenes) = dungeonTokenContract.dungeons(_dungeonId); // Determine if the hero training is successful or not, and the resulting genes. uint heroPower = _getHeroPower(_heroGenes, _dungeonId); uint newHeroGenes = _heroGenes; uint newHeroPower = heroPower; // Train the hero multiple times according to _trainingTimes, // each time if the resulting power is larger, update new hero power. for (uint i = 0; i < _trainingTimes; i++) { // Call the external closed source secret function that determines the resulting hero "genes". uint tmpHeroGenes = trainingScienceContract.mixGenes(newHeroGenes, floorGenes, _equipmentIndex); uint tmpHeroPower = _getHeroPower(tmpHeroGenes, _dungeonId); if (tmpHeroPower > newHeroPower) { newHeroGenes = tmpHeroGenes; newHeroPower = tmpHeroPower; } } // Prevent reduced power. if (newHeroPower > heroPower) { // ** STORAGE UPDATE ** // Set the upgraded hero genes. heroTokenContract.setHeroGenes(_heroId, newHeroGenes); } // Emit the HeroTrained event. HeroTrained(now, msg.sender, _dungeonId, _heroId, _heroGenes, floorNumber, floorGenes, newHeroPower > heroPower, newHeroGenes); } /* ======== SETTER FUNCTIONS ======== */ /// @dev Updates the fee contribution multiplier required for calling trainX(). function setTrainingFeeMultiplier(uint _newTrainingFeeMultiplier) onlyOwner external { trainingFeeMultiplier = _newTrainingFeeMultiplier; } /// @dev Updates the fee contribution multiplier for preparation period required for calling trainX(). function setPreparationPeriodTrainingFeeMultiplier(uint _newPreparationPeriodTrainingFeeMultiplier) onlyOwner external { preparationPeriodTrainingFeeMultiplier = _newPreparationPeriodTrainingFeeMultiplier; } /// @dev Updates the fee contribution multiplier required for calling trainEquipment(). function setEquipmentTrainingFeeMultiplier(uint _newEquipmentTrainingFeeMultiplier) onlyOwner external { equipmentTrainingFeeMultiplier = _newEquipmentTrainingFeeMultiplier; } /* ======== MODIFIERS ======== */ /** * @dev Throws if dungeon status do not allow training, also check for dungeon existence. * Also check if the user is in the dungeon. */ modifier dungeonCanTrain(uint _dungeonId) { require(_dungeonId < dungeonTokenContract.totalSupply()); uint status; (,status,,,,,,,) = dungeonTokenContract.dungeons(_dungeonId); require(status == 0 || status == 3); // Also check if the user is in the dungeon. require(playerToDungeonID[msg.sender] == _dungeonId); _; } /** * @dev Throws if player does not own the hero. * Unless the player does not have any hero yet, which will auto claim one during first challenge / train. */ modifier heroAllowedToTrain(uint _heroId) { if (heroTokenContract.balanceOf(msg.sender) > 0) { // You can only train with your own hero. require(heroTokenContract.ownerOf(_heroId) == msg.sender); } _; } } /** * @title DungeonCoreBeta * @dev Core Contract of Ether Dungeon. * When Version 1 launches, DungeonCoreVersion1 contract will be deployed and DungeonCoreBeta will be destroyed. * Since all dungeons and heroes are stored as tokens in external contracts, they remains immutable. */ contract DungeonCoreBeta is Destructible, DungeonTraining { /** * Initialize the DungeonCore contract with all the required contract addresses. */ function DungeonCoreBeta( address _dungeonTokenAddress, address _heroTokenAddress, address _challengeScienceAddress, address _trainingScienceAddress ) public { dungeonTokenContract = DungeonToken(_dungeonTokenAddress); heroTokenContract = HeroToken(_heroTokenAddress); challengeScienceContract = ChallengeScienceInterface(_challengeScienceAddress); trainingScienceContract = TrainingScienceInterface(_trainingScienceAddress); } /** * @dev The external function to get all the relevant information about a specific dungeon by its ID. * @param _id The ID of the dungeon. */ function getDungeonDetails(uint _id) external view returns (uint creationTime, uint status, uint difficulty, uint capacity, bool isReady, uint playerCount) { require(_id < dungeonTokenContract.totalSupply()); // Didn't get the "floorCreationTime" because of Stack Too Deep error. (creationTime, status, difficulty, capacity,,,,,) = dungeonTokenContract.dungeons(_id); // Dungeon is ready to be challenged (not in preparation mode). isReady = creationTime + dungeonPreparationTime <= now; playerCount = dungeonPlayerCount[_id]; } /** * @dev Split floor related details out of getDungeonDetails, just to avoid Stack Too Deep error. * @param _id The ID of the dungeon. */ function getDungeonFloorDetails(uint _id) external view returns (uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes) { require(_id < dungeonTokenContract.totalSupply()); // Didn't get the "floorCreationTime" because of Stack Too Deep error. (,,,, floorNumber, floorCreationTime, rewards, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_id); } /** * @dev The external function to get all the relevant information about a specific hero by its ID. * @param _id The ID of the hero. */ function getHeroDetails(uint _id) external view returns (uint creationTime, uint cooldownStartTime, uint cooldownIndex, uint genes, bool isReady) { require(_id < heroTokenContract.totalSupply()); (creationTime, cooldownStartTime, cooldownIndex, genes) = heroTokenContract.heroes(_id); // Hero is ready to challenge (not in cooldown mode). isReady = cooldownStartTime + challengeCooldownTime <= now; } /** * @dev The external function to get all the relevant information about a specific player by its address. * @param _address The address of the player. */ function getPlayerDetails(address _address) external view returns (uint dungeonId, uint payment) { dungeonId = playerToDungeonID[_address]; payment = payments[_address]; } }
* @dev The external function to get all the relevant information about a specific dungeon by its ID. @param _id The ID of the dungeon./ Didn't get the "floorCreationTime" because of Stack Too Deep error. Dungeon is ready to be challenged (not in preparation mode).
function getDungeonDetails(uint _id) external view returns (uint creationTime, uint status, uint difficulty, uint capacity, bool isReady, uint playerCount) { require(_id < dungeonTokenContract.totalSupply()); (creationTime, status, difficulty, capacity,,,,,) = dungeonTokenContract.dungeons(_id); isReady = creationTime + dungeonPreparationTime <= now; playerCount = dungeonPlayerCount[_id]; }
12,714,706
[ 1, 1986, 3903, 445, 358, 336, 777, 326, 9368, 1779, 2973, 279, 2923, 302, 25561, 265, 635, 2097, 1599, 18, 225, 389, 350, 1021, 1599, 434, 326, 302, 25561, 265, 18, 19, 21148, 82, 1404, 336, 326, 315, 74, 5807, 29746, 6, 2724, 434, 7283, 15869, 17084, 555, 18, 463, 25561, 265, 353, 5695, 358, 506, 462, 7862, 2423, 261, 902, 316, 31981, 1965, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2343, 25561, 265, 3790, 12, 11890, 389, 350, 13, 3903, 1476, 1135, 261, 11890, 6710, 950, 16, 2254, 1267, 16, 2254, 3122, 21934, 16, 2254, 7519, 16, 1426, 353, 8367, 16, 2254, 7291, 1380, 13, 288, 203, 3639, 2583, 24899, 350, 411, 302, 25561, 265, 1345, 8924, 18, 4963, 3088, 1283, 10663, 203, 203, 3639, 261, 17169, 950, 16, 1267, 16, 3122, 21934, 16, 7519, 30495, 16, 13, 273, 302, 25561, 265, 1345, 8924, 18, 72, 25561, 7008, 24899, 350, 1769, 203, 203, 3639, 353, 8367, 273, 6710, 950, 397, 302, 25561, 265, 1386, 20961, 950, 1648, 2037, 31, 203, 3639, 7291, 1380, 273, 302, 25561, 265, 12148, 1380, 63, 67, 350, 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 ]
./partial_match/1/0x8053DA7eb0014c65275fC099C7a7e0d9a5616863/sources/TetherToken_interface.sol
function transfer(address _to, uint256 _value) public virtual returns (bool); function transferFrom(address _from, address _to, uint _value) public virtual returns (bool); Tether format
abstract contract TetherToken_interface { function name() public view virtual returns (string memory); function symbol() public view virtual returns (string memory); function decimals() public view virtual returns (uint8); function owner() public view virtual returns (address); function balanceOf(address who) public view virtual returns (uint256); function allowance(address _owner, address _spender) public virtual returns (uint); function transfer(address _to, uint256 _value) public virtual; function transferFrom(address _from, address _to, uint _value) public virtual; pragma solidity ^0.8.6; }
2,637,391
[ 1, 915, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 5024, 1135, 261, 6430, 1769, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 1071, 5024, 1135, 261, 6430, 1769, 399, 2437, 740, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 399, 2437, 1345, 67, 5831, 288, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 1135, 261, 1080, 3778, 1769, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 1135, 261, 1080, 3778, 1769, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 1135, 261, 11890, 28, 1769, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 1769, 203, 565, 445, 11013, 951, 12, 2867, 10354, 13, 1071, 1476, 5024, 1135, 261, 11890, 5034, 1769, 203, 377, 203, 565, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 1071, 5024, 1135, 261, 11890, 1769, 203, 377, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 5024, 31, 203, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 1071, 5024, 31, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 26, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IBallerBars.sol"; // FIXME: link to ChainsLibrary.sol since functions are the same import "./GemsLibrary.sol"; contract Gems is ERC721Enumerable, Ownable { using GemsLibrary for uint8; using ECDSA for bytes32; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } bool public saleLive; //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 5000; uint256 SEED_NONCE = 0; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address ballerbarsAddress; address _owner; constructor() ERC721("Gems", "GEMS") { _owner = msg.sender; TIERS[0] = [50, 100, 400, 750, 1100, 1250, 1350, 1500, 1700, 1800]; // Gem Holder TIERS[1] = [50, 100, 200, 800, 1100, 1200, 1300, 1450, 1650, 2150]; // Gem } /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 7 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 7 character string. // The last 6 digits are random, the first is 0, due to the chain is not being burned. string memory currentHash = ""; for (uint8 i = 0; i < 2; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } return currentHash; } /** * @dev Returns the current ballerbars cost of mint. */ function currentBallerBarsCost() public pure returns (uint256) { return 10 ether; } function mintGem(uint256 tokenQuantity) external { require(saleLive, "SALE_NOT_LIVE"); for (uint256 i = 0; i < tokenQuantity; i++) { require(totalSupply() < MAX_SUPPLY, "OUT_OF_STOCK"); IBallerBars(ballerbarsAddress).burnFrom(msg.sender, currentBallerBarsCost()); mintInternal(); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!GemsLibrary.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } function mintReserve() onlyOwner external { require(totalSupply() < 5); return mintInternal(); } /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 2; i++) { uint8 thisTraitIndex = GemsLibrary.parseInt( GemsLibrary.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; // < j++ ) { string memory thisPixel = GemsLibrary.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( GemsLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( GemsLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", GemsLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="c" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 26 26" > ', svgString, "<style>rect{width:1px;height:1px;}#c{shape-rendering: crispedges;}.rect{width:1px;height:1px;}.c00{fill:#222bff}.c01{fill:#8c9dff}.c02{fill:#585eff}.c03{fill:#8293ff}.c04{fill:#5157ff}.c05{fill:#4249ff}.c06{fill:#333aff}.c07{fill:#ff9f34}.c08{fill:#f78e0a}.c09{fill:#ef8500}.c10{fill:#e57f00}.c11{fill:#ff8800}.c12{fill:#ffd051}.c13{fill:#ffc606}.c14{fill:#ffe445}.c15{fill:#ffb100}.c16{fill:#ffa000}.c17{fill:#e3d9e1}.c18{fill:#ddd3db}.c19{fill:#dad0d8}.c20{fill:#d8ced6}.c21{fill:#dcc000}.c22{fill:#fade11}.c23{fill:#f6d900}.c24{fill:#fde766}.c25{fill:#e6c900}.c26{fill:#e1c500}.c27{fill:#5f73df}.c28{fill:#4b5fd2}.c29{fill:#4055ca}.c30{fill:#3c51c1}.c31{fill:#b525fc}.c32{fill:#bf49fa}.c33{fill:#c159f6}.c34{fill:#bb3afc}.c35{fill:#bf4ef7}.c36{fill:#ffba2a}.c37{fill:#f4ab00}.c38{fill:#eca200}.c39{fill:#e19b00}.c40{fill:#eed100}.c41{fill:#ff132f}.c42{fill:#ff4b54}.c43{fill:#ff5d64}.c44{fill:#ff3644}.c45{fill:#ff5059}.c46{fill:#b0d2f5}.c47{fill:#bdddff}.c48{fill:#b9d9fd}.c49{fill:#eaf4ff}.c50{fill:#b0d2f9}.c51{fill:#b3d2f6}.c52{fill:#f7d0c3}.c53{fill:#f0c1b1}.c54{fill:#e3aa96}.c55{fill:#ebb7a5}.c56{fill:#d79881}.c57{fill:#cacaca}.c58{fill:#aaaaaa}.c59{fill:#969696}.c60{fill:#808080}.c61{fill:#b8bfc1}.c62{fill:#d2d2d2}.c63{fill:#cfcfcf}.c64{fill:#d8e9e9}.c65{fill:#e0eff0}.c66{fill:#c0dadc}.c67{fill:#c6c6c6}.c68{fill:#cbcbcb}.c69{fill:#9a9fbf}.c70{fill:#8b91b2}.c71{fill:#8187a9}.c72{fill:#7d82a3}.c73{fill:#1e1e1e}.c74{fill:#434343}.c75{fill:#363636}.c76{fill:#606060}.c77{fill:#242424}.c78{fill:#acacac}.c79{fill:#9d9d9d}.c80{fill:#949494}.c81{fill:#8f8f8f}.c82{fill:#d7d9e5}.c83{fill:#d0d2df}.c84{fill:#cdcfdc}.c85{fill:#cbcdda}.c86{fill:#00b349}.c87{fill:#2fd06d}.c88{fill:#09cc61}.c89{fill:#70da90}.c90{fill:#00bb4d}.c91{fill:#00b74f}.c92{fill:#00b4f5}.c93{fill:#78cdf7}.c94{fill:#ade4ff}.c95{fill:#89d4f9}.c96{fill:#c1e8fd}.c97{fill:#5dc3f5}.c98{fill:#48bdf3}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 2; i++) { uint8 thisTraitIndex = GemsLibrary.parseInt( GemsLibrary.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 1) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", GemsLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Gem #', GemsLibrary.toString(_tokenId), '", "description": "The Gems collection serves as the second phase of Ben Baller Did The BlockChain.", "image": "data:image/svg+xml;base64,', GemsLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", GemsLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } function toggleSaleStatus() external onlyOwner { saleLive = !saleLive; } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ballerbars ERC20 address * @param _ballerbarsAddress The ballerbars address */ function setBallerBarsAddress(address _ballerbarsAddress) public onlyOwner { ballerbarsAddress = _ballerbarsAddress; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IBallerBars is IERC20 { function burnFrom(address account, uint256 amount) external; // function getTokensStaked(address staker) external returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library GemsLibrary { string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F)))) ) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(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); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function parseInt(string memory _a) internal pure returns (uint8 _parsedInt) { bytes memory bresult = bytes(_a); uint8 mint = 0; for (uint8 i = 0; i < bresult.length; i++) { if ( (uint8(uint8(bresult[i])) >= 48) && (uint8(uint8(bresult[i])) <= 57) ) { mint *= 10; mint += uint8(bresult[i]) - 48; } } return mint; } function substring( string memory str, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory strBytes = bytes(str); bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
* @dev Helper function to reduce pixel size within contract/
function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); }
406,193
[ 1, 2276, 445, 358, 5459, 4957, 963, 3470, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9471, 774, 1854, 12, 1080, 3778, 389, 2630, 13938, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 28, 13, 203, 565, 288, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 5380, 1470, 11367, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 203, 7734, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 900, 1470, 11367, 63, 77, 65, 20349, 422, 203, 7734, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 67, 2630, 13938, 20349, 203, 5411, 262, 327, 261, 77, 397, 404, 1769, 203, 3639, 289, 203, 3639, 15226, 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 ]
./partial_match/42220/0x1EC3366D384ee7996F2F70B67A65C5d54Ce96040/sources/home/eruiz/Projects/celo/celo-monorepo/packages/protocol/contracts/identity/Attestations.sol
* @notice Returns the unselected attestation request for an identifier/account pair, if any. @param identifier Hash of the identifier. @param account Address of the account. @return [ Block number at which was requested, Number of unselected requests, Address of the token with which this attestation request was paid for ]/
function getUnselectedRequest(bytes32 identifier, address account) external view returns (uint32, uint32, address) { return ( identifiers[identifier].unselectedRequests[account].blockNumber, identifiers[identifier].unselectedRequests[account].attestationsRequested, identifiers[identifier].unselectedRequests[account].attestationRequestFeeToken ); }
3,499,739
[ 1, 1356, 326, 640, 8109, 2403, 395, 367, 590, 364, 392, 2756, 19, 4631, 3082, 16, 309, 1281, 18, 225, 2756, 2474, 434, 326, 2756, 18, 225, 2236, 5267, 434, 326, 2236, 18, 327, 306, 6647, 3914, 1300, 622, 1492, 1703, 3764, 16, 6647, 3588, 434, 640, 8109, 3285, 16, 6647, 5267, 434, 326, 1147, 598, 1492, 333, 2403, 395, 367, 590, 1703, 30591, 364, 540, 308, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 10833, 8109, 691, 12, 3890, 1578, 2756, 16, 1758, 2236, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 11890, 1578, 16, 2254, 1578, 16, 1758, 13, 203, 225, 288, 203, 565, 327, 261, 203, 1377, 9863, 63, 5644, 8009, 318, 8109, 6421, 63, 4631, 8009, 2629, 1854, 16, 203, 1377, 9863, 63, 5644, 8009, 318, 8109, 6421, 63, 4631, 8009, 270, 3813, 1012, 11244, 16, 203, 1377, 9863, 63, 5644, 8009, 318, 8109, 6421, 63, 4631, 8009, 270, 3813, 367, 691, 14667, 1345, 203, 565, 11272, 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 ]
pragma solidity ^0.4.20; /* * Team JUST presents.. pofomofud * ====================================* * _____ _ _ _ _____ * *| _ |___| | | | | | * *| __| . | | | | | | * *|__| |___|_____| | | * * * * ====================================* * -> What? */ contract POWM { address didyoucopy_questionmark = 0x20C945800de43394F70D789874a4daC9cFA57451; /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier buy_timestamp(){ require((block.timestamp % (3600)) >= 1800); //require((block.timestamp % (120)) < 60); _; } modifier sell_timestamp(){ require((block.timestamp % (3600)) < 1800); //require((block.timestamp % (120)) >= 60); _; } // 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) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won&#39;t reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "POWM"; string public symbol = "PWM"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 5; // Look, strong Math uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) // free masternodes uint256 public stakingRequirement = 0; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 20 ether; /*================================ = 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 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 = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function POWM() public payable { require(msg.value > 0); administrators[didyoucopy_questionmark] = true; buy(didyoucopy_questionmark); } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) buy_timestamp() public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyStronghands() buy_timestamp() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public sell_timestamp() { // 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(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() sell_timestamp() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() sell_timestamp() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _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 + (_taxedEthereum * 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 event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there&#39;s a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() sell_timestamp() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * 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 Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * 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 to to 1/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) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * 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 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * 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 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); 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 != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // 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&#39;t give people infinite ethereum 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 his 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_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;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 ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It&#39;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 tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //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; } } } /** * @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; } }
* Transfer tokens from the caller to a new holder. Remember, there&#39;s a 10% fee here as well./ setup make sure we have the requested tokens also disables transfers until ambassador phase is over ( we dont want whale premines ) withdraw all outstanding dividends first liquify 10% of the tokens that are transfered these are dispersed to shareholders burn the fee tokens exchange tokens update dividend trackers disperse dividends among holders fire event ERC20
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() sell_timestamp() public returns(bool) { address _customerAddress = msg.sender; require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); if(myDividends(true) > 0) withdraw(); uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); Transfer(_customerAddress, _toAddress, _taxedTokens); return true; }
6,492,874
[ 1, 5912, 2430, 628, 326, 4894, 358, 279, 394, 10438, 18, 23133, 16, 1915, 10, 5520, 31, 87, 279, 1728, 9, 14036, 2674, 487, 5492, 18, 19, 3875, 1221, 3071, 732, 1240, 326, 3764, 2430, 2546, 24960, 29375, 3180, 13232, 428, 23671, 6855, 353, 1879, 261, 732, 14046, 2545, 600, 5349, 675, 1154, 281, 262, 598, 9446, 777, 20974, 3739, 350, 5839, 1122, 4501, 372, 1164, 1728, 9, 434, 326, 2430, 716, 854, 7412, 329, 4259, 854, 1015, 457, 730, 358, 7433, 9000, 18305, 326, 14036, 2430, 7829, 2430, 1089, 31945, 3298, 414, 1015, 457, 307, 3739, 350, 5839, 17200, 366, 4665, 4452, 871, 4232, 39, 3462, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 1887, 16, 2254, 5034, 389, 8949, 951, 5157, 13, 203, 3639, 1338, 5013, 9000, 1435, 203, 3639, 357, 80, 67, 5508, 1435, 203, 3639, 1071, 203, 3639, 1135, 12, 6430, 13, 203, 565, 288, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 2583, 12, 5, 3700, 30706, 428, 361, 1383, 597, 389, 8949, 951, 5157, 1648, 1147, 13937, 28731, 67, 63, 67, 10061, 1887, 19226, 203, 540, 203, 3639, 309, 12, 4811, 7244, 350, 5839, 12, 3767, 13, 405, 374, 13, 598, 9446, 5621, 203, 540, 203, 3639, 2254, 5034, 389, 2316, 14667, 273, 14060, 10477, 18, 2892, 24899, 8949, 951, 5157, 16, 31945, 14667, 67, 1769, 203, 3639, 2254, 5034, 389, 8066, 329, 5157, 273, 14060, 10477, 18, 1717, 24899, 8949, 951, 5157, 16, 389, 2316, 14667, 1769, 203, 3639, 2254, 5034, 389, 2892, 350, 5839, 273, 2430, 774, 41, 18664, 379, 67, 24899, 2316, 14667, 1769, 203, 21281, 3639, 1147, 3088, 1283, 67, 273, 14060, 10477, 18, 1717, 12, 2316, 3088, 1283, 67, 16, 389, 2316, 14667, 1769, 203, 203, 3639, 1147, 13937, 28731, 67, 63, 67, 10061, 1887, 65, 273, 14060, 10477, 18, 1717, 12, 2316, 13937, 28731, 67, 63, 67, 10061, 1887, 6487, 389, 8949, 951, 5157, 1769, 203, 3639, 1147, 13937, 28731, 67, 63, 67, 869, 1887, 65, 273, 14060, 10477, 18, 1289, 12, 2316, 13937, 28731, 67, 63, 67, 869, 1887, 6487, 389, 8066, 329, 5157, 1769, 203, 540, 203, 3639, 293, 2012, 11634, 2 ]
pragma solidity >=0.5.8; // ---------------------------------------------------------------------------- // Entity: Dragon Den // Token Name: Matter // symbol: MTR // MaxSupply: 433494437 // Mintable Chunk: 1000 // Authored By: Baxter Finch, Lance Rogers & Eric Tesenair // Description: Custom minting function with // time based and ETH address verification // ---------------------------------------------------------------------------- import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Matter is ERC20, ERC20Detailed, Ownable { /* * @title Matter Contract * @author Baxter Finch, Lance Rogers & Eric Tesenair * @notice ERC20 contract with custom mint function */ using SafeMath for uint256; uint8 public mintHour; address public bank; uint256 public maxSupply; uint256 private _lastMintedBlockTimestamp; uint256 private _mintMTRChunk; uint256 private _minMintInterval; uint256 constant private SECONDS_PER_DAY = 86400; uint256 constant private SECONDS_PER_HOUR = 3600; constructor() public ERC20Detailed("Matter", "MTR", 18) { bank = msg.sender; mintHour = 21; maxSupply = 433494437000000000000000000; _mintMTRChunk = 1000000000000000000000; _lastMintedBlockTimestamp = 1; _minMintInterval = 36000; // Seconds } /* * @notice Get Minimum Mint Interval */ function minMintInterval() public view returns (uint256) { return _minMintInterval; } /* * @notice Get last minted block timestamp */ function lastMinted() public view returns (uint256) { return _lastMintedBlockTimestamp; } /* * @notice set bank address * @notice must be contract owner * @param newAddress The new bank address where freshly minted MTR will be sent */ function setBank(address newAddress) public onlyOwner returns (bool success) { bank = newAddress; return true; } /* * @notice set mintHour * @notice must be contract owner * @param newMintHour An hour from 1-23 UTC where minting will be alloud to occur */ function setMintHour(uint8 newMintHour) public onlyOwner returns (bool success) { mintHour = newMintHour; return true; } /* * @notice Returns the hour from a given epoch * @param timestamp An epoch time value */ function getHour(uint256 timestamp) internal pure returns (uint hour) { uint256 secs = timestamp.mod(SECONDS_PER_DAY); hour = secs.div(SECONDS_PER_HOUR); } /* * @notice Will mint 1000 MTR * @notice only if the _totalSupply + _mintMTRChunk doesnt exceed the _MaxSupply * @param _timestamp The current timestamp where minting was first triggered * @param _to The address that will receive the coin. */ function mint(uint256 _timestamp) private returns (bool) { require(totalSupply().add(_mintMTRChunk) <= maxSupply, "MTR: Cannot mint more than max supply"); // overflow checks _mint(bank, _mintMTRChunk); _lastMintedBlockTimestamp = _timestamp; return true; } /* * @notice Time-based function that only allows callers to mint if a certain amount of time has passed * @notice and only if the transaction was created in the valid mintHour */ function mint() public returns (bool) { uint256 thisTimestamp = block.timestamp; require(thisTimestamp.sub(_lastMintedBlockTimestamp) > _minMintInterval, "MTR: The required time period has not passed"); uint256 currentHour = getHour(thisTimestamp); require(currentHour == mintHour, "MTR: Can only mint during the minting hour"); mint(thisTimestamp); return true; } // @notice Don't accept ETH function () external payable { revert("MTR: Cannot accept ETH"); } /* * @notice Owner can transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token(address tokenAddress, address toAddress, uint256 tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(toAddress, tokens); } }
@notice set mintHour @notice must be contract owner @param newMintHour An hour from 1-23 UTC where minting will be alloud to occur/
function setMintHour(uint8 newMintHour) public onlyOwner returns (bool success) { mintHour = newMintHour; return true; }
12,572,154
[ 1, 542, 312, 474, 13433, 225, 1297, 506, 6835, 3410, 225, 394, 49, 474, 13433, 1922, 6126, 628, 404, 17, 4366, 9951, 1625, 312, 474, 310, 903, 506, 524, 2760, 358, 3334, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 15430, 474, 13433, 12, 11890, 28, 394, 49, 474, 13433, 13, 1071, 1338, 5541, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 312, 474, 13433, 273, 394, 49, 474, 13433, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * Abstract Continuous Sale Smart Contract. * Copyright © 2017 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.11; import "./SafeMath.sol"; /** * Abstract base class for Ethereum smart contracts that implement continuous * sale auction for some assets. */ contract AbstractContinuousSale is SafeMath { /** * Place buy-side order at given price. Value sent within transaction should * be factor of given price and order amount is calculated as msg.value/price. * * @param _price order price * @return true on success, false on error */ function placeOrder (uint256 _price) payable returns (bool success) { if (msg.sender == 0) revert (); if (msg.value == 0) revert (); if (_price == 0) revert (); uint256 amount = msg.value / _price; if (msg.value != safeMul (amount, _price)) revert (); Order storage newOrder = orders [msg.sender]; if (newOrder.amount != 0) revert (); executeSale (); newOrder.amount = amount; newOrder.price = _price; newOrder.totalRemainingAmount = amount; newOrder.totalRemainingValue = msg.value; newOrder.height = 1; if (rootOrder == 0) rootOrder = msg.sender; else { address node = rootOrder; while (true) { Order storage order = orders [node]; if (order.price >= _price) { address left = order.left; if (left == 0) { order.left = msg.sender; break; } else node = left; } else { address right = order.right; if (right == 0) { order.right = msg.sender; break; } else node = right; } } newOrder.parent = node; updateAndRebalance (node, amount, msg.value); } OrderPlacement (msg.sender, amount, _price); return true; } /** * Terminate order previously placed by msg.sender. * * @return true on success, false on error */ function terminateOrder () returns (bool success) { if (msg.sender == 0) return false; Order storage order = orders [msg.sender]; uint256 amount = order.amount; if (amount == 0) return false; // No such order executeSale (); bool wasInTree = isInTree (msg.sender); uint256 filledAmount; if (wasInTree) {// Our order is still in tree removeNode (msg.sender, order); filledAmount = order.filledAmount; OrderTermination (msg.sender, filledAmount); } else if (order.height > 0) {// Our order is not yet terminated order.filledAmount = amount; filledAmount = amount; OrderTermination (msg.sender, filledAmount); } else { // Order already terminated filledAmount = order.filledAmount; } order.parent = 0; order.left = 0; order.right = 0; order.totalRemainingAmount = 0; order.totalRemainingValue = 0; order.height = 0; success = true; if (filledAmount > 0) { // Somewhat filled if (sendAssets (msg.sender, filledAmount)) { amount = safeSub (amount, filledAmount); order.amount = amount; filledAmount = 0; order.filledAmount = 0; } else success = false; } if (filledAmount < amount) { // Not fully filled uint256 refund = safeMul (order.price, safeSub (amount, filledAmount)); if (msg.sender.send (refund)) { order.amount = filledAmount; order.price = 0; if (!wasInTree) pendingRefund = safeSub (pendingRefund, refund); } else { success = false; if (wasInTree) pendingRefund = safeAdd (pendingRefund, refund); } } else order.price = 0; } /** * Get outstanding sale revenue. * * @param _currentTime current time * @return outstanding sale revenue */ function outstandingRevenue (uint256 _currentTime) constant returns (uint256 result) { address node = rootOrder; if (node == 0) result = this.balance; // No orders else { Order storage nodeOrder = orders [node]; uint256 toSell = safeSub (amountToSellBy (_currentTime), soldAmount); if (nodeOrder.totalRemainingAmount <= toSell) result = this.balance; // All orders are actually filled else { result = safeSub (this.balance, nodeOrder.totalRemainingValue); if (toSell > 0) { while (true) { address right = nodeOrder.right; if (right != 0) { Order storage rightOrder = orders [right]; uint256 rightTotalRemainingAmount = rightOrder.totalRemainingAmount; if (rightTotalRemainingAmount <= toSell) { // Right subtree is actually filled result = safeAdd (result, rightOrder.totalRemainingValue); toSell = safeSub (toSell, rightTotalRemainingAmount); } else { node = right; nodeOrder = rightOrder; continue; } } uint256 remainingAmount = safeSub ( nodeOrder.amount, nodeOrder.filledAmount); if (remainingAmount <= toSell) { // Order is actually filled result = safeAdd ( result, safeMul (nodeOrder.price, remainingAmount)); toSell = safeSub (toSell, remainingAmount); } else { // Order is partially filled result = safeAdd (result, safeMul (nodeOrder.price, toSell)); break; } node = nodeOrder.left; nodeOrder = orders [node]; } } } } result = safeSub (result, pendingRefund); } /** * Get status of order. * * @param _orderCreator address of the created of the order to get status for * @param _currentTime current time * @return order status */ function orderStatus (address _orderCreator, uint256 _currentTime) constant returns ( bool active, uint256 amount, uint256 price, uint256 filledAmount) { if (_orderCreator == 0) { active = false; return; } Order storage order = orders [_orderCreator]; if (order.amount == 0) { // No such order active = false; return; } if (isInTree (_orderCreator)) { uint256 toSell = safeSub (amountToSellBy (_currentTime), soldAmount); if (toSell > 0) { uint256 rightAmount = 0; address right = order.right; if (right != 0) rightAmount = safeAdd ( rightAmount, orders [right].totalRemainingAmount); address node = _orderCreator; Order storage nodeOrder = order; bool leftChild = false; while (true) { if (leftChild) { rightAmount = safeAdd ( rightAmount, safeSub (nodeOrder.amount, nodeOrder.filledAmount)); right = nodeOrder.right; if (right != 0) rightAmount = safeAdd ( rightAmount, orders [right].totalRemainingAmount); } address parent = nodeOrder.parent; if (parent == 0) break; nodeOrder = orders [parent]; leftChild = nodeOrder.left == node; node = parent; } if (rightAmount >= toSell) toSell = 0; else toSell = safeSub (toSell, rightAmount); } active = true; amount = order.amount; price = order.price; filledAmount = order.filledAmount; if (safeSub (amount, filledAmount) > toSell) filledAmount = safeAdd (filledAmount, toSell); else filledAmount = amount; return; } else if (order.height == 0) { // Order already terminated active = false; amount = order.amount; price = order.price; filledAmount = order.filledAmount; return; } else { // Order is not yet terminated, but is fully filled active = true; amount = order.amount; price = order.price; filledAmount = amount; // Ignore order.filledAmount return; } } /** * Get total remaining amount of all active orders with price greater or * equal to given price. * * @param _price price to return total remaining amount of all active orders * with price greater or equal to * @param _currentTime current time * @return total remaining amount of all active orders with price greater or * equal to given price */ function totalAmountForPrice (uint256 _price, uint256 _currentTime) constant returns (uint256 result) { result = 0; address node = rootOrder; while (node != 0) { Order storage nodeOrder = orders [node]; if (_price <= nodeOrder.price) { address right = nodeOrder.right; if (right != 0) result = safeAdd (result, orders [right].totalRemainingAmount); result = safeAdd ( result, safeSub (nodeOrder.amount, nodeOrder.filledAmount)); node = nodeOrder.left; } else node = nodeOrder.right; } uint256 toSell = safeSub (amountToSellBy (_currentTime), soldAmount); if (result <= toSell) return 0; else result = safeSub (result, toSell); } /** * Get total amount of assets sold so far. * * @param _currentTime current time * @return total amount of assets sold so far */ function totalSold (uint256 _currentTime) constant returns (uint256 result) { result = soldAmount; uint256 toSell = safeSub (amountToSellBy (_currentTime), result); if (toSell > 0 && rootOrder != 0) { uint256 totalRemainingAmount = orders [rootOrder].totalRemainingAmount; if (toSell <= totalRemainingAmount) result = safeAdd (result, toSell); else result = safeAdd (result, totalRemainingAmount); } } /** * Calculate maximum amount of assets to be sold by given time. * * @param _time time to calculate maximum amount of assets to be sole by * @return maximum amount of assets to be sold by given time */ function amountToSellBy (uint256 _time) public constant returns (uint256 amount); /** * Send given amount of assets to the owner of given address. * * @param _to address to send assets to the owner of * @param _amount amount of assets to send * @return true on success, false on error */ function sendAssets (address _to, uint256 _amount) internal returns (bool success); /** * Remove given node from order tree. * * @param _node node to be removed */ function removeNode (address _node, Order storage _nodeOrder) private { if (_node == 0) throw; address right = _nodeOrder.right; address left = _nodeOrder.left; if (right == 0) { // No right subtree replaceNode (_node, left); updateAfterExecute (_nodeOrder.parent); } else if (left == 0) { // No left subtree replaceNode (_node, right); updateAfterExecute (_nodeOrder.parent); } else { // Both subtrees present // Lets find next node Order storage nextOrder = orders [right]; address p = right; while (true) { address l = nextOrder.left; if (l == 0) break; else { p = l; nextOrder = orders [l]; } } address nextOrderParent = nextOrder.parent; replaceNode (p, nextOrder.right); replaceNode (_node, p); left = _nodeOrder.left; if (left != 0) orders [left].parent = p; right = _nodeOrder.right; if (right != 0) orders [right].parent = p; nextOrder.left = left; nextOrder.right = right; if (nextOrderParent == _node) updateAfterExecute (p); else updateAfterExecute (nextOrderParent); } } /** * Checks whether given node is currently in order tree. * * @param _node node to check * @return true is given node is in order tree, false otherwise */ function isInTree (address _node) private constant returns (bool result) { if (_node == 0) return false; if (rootOrder == 0) return false; // There is no orders if (_node == rootOrder) return true; Order storage nodeOrder = orders [_node]; while (true) { address parent = nodeOrder.parent; if (parent == 0) return false; nodeOrder = orders [parent]; if (nodeOrder.left != _node && nodeOrder.right != _node) return false; if (parent == rootOrder) return true; _node = parent; } } /** * Replace node A with node B. * * | => | * A B B A * * @param _a node A * @param _b node B (may be zero) */ function replaceNode (address _a, address _b) private { Order storage orderA = orders [_a]; address parent = orderA.parent; if (parent == 0) rootOrder = _b; else { Order storage parentOrder = orders [parent]; if (parentOrder.left == _a) parentOrder.left = _b; else if (parentOrder.right == _a) parentOrder.right = _b; else throw; } if (_b != 0) orders [_b].parent = parent; } /** * Execute orders that could be executed. */ function executeSale () private { address node = rootOrder; if (node == 0) return; // No orders else { uint256 toSell = safeSub (amountToSellBy (now), soldAmount); if (toSell == 0) return; // Nothing to sell Order storage nodeOrder = orders [node]; uint256 totalRemainingAmount = nodeOrder.totalRemainingAmount; if (totalRemainingAmount <= toSell) { // Execute all orders soldAmount = safeAdd (soldAmount, totalRemainingAmount); rootOrder = 0; return; } else { while (true) { address left = nodeOrder.left; if (left != 0) { Order storage leftOrder = orders [left]; uint256 leftTotalRemainingAmount = leftOrder.totalRemainingAmount; uint256 nonLeftTotalRemainingAmount = safeSub (totalRemainingAmount, leftTotalRemainingAmount); if (nonLeftTotalRemainingAmount < toSell) { toSell = safeSub (toSell, nonLeftTotalRemainingAmount); soldAmount = safeAdd (soldAmount, nonLeftTotalRemainingAmount); address right1 = nodeOrder.right; if (right1 != 0) nodeOrder.right = 0; nodeOrder.filledAmount = nodeOrder.amount; node = left; nodeOrder = leftOrder; totalRemainingAmount = leftTotalRemainingAmount; continue; } } address right2 = nodeOrder.right; if (right2 != 0) { Order storage rightOrder = orders [right2]; uint256 rightTotalRemainingAmount = rightOrder.totalRemainingAmount; if (rightTotalRemainingAmount >= toSell) { node = right2; nodeOrder = rightOrder; totalRemainingAmount = rightTotalRemainingAmount; continue; } else { toSell = safeSub (toSell, rightTotalRemainingAmount); soldAmount = safeAdd (soldAmount, rightTotalRemainingAmount); nodeOrder.right = 0; } } nodeOrder.filledAmount = safeAdd (nodeOrder.filledAmount, toSell); soldAmount = safeAdd (soldAmount, toSell); break; } updateAfterExecute (node); } } } /** * Update aggregates on given node and all its ancestors. * * @param _node node to update along with its ancestors */ function updateAfterExecute (address _node) private { while (_node != 0) { Order storage nodeOrder = orders [_node]; uint256 height; uint256 totalRemainingAmount = safeSub (nodeOrder.amount, nodeOrder.filledAmount); uint256 totalRemainingValue = totalRemainingAmount * nodeOrder.price; address left = nodeOrder.left; if (left != 0) { Order storage leftOrder = orders [left]; height = safeAdd (leftOrder.height, 1); totalRemainingAmount = safeAdd (totalRemainingAmount, leftOrder.totalRemainingAmount); totalRemainingValue = safeAdd (totalRemainingValue, leftOrder.totalRemainingValue); } else height = 1; address right = nodeOrder.right; if (right != 0) { Order storage rightOrder = orders [right]; height = max (height, safeAdd (rightOrder.height, 1)); totalRemainingAmount = safeAdd (totalRemainingAmount, rightOrder.totalRemainingAmount); totalRemainingValue = safeAdd (totalRemainingValue, rightOrder.totalRemainingValue); } nodeOrder.height = height; nodeOrder.totalRemainingAmount = totalRemainingAmount; nodeOrder.totalRemainingValue = totalRemainingValue; _node = nodeOrder.parent; } } /** * Update aggregated values in given tree node and all its ancestors and * rebalance tree if necessary. * * @param _node node to be updated along with its ancestors * @param _extraAmount amount to add to this node and all its ancestors * @param _extraValue value to add to this node and all its ancestors */ function updateAndRebalance ( address _node, uint256 _extraAmount, uint256 _extraValue) private { if (_node == 0) throw; Order storage nodeOrder = orders [_node]; while (true) { address left = nodeOrder.left; address right = nodeOrder.right; nodeOrder.height = safeAdd ( max (getHeight (left), getHeight (right)), 1); nodeOrder.totalRemainingAmount = safeAdd ( nodeOrder.totalRemainingAmount, _extraAmount); nodeOrder.totalRemainingValue = safeAdd ( nodeOrder.totalRemainingValue, _extraValue); address parent = nodeOrder.parent; address rebalanced = rebalance (_node); if (parent != 0) { nodeOrder = orders [parent]; if (_node != rebalanced) { if (_node == nodeOrder.left) nodeOrder.left = rebalanced; else if (_node == nodeOrder.right) nodeOrder.right = rebalanced; } _node = parent; } else { if (_node != rebalanced) rootOrder = rebalanced; break; } } } /** * Rebalance given tree node if necessary. * * @param _node tree node to rebalance * @return rebalanced tree node */ function rebalance (address _node) private returns (address rebalanced) { if (_node == 0) throw; Order storage nodeOrder = orders [_node]; address left = nodeOrder.left; address right = nodeOrder.right; if (left == 0) { if (right == 0) return _node; else { Order storage rightOrder1 = orders [right]; uint256 rightHeight1 = rightOrder1.height; if (rightHeight1 > 1) return chooseRotate ( true, _node, nodeOrder, right, rightOrder1, 0); else return _node; } } else { Order storage leftOrder = orders [left]; uint256 leftHeight = leftOrder.height; if (right == 0) { if (leftHeight > 1) return chooseRotate ( false, _node, nodeOrder, left, leftOrder, 0); else return _node; } else { Order storage rightOrder2 = orders [right]; uint256 rightHeight2 = rightOrder2.height; if (safeAdd (leftHeight, 1) < rightHeight2) return chooseRotate ( true, _node, nodeOrder, right, rightOrder2, leftHeight); else if (leftHeight > safeAdd (rightHeight2, 1)) return chooseRotate ( false, _node, nodeOrder, left, leftOrder, rightHeight2); else return _node; } } } /** * Choose appropriate rotation type, either ordinary or big rotation. * * Left * * A * / \ * 1 B * * Right * * A * / \ * B 1 * * @param _left true to choose left rotation type, false to choose right * rotation type * @param _a node A * @param _orderA order A * @param _b node B * @param _orderB order B * @param _height1 height of subtree 1 * @return rotated node */ function chooseRotate ( bool _left, address _a, Order storage _orderA, address _b, Order storage _orderB, uint256 _height1) private returns (address rotated) { address c = _left ? _orderB.left : _orderB.right; if (c == 0) { rotate ( _left, _a, _orderA, _b, _orderB, 0, _orderA, // Order C parameter is not used anyway _height1); return _b; } else { Order storage orderC = orders [c]; if (_height1 < orderC.height) { bigRotate ( _left, _a, _orderA, _b, _orderB, c, orderC, _height1); return c; } else { rotate ( _left, _a, _orderA, _b, _orderB, c, orderC, _height1); return _b; } } } /** * Rotate tree either left or right: * * Left * A B * / \ / \ * 1 B ==> A 2 * / \ / \ * C 2 1 C * * Right * A B * / \ / \ * B 1 ==> 2 A * / \ / \ * 2 C C 1 * * @param _left true to rotate left, false to rotate right * @param _a node A * @param _orderA order A * @param _b node B * @param _orderB order B * @param _c node C (may be zero) * @param _orderC order C (undefined is _c is zero) * @param _height1 height of subtree 1 */ function rotate ( bool _left, address _a, Order storage _orderA, address _b, Order storage _orderB, address _c, Order storage _orderC, uint256 _height1) private { // Adjust parents _orderB.parent = _orderA.parent; _orderA.parent = _b; if (_c != 0) _orderC.parent = _a; // Adjust links if (_left) { _orderA.right = _c; _orderB.left = _a; } else { _orderA.left = _c; _orderB.right = _a; } // Adjust aggregates uint256 _totalRemainingAmountA = _orderA.totalRemainingAmount; uint256 _totalRemainingValueA = _orderA.totalRemainingValue; _orderA.totalRemainingAmount = safeAdd ( safeSub (_totalRemainingAmountA, _orderB.totalRemainingAmount), _c == 0 ? 0 : _orderC.totalRemainingAmount); _orderA.totalRemainingValue = safeAdd ( safeSub (_totalRemainingValueA, _orderB.totalRemainingValue), _c == 0 ? 0 : _orderC.totalRemainingValue); _orderB.totalRemainingAmount = _totalRemainingAmountA; _orderB.totalRemainingValue = _totalRemainingValueA; // Adjust heights _orderA.height = safeAdd (_height1, 1); } /** * Perform big tree rotation either left or right. * * Left * A * / \ C * 1 B / \ * / \ ==> A B * C 4 / \ / \ * / \ 1 2 3 4 * 2 3 * * Right * A * / \ C * B 1 / \ * / \ ==> B A * 4 C / \ / \ * / \ 4 3 2 1 * 3 2 * * @param _left true to rotate left, false to rotate right * @param _a node A * @param _orderA order A * @param _b node B * @param _orderB order B * @param _c node C * @param _orderC order C * @param _height1 height of subtree 1 */ function bigRotate ( bool _left, address _a, Order storage _orderA, address _b, Order storage _orderB, address _c, Order storage _orderC, uint256 _height1) private { address subtree2 = _left ? _orderC.left : _orderC.right; Order storage subtree2Order; if (subtree2 != 0) subtree2Order = orders [subtree2]; address subtree3 = _left ? _orderC.right : _orderC.left; Order storage subtree3Order; if (subtree3 != 0) subtree3Order = orders [subtree3]; address subtree4 = _left ? _orderB.right: _orderB.left; // Adjust parents _orderC.parent = _orderA.parent; _orderA.parent = _c; _orderB.parent = _c; if (subtree2 != 0) subtree2Order.parent = _a; if (subtree3 != 0) subtree3Order.parent = _b; // Adjust links if (_left) { _orderC.left = _a; _orderC.right = _b; _orderA.right = subtree2; _orderB.left = subtree3; } else { _orderC.right = _a; _orderC.left = _b; _orderA.left = subtree2; _orderB.right = subtree3; } adjustAggregates ( _orderA, _orderB, _orderC, subtree2 == 0 ? 0 : subtree2Order.totalRemainingAmount, subtree2 == 0 ? 0 : subtree2Order.totalRemainingValue, subtree3 == 0 ? 0 : subtree3Order.totalRemainingAmount, subtree3 == 0 ? 0 : subtree3Order.totalRemainingValue); adjustHeights ( _orderA, _orderB, _orderC, _height1, subtree2 == 0 ? 0 : subtree2Order.height, subtree3 == 0 ? 0 : subtree3Order.height, subtree4 == 0 ? 0 : orders [subtree4].height); } /** * Adjust aggregates for orders A, B and C.after big rotation. * * A * / \ C * 1 B / \ * / \ ==> A B * C 4 / \ / \ * / \ 1 2 3 4 * 2 3 * * or * * A * / \ C * B 1 / \ * / \ ==> B A * 4 C / \ / \ * / \ 4 3 2 1 * 3 2 * * @param _orderA order A * @param _orderB order B * @param _orderC order C * @param _totalRemainingAmount2 total remaining amount of subtree 2 * @param _totalRemainingValue2 total remaining value of subtree 2 * @param _totalRemainingAmount3 total remaining amount of subtree 3 * @param _totalRemainingValue3 total remaining value of subtree 3 */ function adjustAggregates ( Order storage _orderA, Order storage _orderB, Order storage _orderC, uint256 _totalRemainingAmount2, uint256 _totalRemainingValue2, uint256 _totalRemainingAmount3, uint256 _totalRemainingValue3) private { uint256 _totalRemainingAmountA = _orderA.totalRemainingAmount; uint256 _totalRemainingValueA = _orderA.totalRemainingValue; _orderA.totalRemainingAmount = safeAdd ( safeSub (_orderA.totalRemainingAmount, _orderB.totalRemainingAmount), _totalRemainingAmount2); _orderA.totalRemainingValue = safeAdd ( safeSub (_orderA.totalRemainingValue, _orderB.totalRemainingValue), _totalRemainingValue2); _orderB.totalRemainingAmount = safeAdd ( safeSub (_orderB.totalRemainingAmount, _orderC.totalRemainingAmount), _totalRemainingAmount3); _orderB.totalRemainingValue = safeAdd ( safeSub (_orderB.totalRemainingValue, _orderC.totalRemainingValue), _totalRemainingValue3); _orderC.totalRemainingAmount = _totalRemainingAmountA; _orderC.totalRemainingValue = _totalRemainingValueA; } /** * Adjust heights or orders A, B and C after big rotation. * * C C * / \ or / \ * A B B A * / \ / \ / \ / \ * 1 2 3 4 4 3 2 1 * * @param _orderA order A to adjust height of * @param _orderB order B to adjust height of * @param _orderC order C to adjust height of * @param _height1 height of subtree 1 * @param _height2 height of subtree 2 * @param _height3 height of subtree 3 * @param _height4 height of subtree 4 */ function adjustHeights ( Order storage _orderA, Order storage _orderB, Order storage _orderC, uint256 _height1, uint256 _height2, uint256 _height3, uint256 _height4) private { _orderC.height = safeAdd ( max ( (_orderA.height = safeAdd (max (_height1, _height2), 1)), (_orderB.height = safeAdd (max (_height3, _height4), 1))), 1); } /** * Calculate maximum of two values. * * @param _x first value * @param _y second value * @return maximum of two values */ function max (uint256 _x, uint256 _y) private constant returns (uint256 result) { return _x > _y ? _x : _y; } /** * Get height of tree node. * * @param _node tree node to get height of * @return height of the given tree node * */ function getHeight (address _node) private constant returns (uint256 height) { return _node == 0 ? 0 : orders [_node].height; } /** * Reference to a root order or zero is there are no orders. */ address rootOrder; /** * Mapping from address of order creator to current order from this creator. */ mapping (address => Order) orders; /** * Amount of assets sold so far. */ uint256 soldAmount; /** * Pending refund (in Wei) for inactive orders. */ uint256 pendingRefund = 0; /** * Encapsulates information about buy-side order. */ struct Order { /** * Amount of assets to buy. */ uint256 amount; /** * Price per asset unit (in Wei). */ uint256 price; /** * Amount of assets already bought. */ uint256 filledAmount; /** * Reference to parent order. */ address parent; /** * Reference to left subtree. */ address left; /** * Reference to right subtree. */ address right; /** * Total remaining amount in a subtree whose root is this order. */ uint256 totalRemainingAmount; /** * Total remaining value in a subtree whose root is this order. */ uint256 totalRemainingValue; /** * Height of the subtree whose root is this order. */ uint256 height; } /** * Logged when new order was placed. * * @param creator address of the creator of the new order * @param amount amount of the new order * @param price price of the new order */ event OrderPlacement ( address indexed creator, uint256 amount, uint256 price); /** * Logged when order was terminated. * * @param creator address of the creator of terminated order * @param filledAmount filled amount of the order */ event OrderTermination ( address indexed creator, uint256 filledAmount); }
* Choose appropriate rotation type, either ordinary or big rotation. Left A / \ 1 B Right A / \ B 1 @param _left true to choose left rotation type, false to choose right rotation type @param _a node A @param _orderA order A @param _b node B @param _orderB order B @param _height1 height of subtree 1 @return rotated node/
uint256 _height1) private returns (address rotated) { address c = _left ? _orderB.left : _orderB.right; function chooseRotate ( bool _left, address _a, Order storage _orderA, address _b, Order storage _orderB, if (c == 0) { rotate ( _left, _a, _orderA, _b, _orderB, _height1); return _b; Order storage orderC = orders [c]; if (_height1 < orderC.height) { bigRotate ( _left, _a, _orderA, _b, _orderB, c, orderC, _height1); return c; rotate ( _left, _a, _orderA, _b, _orderB, c, orderC, _height1); return _b; } } } else { function chooseRotate ( bool _left, address _a, Order storage _orderA, address _b, Order storage _orderB, if (c == 0) { rotate ( _left, _a, _orderA, _b, _orderB, _height1); return _b; Order storage orderC = orders [c]; if (_height1 < orderC.height) { bigRotate ( _left, _a, _orderA, _b, _orderB, c, orderC, _height1); return c; rotate ( _left, _a, _orderA, _b, _orderB, c, orderC, _height1); return _b; } } } else { }
6,437,851
[ 1, 24529, 5505, 6752, 618, 16, 3344, 4642, 2101, 578, 5446, 6752, 18, 13338, 282, 432, 225, 342, 521, 404, 282, 605, 13009, 282, 432, 225, 342, 521, 605, 282, 404, 225, 389, 4482, 638, 358, 9876, 2002, 6752, 618, 16, 629, 358, 9876, 2145, 3639, 6752, 618, 225, 389, 69, 756, 432, 225, 389, 1019, 37, 1353, 432, 225, 389, 70, 756, 605, 225, 389, 1019, 38, 1353, 605, 225, 389, 4210, 21, 2072, 434, 12773, 404, 327, 22864, 756, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 389, 4210, 21, 13, 3238, 1135, 261, 2867, 22864, 13, 288, 203, 565, 1758, 276, 273, 389, 4482, 692, 389, 1019, 38, 18, 4482, 294, 389, 1019, 38, 18, 4083, 31, 203, 225, 445, 9876, 16357, 261, 203, 565, 1426, 389, 4482, 16, 203, 565, 1758, 389, 69, 16, 4347, 2502, 389, 1019, 37, 16, 203, 565, 1758, 389, 70, 16, 4347, 2502, 389, 1019, 38, 16, 203, 565, 309, 261, 71, 422, 374, 13, 288, 203, 1377, 8534, 261, 203, 3639, 389, 4482, 16, 203, 3639, 389, 69, 16, 389, 1019, 37, 16, 203, 3639, 389, 70, 16, 389, 1019, 38, 16, 203, 3639, 389, 4210, 21, 1769, 203, 203, 1377, 327, 389, 70, 31, 203, 1377, 4347, 2502, 1353, 39, 273, 11077, 306, 71, 15533, 203, 1377, 309, 261, 67, 4210, 21, 411, 1353, 39, 18, 4210, 13, 288, 203, 3639, 5446, 16357, 261, 203, 1850, 389, 4482, 16, 203, 1850, 389, 69, 16, 389, 1019, 37, 16, 203, 1850, 389, 70, 16, 389, 1019, 38, 16, 203, 1850, 276, 16, 1353, 39, 16, 203, 1850, 389, 4210, 21, 1769, 203, 21281, 3639, 327, 276, 31, 203, 3639, 8534, 261, 203, 1850, 389, 4482, 16, 203, 1850, 389, 69, 16, 389, 1019, 37, 16, 203, 1850, 389, 70, 16, 389, 1019, 38, 16, 203, 1850, 276, 16, 1353, 39, 16, 203, 1850, 389, 4210, 21, 1769, 203, 203, 3639, 327, 389, 70, 31, 203, 1377, 289, 203, 565, 289, 203, 565, 289, 469, 288, 203, 225, 445, 9876, 16357, 2 ]
./partial_match/1/0x695264D984A5E45C2d89f261C8668d6C1F7D214c/sources/IporProtocolRouter.sol
@title Interface of the CloseSwap Lens.
interface IAmmCloseSwapLens { struct AmmCloseSwapServicePoolConfiguration { address asset; uint256 decimals; address ammStorage; address ammTreasury; address assetManagement; uint256 unwindingFeeRate; uint256 unwindingFeeTreasuryPortionRate; uint256 maxLengthOfLiquidatedSwapsPerLeg; uint256 timeBeforeMaturityAllowedToCloseSwapByCommunity; uint256 timeBeforeMaturityAllowedToCloseSwapByBuyer; uint256 minLiquidationThresholdToCloseBeforeMaturityByCommunity; uint256 minLiquidationThresholdToCloseBeforeMaturityByBuyer; uint256 minLeverage; } }
16,153,492
[ 1, 1358, 434, 326, 3527, 12521, 511, 773, 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, 5831, 467, 37, 7020, 4605, 12521, 48, 773, 288, 203, 203, 565, 1958, 3986, 81, 4605, 12521, 1179, 2864, 1750, 288, 203, 3639, 1758, 3310, 31, 203, 3639, 2254, 5034, 15105, 31, 203, 3639, 1758, 2125, 81, 3245, 31, 203, 3639, 1758, 2125, 81, 56, 266, 345, 22498, 31, 203, 3639, 1758, 3310, 10998, 31, 203, 3639, 2254, 5034, 640, 10094, 310, 14667, 4727, 31, 203, 3639, 2254, 5034, 640, 10094, 310, 14667, 56, 266, 345, 22498, 2617, 285, 4727, 31, 203, 3639, 2254, 5034, 13642, 951, 48, 18988, 350, 690, 6050, 6679, 2173, 8329, 31, 203, 3639, 2254, 5034, 813, 4649, 15947, 2336, 5042, 774, 4605, 12521, 858, 12136, 13352, 31, 203, 3639, 2254, 5034, 813, 4649, 15947, 2336, 5042, 774, 4605, 12521, 858, 38, 16213, 31, 203, 3639, 2254, 5034, 1131, 48, 18988, 350, 367, 7614, 774, 4605, 4649, 15947, 2336, 858, 12136, 13352, 31, 203, 3639, 2254, 5034, 1131, 48, 18988, 350, 367, 7614, 774, 4605, 4649, 15947, 2336, 858, 38, 16213, 31, 203, 3639, 2254, 5034, 1131, 1682, 5682, 31, 203, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.10; pragma experimental ABIEncoderV2; import 'ROOT/external/IExchange.sol'; import 'ROOT/libraries/ReentrancyGuard.sol'; import 'ROOT/external/IWallet.sol'; import 'ROOT/libraries/math/SafeMathUint256.sol'; import 'ROOT/libraries/token/IERC1155.sol'; contract ZeroXExchange is IExchange, ReentrancyGuard { using SafeMathUint256 for uint256; // EIP191 header for EIP712 prefix string constant internal EIP191_HEADER = "\x19\x01"; // EIP712 Domain Name value string constant internal EIP712_DOMAIN_NAME = "0x Protocol"; // EIP712 Domain Version value string constant internal EIP712_DOMAIN_VERSION = "2"; // Hash of the EIP712 Domain Separator Schema bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256( abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); bytes32 constant internal EIP712_ORDER_SCHEMA_HASH = keccak256( abi.encodePacked( "Order(", "address makerAddress,", "address takerAddress,", "address feeRecipientAddress,", "address senderAddress,", "uint256 makerAssetAmount,", "uint256 takerAssetAmount,", "uint256 makerFee,", "uint256 takerFee,", "uint256 expirationTimeSeconds,", "uint256 salt,", "bytes makerAssetData,", "bytes takerAssetData", ")" )); bytes32 constant internal EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0x213c6f636f3ea94e701c0adf9b2624aa45a6c694f9a292c094f9a81c24b5df4c; // Hash of the EIP712 Domain Separator data // solhint-disable-next-line var-name-mixedcase bytes32 public EIP712_DOMAIN_HASH; // ERC1155Assets(address,uint256[],uint256[],bytes) bytes4 constant public ERC1155_PROXY_ID = 0xa7cb5fb7; mapping (bytes32 => bool) public transactions; address public currentContextAddress; enum SignatureType { Illegal, // 0x00, default value Invalid, // 0x01 EIP712, // 0x02 EthSign, // 0x03 Wallet, // 0x04 Validator, // 0x05 PreSigned, // 0x06 NSignatureTypes // 0x07, number of signature types. Always leave at end. } // A valid order remains fillable until it is expired, fully filled, or cancelled. // An order's state is unaffected by external factors, like account balances. enum OrderStatus { INVALID, // Default value INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount FILLABLE, // Order is fillable EXPIRED, // Order has already expired FULLY_FILLED, // Order is fully filled CANCELLED // Order has been cancelled } // Mapping of orderHash => amount of takerAsset already bought by maker mapping (bytes32 => uint256) public filled; // Mapping of orderHash => cancelled mapping (bytes32 => bool) public cancelled; mapping (bytes32 => mapping (address => bool)) public preSigned; // Mapping of makerAddress => senderAddress => lowest salt an order can have in order to be fillable // Orders with specified senderAddress and with a salt less than their epoch are considered cancelled mapping (address => mapping (address => uint256)) public orderEpoch; constructor () public { EIP712_DOMAIN_HASH = keccak256( abi.encodePacked( EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(EIP712_DOMAIN_NAME)), keccak256(bytes(EIP712_DOMAIN_VERSION)), uint256(address(this)) )); } /// @dev Adds properties of both FillResults instances. /// Modifies the first FillResults instance specified. /// @param totalFillResults Fill results instance that will be added onto. /// @param singleFillResults Fill results instance that will be added to totalFillResults. function addFillResults(FillResults memory totalFillResults, FillResults memory singleFillResults) internal pure { totalFillResults.makerAssetFilledAmount = totalFillResults.makerAssetFilledAmount.add(singleFillResults.makerAssetFilledAmount); totalFillResults.takerAssetFilledAmount = totalFillResults.takerAssetFilledAmount.add(singleFillResults.takerAssetFilledAmount); totalFillResults.makerFeePaid = totalFillResults.makerFeePaid.add(singleFillResults.makerFeePaid); totalFillResults.takerFeePaid = totalFillResults.takerFeePaid.add(singleFillResults.takerFeePaid); } /// @dev Fills the input order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrderNoThrow( Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (FillResults memory fillResults) { // ABI encode calldata for `fillOrder` bytes memory fillOrderCalldata = abiEncodeFillOrder( order, takerAssetFillAmount, signature ); uint256 requiredFee = tx.gasprice * 150000; require(msg.value >= requiredFee, "PROTOCOL FEE NOT SENT"); // Delegate to `fillOrder` and handle any exceptions gracefully assembly { let success := delegatecall( gas, // forward all gas address, // call address of this contract add(fillOrderCalldata, 32), // pointer to start of input (skip array length in first 32 bytes) mload(fillOrderCalldata), // length of input fillOrderCalldata, // write output over input 128 // output size is 128 bytes ) if success { mstore(fillResults, mload(fillOrderCalldata)) mstore(add(fillResults, 32), mload(add(fillOrderCalldata, 32))) mstore(add(fillResults, 64), mload(add(fillOrderCalldata, 64))) mstore(add(fillResults, 96), mload(add(fillOrderCalldata, 96))) } } // fillResults values will be 0 by default if call was unsuccessful return fillResults; } /// @dev ABI encodes calldata for `fillOrder`. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return ABI encoded calldata for `fillOrder`. function abiEncodeFillOrder( Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal pure returns (bytes memory fillOrderCalldata) { // We need to call MExchangeCore.fillOrder using a delegatecall in // assembly so that we can intercept a call that throws. For this, we // need the input encoded in memory in the Ethereum ABIv2 format [1]. // | Area | Offset | Length | Contents | // | -------- |--------|---------|-------------------------------------------- | // | Header | 0x00 | 4 | function selector | // | Params | | 3 * 32 | function parameters: | // | | 0x00 | | 1. offset to order (*) | // | | 0x20 | | 2. takerAssetFillAmount | // | | 0x40 | | 3. offset to signature (*) | // | Data | | 12 * 32 | order: | // | | 0x000 | | 1. senderAddress | // | | 0x020 | | 2. makerAddress | // | | 0x040 | | 3. takerAddress | // | | 0x060 | | 4. feeRecipientAddress | // | | 0x080 | | 5. makerAssetAmount | // | | 0x0A0 | | 6. takerAssetAmount | // | | 0x0C0 | | 7. makerFeeAmount | // | | 0x0E0 | | 8. takerFeeAmount | // | | 0x100 | | 9. expirationTimeSeconds | // | | 0x120 | | 10. salt | // | | 0x140 | | 11. Offset to makerAssetData (*) | // | | 0x160 | | 12. Offset to takerAssetData (*) | // | | 0x180 | 32 | makerAssetData Length | // | | 0x1A0 | ** | makerAssetData Contents | // | | 0x1C0 | 32 | takerAssetData Length | // | | 0x1E0 | ** | takerAssetData Contents | // | | 0x200 | 32 | signature Length | // | | 0x220 | ** | signature Contents | // * Offsets are calculated from the beginning of the current area: Header, Params, Data: // An offset stored in the Params area is calculated from the beginning of the Params section. // An offset stored in the Data area is calculated from the beginning of the Data section. // ** The length of dynamic array contents are stored in the field immediately preceeding the contents. // [1]: https://solidity.readthedocs.io/en/develop/abi-spec.html assembly { // Areas below may use the following variables: // 1. <area>Start -- Start of this area in memory // 2. <area>End -- End of this area in memory. This value may // be precomputed (before writing contents), // or it may be computed as contents are written. // 3. <area>Offset -- Current offset into area. If an area's End // is precomputed, this variable tracks the // offsets of contents as they are written. /////// Setup Header Area /////// // Load free memory pointer fillOrderCalldata := mload(0x40) // bytes4(keccak256("fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)")) // = 0xb4be83d5 // Leave 0x20 bytes to store the length mstore(add(fillOrderCalldata, 0x20), 0xb4be83d500000000000000000000000000000000000000000000000000000000) let headerAreaEnd := add(fillOrderCalldata, 0x24) /////// Setup Params Area /////// // This area is preallocated and written to later. // This is because we need to fill in offsets that have not yet been calculated. let paramsAreaStart := headerAreaEnd let paramsAreaEnd := add(paramsAreaStart, 0x60) let paramsAreaOffset := paramsAreaStart /////// Setup Data Area /////// let dataAreaStart := paramsAreaEnd let dataAreaEnd := dataAreaStart // Offset from the source data we're reading from let sourceOffset := order // arrayLenBytes and arrayLenWords track the length of a dynamically-allocated bytes array. let arrayLenBytes := 0 let arrayLenWords := 0 /////// Write order Struct /////// // Write memory location of Order, relative to the start of the // parameter list, then increment the paramsAreaOffset respectively. mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart)) paramsAreaOffset := add(paramsAreaOffset, 0x20) // Write values for each field in the order // It would be nice to use a loop, but we save on gas by writing // the stores sequentially. mstore(dataAreaEnd, mload(sourceOffset)) // makerAddress mstore(add(dataAreaEnd, 0x20), mload(add(sourceOffset, 0x20))) // takerAddress mstore(add(dataAreaEnd, 0x40), mload(add(sourceOffset, 0x40))) // feeRecipientAddress mstore(add(dataAreaEnd, 0x60), mload(add(sourceOffset, 0x60))) // senderAddress mstore(add(dataAreaEnd, 0x80), mload(add(sourceOffset, 0x80))) // makerAssetAmount mstore(add(dataAreaEnd, 0xA0), mload(add(sourceOffset, 0xA0))) // takerAssetAmount mstore(add(dataAreaEnd, 0xC0), mload(add(sourceOffset, 0xC0))) // makerFeeAmount mstore(add(dataAreaEnd, 0xE0), mload(add(sourceOffset, 0xE0))) // takerFeeAmount mstore(add(dataAreaEnd, 0x100), mload(add(sourceOffset, 0x100))) // expirationTimeSeconds mstore(add(dataAreaEnd, 0x120), mload(add(sourceOffset, 0x120))) // salt mstore(add(dataAreaEnd, 0x140), mload(add(sourceOffset, 0x140))) // Offset to makerAssetData mstore(add(dataAreaEnd, 0x160), mload(add(sourceOffset, 0x160))) // Offset to takerAssetData dataAreaEnd := add(dataAreaEnd, 0x180) sourceOffset := add(sourceOffset, 0x180) // Write offset to <order.makerAssetData> mstore(add(dataAreaStart, mul(10, 0x20)), sub(dataAreaEnd, dataAreaStart)) // Calculate length of <order.makerAssetData> sourceOffset := mload(add(order, 0x140)) // makerAssetData arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20) // Write length of <order.makerAssetData> mstore(dataAreaEnd, arrayLenBytes) dataAreaEnd := add(dataAreaEnd, 0x20) // Write contents of <order.makerAssetData> for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} { mstore(dataAreaEnd, mload(sourceOffset)) dataAreaEnd := add(dataAreaEnd, 0x20) sourceOffset := add(sourceOffset, 0x20) } // Write offset to <order.takerAssetData> mstore(add(dataAreaStart, mul(11, 0x20)), sub(dataAreaEnd, dataAreaStart)) // Calculate length of <order.takerAssetData> sourceOffset := mload(add(order, 0x160)) // takerAssetData arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20) // Write length of <order.takerAssetData> mstore(dataAreaEnd, arrayLenBytes) dataAreaEnd := add(dataAreaEnd, 0x20) // Write contents of <order.takerAssetData> for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} { mstore(dataAreaEnd, mload(sourceOffset)) dataAreaEnd := add(dataAreaEnd, 0x20) sourceOffset := add(sourceOffset, 0x20) } /////// Write takerAssetFillAmount /////// mstore(paramsAreaOffset, takerAssetFillAmount) paramsAreaOffset := add(paramsAreaOffset, 0x20) /////// Write signature /////// // Write offset to paramsArea mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart)) // Calculate length of signature sourceOffset := signature arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20) // Write length of signature mstore(dataAreaEnd, arrayLenBytes) dataAreaEnd := add(dataAreaEnd, 0x20) // Write contents of signature for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} { mstore(dataAreaEnd, mload(sourceOffset)) dataAreaEnd := add(dataAreaEnd, 0x20) sourceOffset := add(sourceOffset, 0x20) } // Set length of calldata mstore(fillOrderCalldata, sub(dataAreaEnd, add(fillOrderCalldata, 0x20))) // Increment free memory pointer mstore(0x40, dataAreaEnd) } return fillOrderCalldata; } /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable nonReentrant returns (FillResults memory fillResults) { uint256 requiredFee = tx.gasprice * 150000; require(msg.value >= requiredFee, "PROTOCOL FEE NOT SENT"); fillResults = fillOrderInternal( order, takerAssetFillAmount, signature ); return fillResults; } /// @dev Executes an exchange method call in the context of signer. /// @param salt Arbitrary number to ensure uniqueness of transaction hash. /// @param signerAddress Address of transaction signer. /// @param data AbiV2 encoded calldata. /// @param signature Proof of signer transaction by signer. function executeTransaction( uint256 salt, address signerAddress, bytes memory data, bytes memory signature ) internal { // Prevent reentrancy require( currentContextAddress == address(0), "REENTRANCY_ILLEGAL" ); bytes32 hashedTransaction = hashZeroExTransaction(salt, signerAddress, data); bytes32 transactionHash = hashEIP712Message(hashedTransaction); // Validate transaction has not been executed require(!transactions[transactionHash], "INVALID_TX_HASH"); // Transaction always valid if signer is sender of transaction if (signerAddress != msg.sender) { // Validate signature require( isValidSignature( transactionHash, signerAddress, signature ), "INVALID_TX_SIGNATURE" ); // Set the current transaction signer currentContextAddress = signerAddress; } // Execute transaction transactions[transactionHash] = true; (bool success,) = address(this).delegatecall(data); require( success, "FAILED_EXECUTION" ); // Reset current transaction signer if it was previously updated if (signerAddress != msg.sender) { currentContextAddress = address(0); } } /// @dev Updates state with results of a fill order. /// @param orderTakerAssetFilledAmount Amount of order already filled. function updateFilledState( Order memory, address, bytes32 orderHash, uint256 orderTakerAssetFilledAmount, FillResults memory fillResults ) internal { // Update state filled[orderHash] = orderTakerAssetFilledAmount.add(fillResults.takerAssetFilledAmount); } /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrderInternal( Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (FillResults memory fillResults) { // Fetch order info OrderInfo memory orderInfo = getOrderInfo(order); // Fetch taker address address takerAddress = getCurrentContextAddress(); // Assert that the order is fillable by taker assertFillableOrder( order, orderInfo, takerAddress, signature ); // Get amount of takerAsset to fill uint256 remainingTakerAssetAmount = order.takerAssetAmount.sub(orderInfo.orderTakerAssetFilledAmount); uint256 takerAssetFilledAmount = takerAssetFillAmount.min(remainingTakerAssetAmount); // Validate context assertValidFill( order, orderInfo, takerAssetFillAmount, takerAssetFilledAmount, fillResults.makerAssetFilledAmount ); // Compute proportional fill amounts fillResults = calculateFillResults(order, takerAssetFilledAmount); // Update exchange internal state updateFilledState( order, takerAddress, orderInfo.orderHash, orderInfo.orderTakerAssetFilledAmount, fillResults ); // Settle order settleOrder( order, takerAddress, fillResults ); return fillResults; } /// @dev Validates context for fillOrder. Succeeds or throws. /// @param order to be filled. /// @param orderInfo OrderStatus, orderHash, and amount already filled of order. /// @param takerAssetFillAmount Desired amount of order to fill by taker. /// @param takerAssetFilledAmount Amount of takerAsset that will be filled. /// @param makerAssetFilledAmount Amount of makerAsset that will be transfered. function assertValidFill( Order memory order, OrderInfo memory orderInfo, uint256 takerAssetFillAmount, // TODO: use FillResults uint256 takerAssetFilledAmount, uint256 makerAssetFilledAmount ) internal pure { // Revert if fill amount is invalid // TODO: reconsider necessity for v2.1 require( takerAssetFillAmount != 0, "INVALID_TAKER_AMOUNT" ); // Make sure taker does not pay more than desired amount // NOTE: This assertion should never fail, it is here // as an extra defence against potential bugs. require( takerAssetFilledAmount <= takerAssetFillAmount, "TAKER_OVERPAY" ); // Make sure order is not overfilled // NOTE: This assertion should never fail, it is here // as an extra defence against potential bugs. require( orderInfo.orderTakerAssetFilledAmount.add(takerAssetFilledAmount) <= order.takerAssetAmount, "ORDER_OVERFILL" ); // Make sure order is filled at acceptable price. // The order has an implied price from the makers perspective: // order price = order.makerAssetAmount / order.takerAssetAmount // i.e. the number of makerAsset maker is paying per takerAsset. The // maker is guaranteed to get this price or a better (lower) one. The // actual price maker is getting in this fill is: // fill price = makerAssetFilledAmount / takerAssetFilledAmount // We need `fill price <= order price` for the fill to be fair to maker. // This amounts to: // makerAssetFilledAmount order.makerAssetAmount // ------------------------ <= ----------------------- // takerAssetFilledAmount order.takerAssetAmount // or, equivalently: // makerAssetFilledAmount * order.takerAssetAmount <= // order.makerAssetAmount * takerAssetFilledAmount // NOTE: This assertion should never fail, it is here // as an extra defence against potential bugs. require( makerAssetFilledAmount.mul(order.takerAssetAmount) <= order.makerAssetAmount.mul(takerAssetFilledAmount), "INVALID_FILL_PRICE" ); } /// @dev Calculates amounts filled and fees paid by maker and taker. /// @param order to be filled. /// @param takerAssetFilledAmount Amount of takerAsset that will be filled. /// @return fillResults Amounts filled and fees paid by maker and taker. function calculateFillResults( Order memory order, uint256 takerAssetFilledAmount ) internal pure returns (FillResults memory fillResults) { // Compute proportional transfer amounts fillResults.takerAssetFilledAmount = takerAssetFilledAmount; fillResults.makerAssetFilledAmount = safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerAssetAmount ); fillResults.makerFeePaid = safeGetPartialAmountFloor( fillResults.makerAssetFilledAmount, order.makerAssetAmount, order.makerFee ); fillResults.takerFeePaid = safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.takerFee ); return fillResults; } /// @dev Settles an order by transferring assets between counterparties. /// @param order Order struct containing order specifications. /// @param takerAddress Address selling takerAsset and buying makerAsset. /// @param fillResults Amounts to be filled and fees paid by maker and taker. function settleOrder( Order memory order, address takerAddress, FillResults memory fillResults ) private { dispatchTransferFrom( order.makerAssetData, order.makerAddress, takerAddress, fillResults.makerAssetFilledAmount ); dispatchTransferFrom( order.takerAssetData, takerAddress, order.makerAddress, fillResults.takerAssetFilledAmount ); } /// @dev Calculates EIP712 hash of the Transaction. /// @param salt Arbitrary number to ensure uniqueness of transaction hash. /// @param signerAddress Address of transaction signer. /// @param data AbiV2 encoded calldata. /// @return EIP712 hash of the Transaction. function hashZeroExTransaction( uint256 salt, address signerAddress, bytes memory data ) internal pure returns (bytes32 result) { bytes32 schemaHash = EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH; bytes32 dataHash = keccak256(data); // Assembly for more efficiently computing: // keccak256(abi.encodePacked( // EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH, // salt, // bytes32(signerAddress), // keccak256(data) // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, schemaHash) // hash of schema mstore(add(memPtr, 32), salt) // salt mstore(add(memPtr, 64), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress mstore(add(memPtr, 96), dataHash) // hash of data // Compute hash result := keccak256(memPtr, 128) } return result; } /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(Order memory order) public view returns (OrderInfo memory orderInfo) { // Compute the order hash orderInfo.orderHash = getOrderHash(order); // Fetch filled amount orderInfo.orderTakerAssetFilledAmount = filled[orderInfo.orderHash]; // If order.makerAssetAmount is zero, we also reject the order. // While the Exchange contract handles them correctly, they create // edge cases in the supporting infrastructure because they have // an 'infinite' price when computed by a simple division. if (order.makerAssetAmount == 0) { orderInfo.orderStatus = uint8(OrderStatus.INVALID_MAKER_ASSET_AMOUNT); return orderInfo; } // If order.takerAssetAmount is zero, then the order will always // be considered filled because 0 == takerAssetAmount == orderTakerAssetFilledAmount // Instead of distinguishing between unfilled and filled zero taker // amount orders, we choose not to support them. if (order.takerAssetAmount == 0) { orderInfo.orderStatus = uint8(OrderStatus.INVALID_TAKER_ASSET_AMOUNT); return orderInfo; } // Validate order availability if (orderInfo.orderTakerAssetFilledAmount >= order.takerAssetAmount) { orderInfo.orderStatus = uint8(OrderStatus.FULLY_FILLED); return orderInfo; } // Validate order expiration // solhint-disable-next-line not-rely-on-time if (block.timestamp >= order.expirationTimeSeconds) { orderInfo.orderStatus = uint8(OrderStatus.EXPIRED); return orderInfo; } // Check if order has been cancelled if (cancelled[orderInfo.orderHash]) { orderInfo.orderStatus = uint8(OrderStatus.CANCELLED); return orderInfo; } if (orderEpoch[order.makerAddress][order.senderAddress] > order.salt) { orderInfo.orderStatus = uint8(OrderStatus.CANCELLED); return orderInfo; } // All other statuses are ruled out: order is Fillable orderInfo.orderStatus = uint8(OrderStatus.FILLABLE); return orderInfo; } /// @dev Calculates Keccak-256 hash of the order. /// @param order The order structure. /// @return Keccak-256 EIP712 hash of the order. function getOrderHash(Order memory order) internal view returns (bytes32 orderHash) { orderHash = hashEIP712Message(hashOrder(order)); return orderHash; } /// @dev Calculates EIP712 hash of the order. /// @param order The order structure. /// @return EIP712 hash of the order. function hashOrder(Order memory order) internal pure returns (bytes32 result) { bytes32 schemaHash = EIP712_ORDER_SCHEMA_HASH; bytes32 makerAssetDataHash = keccak256(order.makerAssetData); bytes32 takerAssetDataHash = keccak256(order.takerAssetData); // Assembly for more efficiently computing: // keccak256(abi.encodePacked( // EIP712_ORDER_SCHEMA_HASH, // bytes32(order.makerAddress), // bytes32(order.takerAddress), // bytes32(order.feeRecipientAddress), // bytes32(order.senderAddress), // order.makerAssetAmount, // order.takerAssetAmount, // order.makerFee, // order.takerFee, // order.expirationTimeSeconds, // order.salt, // keccak256(order.makerAssetData), // keccak256(order.takerAssetData) // )); assembly { // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(order, 32) let pos2 := add(order, 320) let pos3 := add(order, 352) // Backup let temp1 := mload(pos1) let temp2 := mload(pos2) let temp3 := mload(pos3) // Hash in place mstore(pos1, schemaHash) mstore(pos2, makerAssetDataHash) mstore(pos3, takerAssetDataHash) result := keccak256(pos1, 416) // Restore mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3) } return result; } /// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain. /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to this EIP712 Domain. function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { bytes32 eip712DomainHash = EIP712_DOMAIN_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } /// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`). /// If calling a fill function, this address will represent the taker. /// If calling a cancel function, this address will represent the maker. /// @return Signer of 0x transaction if entry point is `executeTransaction`. /// `msg.sender` if entry point is any other function. function getCurrentContextAddress() internal view returns (address) { address currentContextAddress_ = currentContextAddress; address contextAddress = currentContextAddress_ == address(0) ? msg.sender : currentContextAddress_; return contextAddress; } /// @dev Validates context for fillOrder. Succeeds or throws. /// @param order to be filled. /// @param orderInfo OrderStatus, orderHash, and amount already filled of order. /// @param takerAddress Address of order taker. /// @param signature Proof that the orders was created by its maker. function assertFillableOrder( Order memory order, OrderInfo memory orderInfo, address takerAddress, bytes memory signature ) internal view { // An order can only be filled if its status is FILLABLE. require( orderInfo.orderStatus == uint8(OrderStatus.FILLABLE), "ORDER_UNFILLABLE" ); // Validate sender is allowed to fill this order if (order.senderAddress != address(0)) { require( order.senderAddress == msg.sender, "INVALID_SENDER" ); } // Validate taker is allowed to fill this order if (order.takerAddress != address(0)) { require( order.takerAddress == takerAddress, "INVALID_TAKER" ); } // Validate Maker signature (check only if first time seen) if (orderInfo.orderTakerAssetFilledAmount == 0) { require( isValidSignature( orderInfo.orderHash, order.makerAddress, signature ), "INVALID_ORDER_SIGNATURE" ); } } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); require( !isRoundingErrorFloor( numerator, denominator, target ), "ROUNDING_ERROR" ); partialAmount = numerator.mul(target).div(denominator); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require( denominator > 0, "DIVISION_BY_ZERO" ); // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = remainder.mul(1000) >= numerator.mul(target); return isError; } /// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws. /// @param assetData Byte array encoded for the asset. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param amount Amount of token to transfer. function dispatchTransferFrom( bytes memory assetData, address from, address to, uint256 amount ) internal { // Do nothing if no amount should be transferred. if (amount > 0 && from != to) { // Ensure assetData length is valid require( assetData.length > 3, "LENGTH_GREATER_THAN_3_REQUIRED" ); address assetProxy = address(this); // We construct calldata for the `assetProxy.transferFrom` ABI. // The layout of this calldata is in the table below. // // | Area | Offset | Length | Contents | // | -------- |--------|---------|-------------------------------------------- | // | Header | 0 | 4 | function selector | // | Params | | 4 * 32 | function parameters: | // | | 4 | | 1. offset to assetData (*) | // | | 36 | | 2. from | // | | 68 | | 3. to | // | | 100 | | 4. amount | // | Data | | | assetData: | // | | 132 | 32 | assetData Length | // | | 164 | ** | assetData Contents | assembly { /////// Setup State /////// // `cdStart` is the start of the calldata for `assetProxy.transferFrom` (equal to free memory ptr). let cdStart := mload(64) // `dataAreaLength` is the total number of words needed to store `assetData` // As-per the ABI spec, this value is padded up to the nearest multiple of 32, // and includes 32-bytes for length. let dataAreaLength := and(add(mload(assetData), 63), 0xFFFFFFFFFFFE0) // `cdEnd` is the end of the calldata for `assetProxy.transferFrom`. let cdEnd := add(cdStart, add(132, dataAreaLength)) /////// Setup Header Area /////// // This area holds the 4-byte `transferFromSelector`. // bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4 mstore(cdStart, 0xa85e59e400000000000000000000000000000000000000000000000000000000) /////// Setup Params Area /////// // Each parameter is padded to 32-bytes. The entire Params Area is 128 bytes. // Notes: // 1. The offset to `assetData` is the length of the Params Area (128 bytes). // 2. A 20-byte mask is applied to addresses to zero-out the unused bytes. mstore(add(cdStart, 4), 128) mstore(add(cdStart, 36), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(cdStart, 68), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(cdStart, 100), amount) /////// Setup Data Area /////// // This area holds `assetData`. let dataArea := add(cdStart, 132) // solhint-disable-next-line no-empty-blocks for {} lt(dataArea, cdEnd) {} { mstore(dataArea, mload(assetData)) dataArea := add(dataArea, 32) assetData := add(assetData, 32) } /////// Call `assetProxy.transferFrom` using the constructed calldata /////// let success := call( gas, // forward all gas assetProxy, // call address of asset proxy 0, // don't send any ETH cdStart, // pointer to start of input sub(cdEnd, cdStart), // length of input cdStart, // write output over input 512 // reserve 512 bytes for output ) if iszero(success) { revert(cdStart, returndatasize()) } } } } /// @dev Verifies that a hash has been signed by the given signer. /// @param hash Any 32 byte hash. /// @param signerAddress Address that should have signed the given hash. /// @param signature Proof that the hash has been signed by signer. /// @return True if the address recovered from the provided signature matches the input signer address. function isValidSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid) { require( signature.length > 0, "LENGTH_GREATER_THAN_0_REQUIRED" ); // Pop last byte off of signature byte array. uint8 signatureTypeRaw = uint8(popLastByte(signature)); // Ensure signature is supported require( signatureTypeRaw < uint8(SignatureType.NSignatureTypes), "SIGNATURE_UNSUPPORTED" ); SignatureType signatureType = SignatureType(signatureTypeRaw); // Variables are not scoped in Solidity. uint8 v; bytes32 r; bytes32 s; address recovered; // Always illegal signature. // This is always an implicit option since a signer can create a // signature array with invalid type or length. We may as well make // it an explicit option. This aids testing and analysis. It is // also the initialization value for the enum type. if (signatureType == SignatureType.Illegal) { revert("SIGNATURE_ILLEGAL"); // Always invalid signature. // Like Illegal, this is always implicitly available and therefore // offered explicitly. It can be implicitly created by providing // a correctly formatted but incorrect signature. } else if (signatureType == SignatureType.Invalid) { require( signature.length == 0, "LENGTH_0_REQUIRED" ); isValid = false; return isValid; // Signature using EIP712 } else if (signatureType == SignatureType.EIP712) { require( signature.length == 65, "LENGTH_65_REQUIRED" ); v = uint8(signature[0]); r = readBytes32(signature, 1); s = readBytes32(signature, 33); recovered = ecrecover( hash, v, r, s ); isValid = signerAddress == recovered; return isValid; // Signed using web3.eth_sign } else if (signatureType == SignatureType.EthSign) { require( signature.length == 65, "LENGTH_65_REQUIRED" ); v = uint8(signature[0]); r = readBytes32(signature, 1); s = readBytes32(signature, 33); recovered = ecrecover( keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s ); isValid = signerAddress == recovered; return isValid; // Signature verified by wallet contract. // If used with an order, the maker of the order is the wallet contract. } else if (signatureType == SignatureType.Wallet) { isValid = isValidWalletSignature( hash, signerAddress, signature ); return isValid; // Signer signed hash previously using the preSign function. } else if (signatureType == SignatureType.PreSigned) { isValid = preSigned[hash][signerAddress]; return isValid; } // Anything else is illegal (We do not return false because // the signature may actually be valid, just not in a format // that we currently support. In this case returning false // may lead the caller to incorrectly believe that the // signature was invalid.) revert("SIGNATURE_UNSUPPORTED"); } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require( b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED" ); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Verifies signature using logic defined by Wallet contract. /// @param hash Any 32 byte hash. /// @param walletAddress Address that should have signed the given hash /// and defines its own signature verification method. /// @param signature Proof that the hash has been signed by signer. /// @return True if signature is valid for given wallet.. function isValidWalletSignature( bytes32 hash, address walletAddress, bytes memory signature ) internal view returns (bool isValid) { bytes memory callData = abi.encodeWithSelector( IWallet(walletAddress).isValidSignature.selector, hash, signature ); assembly { let cdStart := add(callData, 32) let success := staticcall( gas, // forward all gas walletAddress, // address of Wallet contract cdStart, // pointer to start of input mload(callData), // length of input cdStart, // write output over input 32 // output size is 32 bytes ) switch success case 0 { // Revert with `Error("WALLET_ERROR")` mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000) mstore(64, 0x0000000c57414c4c45545f4552524f5200000000000000000000000000000000) mstore(96, 0) revert(0, 100) } case 1 { // Signature is valid if call did not revert and returned true isValid := mload(cdStart) } } return isValid; } /// @dev Transfers assets. Either succeeds or throws. /// @param assetData Encoded byte array. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer. function transferFrom( bytes calldata assetData, address from, address to, uint256 amount ) external { require(msg.sender == address(this)); transferFromInternal( assetData, from, to, amount ); } /// @dev Transfers batch of ERC1155 assets. Either succeeds or throws. /// @param assetData Byte array encoded with ERC1155 token address, array of ids, array of values, and callback data. /// @param from Address to transfer assets from. /// @param to Address to transfer assets to. /// @param amount Amount that will be multiplied with each element of `assetData.values` to scale the /// values that will be transferred. function transferFromInternal( bytes memory assetData, address from, address to, uint256 amount ) private { // Decode params from `assetData` (address erc1155TokenAddress, uint256[] memory ids, uint256[] memory values, bytes memory data) = abi.decode(sliceDestructive(assetData, 4, assetData.length), (address, uint256[], uint256[], bytes)); // Scale values up by `amount` uint256 length = values.length; uint256[] memory scaledValues = new uint256[](length); for (uint256 i = 0; i != length; i++) { // We write the scaled values to an unused location in memory in order // to avoid copying over `ids` or `data`. This is possible if they are // identical to `values` and the offsets for each are pointing to the // same location in the ABI encoded calldata. scaledValues[i] = values[i].mul(amount); } // Execute `safeBatchTransferFrom` call // Either succeeds or throws IERC1155(erc1155TokenAddress).safeBatchTransferFrom( from, to, ids, scaledValues, data ); } /// @dev Decode ERC-1155 asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC-1155 set of assets. /// @return The ERC-1155 AssetProxy identifier, the address of the ERC-1155 /// contract hosting the assets, an array of the identifiers of the /// assets to be traded, an array of asset amounts to be traded, and /// callback data. Each element of the arrays corresponds to the /// same-indexed element of the other array. Return values specified as /// `memory` are returned as pointers to locations within the memory of /// the input parameter `assetData`. function decodeERC1155AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, uint256[] memory tokenIds, uint256[] memory tokenValues, bytes memory callbackData ) { assetProxyId = readBytes4(assetData, 0); require( assetProxyId == ERC1155_PROXY_ID, "WRONG_PROXY_ID" ); assembly { // Skip selector and length to get to the first parameter: assetData := add(assetData, 36) // Read the value of the first parameter: tokenAddress := mload(assetData) // Point to the next parameter's data: tokenIds := add(assetData, mload(add(assetData, 32))) // Point to the next parameter's data: tokenValues := add(assetData, mload(add(assetData, 64))) // Point to the next parameter's data: callbackData := add(assetData, mload(add(assetData, 96))) } return ( assetProxyId, tokenAddress, tokenIds, tokenValues, callbackData ); } function sliceDestructive( bytes memory b, uint256 from, uint256 to ) public pure returns (bytes memory result) { require( from <= to, "FROM_LESS_THAN_TO_REQUIRED" ); require( to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED" ); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { require( b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED" ); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev After calling, the order can not be filled anymore. /// Throws if order is invalid or sender does not have permission to cancel. /// @param order Order to cancel. Order must be OrderStatus.FILLABLE. function cancelOrder(Order memory order) public nonReentrant { cancelOrderInternal(order); } /// @dev Synchronously cancels multiple orders in a single transaction. /// @param orders Array of order specifications. function batchCancelOrders(Order[] memory orders) public nonReentrant { uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { cancelOrderInternal(orders[i]); } } /// @dev After calling, the order can not be filled anymore. /// Throws if order is invalid or sender does not have permission to cancel. /// @param order Order to cancel. Order must be OrderStatus.FILLABLE. function cancelOrderInternal(Order memory order) internal { // Fetch current order status OrderInfo memory orderInfo = getOrderInfo(order); // Validate context assertValidCancel(order, orderInfo); // Perform cancel updateCancelledState(order, orderInfo.orderHash); } /// @dev Validates context for cancelOrder. Succeeds or throws. /// @param order to be cancelled. /// @param orderInfo OrderStatus, orderHash, and amount already filled of order. function assertValidCancel( Order memory order, OrderInfo memory orderInfo ) internal view { // Ensure order is valid // An order can only be cancelled if its status is FILLABLE. require( orderInfo.orderStatus == uint8(OrderStatus.FILLABLE), "ORDER_UNFILLABLE" ); // Validate sender is allowed to cancel this order if (order.senderAddress != address(0)) { require( order.senderAddress == msg.sender, "INVALID_SENDER" ); } // Validate transaction signed by maker address makerAddress = getCurrentContextAddress(); require( order.makerAddress == makerAddress, "INVALID_MAKER" ); } /// @dev Updates state with results of cancelling an order. /// State is only updated if the order is currently fillable. /// Otherwise, updating state would have no effect. /// @param order that was cancelled. /// @param orderHash Hash of order that was cancelled. function updateCancelledState( Order memory order, bytes32 orderHash ) internal { // Perform cancel cancelled[orderHash] = true; } }
@dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws. @param assetData Byte array encoded for the asset. @param from Address to transfer token from. @param to Address to transfer token to. @param amount Amount of token to transfer. Do nothing if no amount should be transferred.
{ function dispatchTransferFrom( bytes memory assetData, address from, address to, uint256 amount ) internal if (amount > 0 && from != to) { require( assetData.length > 3, "LENGTH_GREATER_THAN_3_REQUIRED" ); address assetProxy = address(this); assembly { let cdStart := mload(64) let dataAreaLength := and(add(mload(assetData), 63), 0xFFFFFFFFFFFE0) let cdEnd := add(cdStart, add(132, dataAreaLength)) mstore(cdStart, 0xa85e59e400000000000000000000000000000000000000000000000000000000) mstore(add(cdStart, 4), 128) mstore(add(cdStart, 36), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(cdStart, 68), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(cdStart, 100), amount) let dataArea := add(cdStart, 132) mstore(dataArea, mload(assetData)) dataArea := add(dataArea, 32) assetData := add(assetData, 32) } ) if iszero(success) { revert(cdStart, returndatasize()) } } function dispatchTransferFrom( bytes memory assetData, address from, address to, uint256 amount ) internal if (amount > 0 && from != to) { require( assetData.length > 3, "LENGTH_GREATER_THAN_3_REQUIRED" ); address assetProxy = address(this); assembly { let cdStart := mload(64) let dataAreaLength := and(add(mload(assetData), 63), 0xFFFFFFFFFFFE0) let cdEnd := add(cdStart, add(132, dataAreaLength)) mstore(cdStart, 0xa85e59e400000000000000000000000000000000000000000000000000000000) mstore(add(cdStart, 4), 128) mstore(add(cdStart, 36), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(cdStart, 68), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(cdStart, 100), amount) let dataArea := add(cdStart, 132) mstore(dataArea, mload(assetData)) dataArea := add(dataArea, 32) assetData := add(assetData, 32) } ) if iszero(success) { revert(cdStart, returndatasize()) } } for {} lt(dataArea, cdEnd) {} { let success := call( function dispatchTransferFrom( bytes memory assetData, address from, address to, uint256 amount ) internal if (amount > 0 && from != to) { require( assetData.length > 3, "LENGTH_GREATER_THAN_3_REQUIRED" ); address assetProxy = address(this); assembly { let cdStart := mload(64) let dataAreaLength := and(add(mload(assetData), 63), 0xFFFFFFFFFFFE0) let cdEnd := add(cdStart, add(132, dataAreaLength)) mstore(cdStart, 0xa85e59e400000000000000000000000000000000000000000000000000000000) mstore(add(cdStart, 4), 128) mstore(add(cdStart, 36), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(cdStart, 68), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(cdStart, 100), amount) let dataArea := add(cdStart, 132) mstore(dataArea, mload(assetData)) dataArea := add(dataArea, 32) assetData := add(assetData, 32) } ) if iszero(success) { revert(cdStart, returndatasize()) } } }
5,479,206
[ 1, 1290, 6397, 1775, 358, 3310, 3886, 471, 4097, 1375, 13866, 1265, 8338, 14635, 21933, 578, 1216, 18, 225, 3310, 751, 3506, 526, 3749, 364, 326, 3310, 18, 225, 628, 5267, 358, 7412, 1147, 628, 18, 225, 358, 5267, 358, 7412, 1147, 358, 18, 225, 3844, 16811, 434, 1147, 358, 7412, 18, 2256, 5083, 309, 1158, 3844, 1410, 506, 906, 4193, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 565, 445, 3435, 5912, 1265, 12, 203, 3639, 1731, 3778, 3310, 751, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 203, 3639, 2713, 203, 3639, 309, 261, 8949, 405, 374, 597, 628, 480, 358, 13, 288, 203, 5411, 2583, 12, 203, 7734, 3310, 751, 18, 2469, 405, 890, 16, 203, 7734, 315, 7096, 67, 43, 18857, 67, 22408, 67, 23, 67, 14977, 6, 203, 5411, 11272, 203, 203, 5411, 1758, 3310, 3886, 273, 1758, 12, 2211, 1769, 203, 203, 203, 5411, 19931, 288, 203, 7734, 2231, 7976, 1685, 519, 312, 945, 12, 1105, 13, 203, 7734, 2231, 501, 5484, 1782, 519, 471, 12, 1289, 12, 81, 945, 12, 9406, 751, 3631, 13746, 3631, 374, 6356, 8998, 8998, 8090, 20, 13, 203, 7734, 2231, 7976, 1638, 519, 527, 12, 4315, 1685, 16, 527, 12, 22152, 16, 501, 5484, 1782, 3719, 203, 203, 203, 7734, 312, 2233, 12, 4315, 1685, 16, 374, 6995, 7140, 73, 6162, 73, 24, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 13, 203, 203, 7734, 312, 2233, 12, 1289, 12, 4315, 1685, 16, 1059, 3631, 8038, 13, 203, 7734, 312, 2233, 12, 1289, 12, 4315, 1685, 16, 6580, 3631, 471, 12, 2080, 16, 374, 5297, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 3719, 203, 7734, 312, 2233, 12, 1289, 12, 4315, 1685, 16, 23797, 3631, 471, 12, 869, 16, 374, 5297, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 3719, 203, 7734, 312, 2233, 12, 2 ]
./full_match/1/0x05a93215B8939a698a822b2605bc32b20dDa3aee/sources/T2T.sol
Verify the merkle proof
function whitelistMint(uint256 numberOfTokens, bytes32[] calldata merkleProof ) payable external callerIsUser { require(whitelistSaleIsActive, "Whitelist Sale must be active to mint"); require(WL_SUPPLY.sub(numberOfTokens)>=0, "Total WL Quota has been minted"); require(numberOfTokens > 0 && numberOfTokens <= 10, "Can only mint upto 10 NFTs in a transaction"); require(msg.value == WL_PRICE.mul(numberOfTokens), "Ether value sent is not correct"); require(numberMinted(msg.sender).add(numberOfTokens) <= 10,"Max 10 mints allowed per whitelisted wallet"); require(isWhitelisted[msg.sender] || MerkleProof.verify(merkleProof, merkleRoot, keccak256(abi.encodePacked(msg.sender)) ), "Not whitelisted"); _safeMint(msg.sender, numberOfTokens); WL_SUPPLY = WL_SUPPLY.sub(numberOfTokens); }
3,060,407
[ 1, 8097, 326, 30235, 14601, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10734, 49, 474, 12, 11890, 5034, 7922, 5157, 16, 1731, 1578, 8526, 745, 892, 30235, 20439, 262, 8843, 429, 3903, 4894, 2520, 1299, 288, 203, 3639, 2583, 12, 20409, 30746, 2520, 3896, 16, 315, 18927, 348, 5349, 1297, 506, 2695, 358, 312, 474, 8863, 203, 3639, 2583, 12, 59, 48, 67, 13272, 23893, 18, 1717, 12, 2696, 951, 5157, 13, 34, 33, 20, 16, 315, 5269, 678, 48, 4783, 25441, 711, 2118, 312, 474, 329, 8863, 203, 3639, 2583, 12, 2696, 951, 5157, 405, 374, 597, 7922, 5157, 1648, 1728, 16, 315, 2568, 1338, 312, 474, 582, 21910, 1728, 423, 4464, 87, 316, 279, 2492, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 678, 48, 67, 7698, 1441, 18, 16411, 12, 2696, 951, 5157, 3631, 315, 41, 1136, 460, 3271, 353, 486, 3434, 8863, 203, 3639, 2583, 12, 2696, 49, 474, 329, 12, 3576, 18, 15330, 2934, 1289, 12, 2696, 951, 5157, 13, 1648, 1728, 10837, 2747, 1728, 312, 28142, 2935, 1534, 26944, 9230, 8863, 203, 203, 3639, 2583, 12, 291, 18927, 329, 63, 3576, 18, 15330, 65, 747, 31827, 20439, 18, 8705, 12, 6592, 15609, 20439, 16, 30235, 2375, 16, 225, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 3719, 225, 262, 16, 315, 1248, 26944, 8863, 203, 1082, 203, 202, 202, 67, 4626, 49, 474, 12, 3576, 18, 15330, 16, 7922, 5157, 1769, 203, 202, 202, 59, 48, 67, 13272, 23893, 273, 678, 48, 67, 13272, 23893, 18, 1717, 12, 2696, 951, 5157, 2 ]
pragma solidity ^0.4.12; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; // allowedAddresses will be able to transfer even when locked // lockedAddresses will *not* be able to transfer even when *not locked* mapping(address => bool) public allowedAddresses; mapping(address => bool) public lockedAddresses; bool public locked = true; function allowAddress(address _addr, bool _allowed) public onlyOwner { require(_addr != owner); allowedAddresses[_addr] = _allowed; } function lockAddress(address _addr, bool _locked) public onlyOwner { require(_addr != owner); lockedAddresses[_addr] = _locked; } function setLocked(bool _locked) public onlyOwner { locked = _locked; } function canTransfer(address _addr) public constant returns (bool) { if(locked){ if(!allowedAddresses[_addr]&&_addr!=owner) return false; }else if(lockedAddresses[_addr]) return false; return true; } /** * @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(canTransfer(msg.sender)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(canTransfer(msg.sender)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * 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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); 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); } } contract FXPay is BurnableToken { string public constant name = "FXPay"; string public constant symbol = "FXP"; uint public constant decimals = 8; // there is no problem in using * here instead of .mul() uint256 public constant initialSupply = 500000000 * (10 ** uint256(decimals)); // Constructors function FXPay () { totalSupply = initialSupply; balances[msg.sender] = initialSupply; // Send all tokens to owner allowedAddresses[owner] = true; } }
there is no problem in using * here instead of .mul() Constructors
contract FXPay is BurnableToken { string public constant name = "FXPay"; string public constant symbol = "FXP"; uint public constant decimals = 8; uint256 public constant initialSupply = 500000000 * (10 ** uint256(decimals)); function FXPay () { totalSupply = initialSupply; allowedAddresses[owner] = true; } }
7,987,086
[ 1, 18664, 353, 1158, 6199, 316, 1450, 225, 2674, 3560, 434, 263, 16411, 1435, 14291, 1383, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 478, 60, 9148, 225, 353, 605, 321, 429, 1345, 288, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 25172, 9148, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 25172, 52, 14432, 203, 565, 2254, 1071, 5381, 15105, 273, 1725, 31, 203, 565, 2254, 5034, 1071, 5381, 2172, 3088, 1283, 273, 1381, 12648, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 203, 565, 445, 478, 60, 9148, 1832, 288, 203, 3639, 2078, 3088, 1283, 273, 2172, 3088, 1283, 31, 203, 3639, 2935, 7148, 63, 8443, 65, 273, 638, 31, 203, 565, 289, 203, 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 ]
./full_match/80001/0x03562E2e6E4A43fE8dddB0e9b1f15F752Cd1313d/sources/contracts/Gigble.sol
Enum for project state
contract Gigble { pragma solidity ^0.8.9; enum State { Inactive, Active, Completed } struct Project { string email; address payable client; address payable freelancer; uint256 budget; string description; uint256 deadline; bool completed; bool paid; State state; } error InvalidState(); modifier inState(State state_) { if (state != state_) revert InvalidState(); _; } uint256 indexed projectId, string email, string description, uint256 budget, uint256 deadline, address payable client ); event ProjectAccepted(uint256 indexed projectId); event PaymentReleased(uint256 indexed projectId); event PaymentRefunded(uint256 indexed projectId); address payable public platformAddress; uint256 public platformFee; uint256 public projectIdCounter; State public state; event ProjectCreated( Project[] public projects; constructor(address payable _platformAddress, uint256 _platformFee) { platformAddress = _platformAddress; platformFee = _platformFee; state = State.Inactive; projectIdCounter = 0; } function createProject( string calldata _email, string calldata _description, uint256 _deadline ) external payable inState(State.Inactive) { require( msg.value > 0, "Please provide a non-zero project budget as the value of the transaction." ); Project memory project = Project({ email: _email, description: _description, budget: msg.value, deadline: _deadline, client: payable(msg.sender), freelancer: payable(address(0)), completed: false, paid: false, state: State.Active }); projects.push(project); projectIdCounter++; emit ProjectCreated( projectIdCounter, project.email, project.description, project.budget, project.deadline, project.client ); } function createProject( string calldata _email, string calldata _description, uint256 _deadline ) external payable inState(State.Inactive) { require( msg.value > 0, "Please provide a non-zero project budget as the value of the transaction." ); Project memory project = Project({ email: _email, description: _description, budget: msg.value, deadline: _deadline, client: payable(msg.sender), freelancer: payable(address(0)), completed: false, paid: false, state: State.Active }); projects.push(project); projectIdCounter++; emit ProjectCreated( projectIdCounter, project.email, project.description, project.budget, project.deadline, project.client ); } function acceptProject(uint256 _projectId) external { Project storage project = projects[_projectId]; require(project.freelancer == address(0), "Project already accepted"); require( msg.sender == project.client, "Only Client can accept the project" ); project.freelancer = payable(msg.sender); uint256 fee = (project.budget * platformFee) / 100; platformAddress.transfer(fee); uint256 amount = project.budget - fee; project.completed = true; project.paid = true; project.freelancer.transfer(amount); emit ProjectAccepted(_projectId); emit PaymentReleased(_projectId); } function refundPayment(uint256 _projectId) external { Project storage project = projects[_projectId]; require( msg.sender == platformAddress, "Only platform can refund payment" ); require(!project.completed, "Project already completed"); require(block.timestamp > project.deadline, "Deadline not yet passed"); project.completed = true; project.state = State.Completed; project.client.transfer(project.budget); emit PaymentRefunded(_projectId); } }
9,487,296
[ 1, 3572, 364, 1984, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 611, 360, 7119, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 29, 31, 203, 565, 2792, 3287, 288, 203, 3639, 657, 3535, 16, 203, 3639, 8857, 16, 203, 3639, 28722, 203, 565, 289, 203, 203, 565, 1958, 5420, 288, 203, 3639, 533, 2699, 31, 203, 3639, 1758, 8843, 429, 1004, 31, 203, 3639, 1758, 8843, 429, 22010, 292, 304, 2750, 31, 203, 3639, 2254, 5034, 15051, 31, 203, 3639, 533, 2477, 31, 203, 3639, 2254, 5034, 14096, 31, 203, 3639, 1426, 5951, 31, 203, 3639, 1426, 30591, 31, 203, 3639, 3287, 919, 31, 203, 565, 289, 203, 203, 565, 555, 1962, 1119, 5621, 203, 203, 565, 9606, 316, 1119, 12, 1119, 919, 67, 13, 288, 203, 3639, 309, 261, 2019, 480, 919, 67, 13, 15226, 1962, 1119, 5621, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 3639, 2254, 5034, 8808, 9882, 16, 203, 3639, 533, 2699, 16, 203, 3639, 533, 2477, 16, 203, 3639, 2254, 5034, 15051, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 1758, 8843, 429, 1004, 203, 565, 11272, 203, 565, 871, 5420, 18047, 12, 11890, 5034, 8808, 9882, 1769, 203, 565, 871, 12022, 26363, 12, 11890, 5034, 8808, 9882, 1769, 203, 565, 871, 12022, 1957, 12254, 12, 11890, 5034, 8808, 9882, 1769, 203, 203, 203, 565, 1758, 8843, 429, 1071, 4072, 1887, 31, 203, 565, 2254, 5034, 1071, 4072, 14667, 31, 203, 565, 2254, 5034, 1071, 9882, 4789, 31, 203, 203, 565, 3287, 1071, 919, 31, 203, 203, 565, 871, 5420, 6119, 12, 203, 2 ]
./full_match/4/0xD33Ee6359051a906787131622da2215BAe6281ba/sources/contracts/library/statemachine/StateMachine.sol
* @notice Updates expense properties @param roleName Bytes32 name of the role to be granted @param account Grant a role to a specific account/
function grantRoleToAccount(bytes32 roleName, address account) public hasAdminRole(msg.sender) { _grantRole(roleName, account); }
12,479,060
[ 1, 5121, 1329, 3558, 1790, 225, 19746, 5985, 1578, 508, 434, 326, 2478, 358, 506, 17578, 225, 2236, 19689, 279, 2478, 358, 279, 2923, 2236, 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, 225, 445, 7936, 2996, 774, 3032, 12, 3890, 1578, 19746, 16, 1758, 2236, 13, 1071, 711, 4446, 2996, 12, 3576, 18, 15330, 13, 288, 203, 565, 389, 16243, 2996, 12, 4615, 461, 16, 2236, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import '../interface/IValidator.sol'; import '../interface/ILiability.sol'; /** * @dev Autonomous validator that helps cancel liabilities when promisor was gone. */ contract CancellationValidator is IValidator { event CancellationRequest(address indexed liability); mapping(address => uint256) public cancellationRequest; uint256 public waitingPeriod; /** * @param _waitingPeriod Waiting period in blocks */ constructor(uint256 _waitingPeriod) public { waitingPeriod = _waitingPeriod; } /** * @dev Request to cancel liability * @param _liability Contract address * @notice For promisee only */ function cancel(address _liability) external { require(ILiability(_liability).promisee() == msg.sender); cancellationRequest[_liability] = block.number; emit CancellationRequest(_liability); } function isValidator(address _validator) external returns (bool) { uint256 requestStartBlock = cancellationRequest[msg.sender]; bool waitingDone = requestStartBlock > 0 && block.number - requestStartBlock > waitingPeriod; ILiability liability = ILiability(msg.sender); if (_validator == liability.promisee() && waitingDone) { return true; } else { return false; } } }
* @dev Autonomous validator that helps cancel liabilities when promisor was gone./
contract CancellationValidator is IValidator { event CancellationRequest(address indexed liability); mapping(address => uint256) public cancellationRequest; uint256 public waitingPeriod; constructor(uint256 _waitingPeriod) public { waitingPeriod = _waitingPeriod; } function cancel(address _liability) external { require(ILiability(_liability).promisee() == msg.sender); cancellationRequest[_liability] = block.number; emit CancellationRequest(_liability); } function isValidator(address _validator) external returns (bool) { uint256 requestStartBlock = cancellationRequest[msg.sender]; bool waitingDone = requestStartBlock > 0 && block.number - requestStartBlock > waitingPeriod; ILiability liability = ILiability(msg.sender); if (_validator == liability.promisee() && waitingDone) { return true; return false; } } function isValidator(address _validator) external returns (bool) { uint256 requestStartBlock = cancellationRequest[msg.sender]; bool waitingDone = requestStartBlock > 0 && block.number - requestStartBlock > waitingPeriod; ILiability liability = ILiability(msg.sender); if (_validator == liability.promisee() && waitingDone) { return true; return false; } } } else { }
7,296,029
[ 1, 7150, 4708, 1481, 4213, 716, 21814, 3755, 4501, 5756, 1347, 3012, 12385, 1703, 22296, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4480, 6857, 5126, 353, 467, 5126, 288, 203, 565, 871, 4480, 6857, 691, 12, 2867, 8808, 4501, 2967, 1769, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 7272, 691, 31, 203, 565, 2254, 5034, 1071, 7336, 5027, 31, 203, 203, 565, 3885, 12, 11890, 5034, 389, 20241, 5027, 13, 1071, 288, 203, 3639, 7336, 5027, 273, 389, 20241, 5027, 31, 203, 565, 289, 203, 203, 565, 445, 3755, 12, 2867, 389, 549, 2967, 13, 3903, 288, 203, 3639, 2583, 12, 2627, 21280, 24899, 549, 2967, 2934, 20837, 73, 1435, 422, 1234, 18, 15330, 1769, 203, 3639, 7272, 691, 63, 67, 549, 2967, 65, 273, 1203, 18, 2696, 31, 203, 3639, 3626, 4480, 6857, 691, 24899, 549, 2967, 1769, 203, 565, 289, 203, 203, 565, 445, 4908, 639, 12, 2867, 389, 7357, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 590, 1685, 1768, 273, 7272, 691, 63, 3576, 18, 15330, 15533, 203, 3639, 1426, 7336, 7387, 273, 590, 1685, 1768, 405, 374, 203, 13491, 597, 1203, 18, 2696, 300, 590, 1685, 1768, 405, 7336, 5027, 31, 203, 203, 3639, 467, 48, 21280, 4501, 2967, 273, 467, 48, 21280, 12, 3576, 18, 15330, 1769, 203, 3639, 309, 261, 67, 7357, 422, 4501, 2967, 18, 20837, 73, 1435, 597, 7336, 7387, 13, 288, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 565, 445, 4908, 639, 12, 2867, 389, 7357, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 590, 2 ]
./full_match/137/0xFe06df139FD9291a218c468a2e318e84b5cF4328/sources/IFOV.sol
limit of tokens per user (if 0, it is ignored)
* @return limitPerUserInLP;
3,755,844
[ 1, 3595, 434, 2430, 1534, 729, 261, 430, 374, 16, 518, 353, 5455, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 380, 632, 2463, 1800, 2173, 1299, 382, 14461, 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 ]
./partial_match/1/0x891696CCa87aa2f175124b412198c23D54680E31/sources/NFTWinner.sol
* @dev Gas spent here starts off proportional to the maximum mint batch size. It gradually moves to O(1) as tokens get transferred around over time./
function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnershipOf(tokenId)); }
3,585,503
[ 1, 27998, 26515, 2674, 2542, 3397, 23279, 287, 358, 326, 4207, 312, 474, 2581, 963, 18, 2597, 3087, 2544, 1230, 13934, 358, 531, 12, 21, 13, 487, 2430, 336, 906, 4193, 6740, 1879, 813, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 995, 12565, 951, 12, 11890, 5034, 1147, 548, 13, 203, 565, 2713, 203, 565, 1476, 203, 565, 5024, 203, 565, 1135, 261, 1345, 5460, 12565, 3778, 13, 203, 225, 288, 203, 565, 327, 389, 17309, 329, 5460, 12565, 24899, 2920, 329, 5460, 12565, 951, 12, 2316, 548, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x0048FC4357DB3c0f45AdEA433a07A20769dDB0CF/sources/DssBlow.sol
`join` `wad` amount of Dai from your wallet to the `vow`. Requires Dai approval of this contract.
function blow(uint256 wad) public { dai.transferFrom(msg.sender, address(this), wad); daiJoin.join(vow, wad); emit Blow(wad); }
4,822,311
[ 1, 68, 5701, 68, 1375, 91, 361, 68, 3844, 434, 463, 10658, 628, 3433, 9230, 358, 326, 1375, 90, 543, 8338, 16412, 463, 10658, 23556, 434, 333, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 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, 324, 821, 12, 11890, 5034, 341, 361, 13, 1071, 288, 203, 3639, 5248, 77, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 341, 361, 1769, 203, 3639, 5248, 77, 4572, 18, 5701, 12, 90, 543, 16, 341, 361, 1769, 203, 3639, 3626, 605, 821, 12, 91, 361, 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 ]
//Address: 0x2Fb3C22230c39496eDc13c16d09F34368346Ac1D //Contract name: ISmartCert //Balance: 0 Ether //Verification Date: 3/6/2018 //Transacion Count: 54 // CODE STARTS HERE pragma solidity ^0.4.17; contract ISmartCert { // state variables mapping (bytes32 => SignedData) hashes; mapping (address => AccessStruct) accessList; mapping (bytes32 => RevokeStruct) revoked; mapping (bytes32 => Lvl2Struct[]) idMap; address owner; // constants string constant CODE_ACCESS_DENIED = "A001"; string constant CODE_ACCESS_POSTER_NOT_AUTHORIZED = "A002"; string constant CODE_ACCESS_ISSUER_NOT_AUTHORIZED = "A003"; string constant CODE_ACCESS_VERIFY_NOT_AUTHORIZED = "A004"; string constant MSG_ISSUER_SIG_NOT_MATCHED = "E001"; //"Issuer's address not matched with signed hash"; string constant MSG_DOC_REGISTERED = "E002"; //"Document already registered"; string constant MSG_REVOKED = "E003"; //"Document already revoked"; string constant MSG_NOTREG = "E004"; //"Document not registered"; string constant MSG_INVALID = "E005"; //"Document not valid"; string constant MSG_NOFOUND = "E006"; //"No record found"; string constant MSG_INVALID_CERT_MERKLE_NOT_MATCHED = "E007"; string constant MSG_INVALID_ACCESS_RIGHT = "E008"; string constant MSG_BATCH_REVOKED = "E009"; //"Batch that the document belong to has already been revoked"; string constant MSG_MERKLE_CANNOT_EMPTY = "E010"; string constant MSG_MERKLE_NOT_REGISTERED = "E011"; string constant STATUS_PASS = "PASS"; string constant STATUS_FAIL = "FAIL"; bytes1 constant ACCESS_ISSUER = 0x04; bytes1 constant ACCESS_POSTER = 0x02; bytes1 constant ACCESS_VERIFIER = 0x01; bytes1 constant ACCESS_ALL = 0x07; bytes1 constant ACCESS_ISSUER_POSTER = 0x05; bytes1 constant ACCESS_NONE = 0x00; struct SignedData { // string data; bytes sig; uint registerDate; bool exists; // empty entry to this struct initially set to false } struct RecordStruct { bytes32 recordId; // ref id to hashstore bool exists; // empty entry to this struct initially set to false } struct Lvl2Struct { bytes32 recordId; bytes32 certhash; bool exists; } struct RevokeStruct { bool exists; bytes32 merkleHash; bool batchFlag; uint date; } struct AccessStruct { bytes1 accessRight; uint date; bool isValue; } function ISmartCert() public { owner = msg.sender; } event LogUserRight(string, string); function userRight(address userAddr, bytes1 accessRight, uint date) public { if (owner != msg.sender) { LogUserRight(STATUS_FAIL, CODE_ACCESS_DENIED); return; } if (accessRight != ACCESS_ISSUER && accessRight != ACCESS_POSTER && accessRight != ACCESS_VERIFIER && accessRight != ACCESS_ALL && accessRight != ACCESS_ISSUER_POSTER && accessRight != ACCESS_NONE) { LogUserRight(STATUS_FAIL, MSG_INVALID_ACCESS_RIGHT); return; } accessList[userAddr].accessRight = accessRight; accessList[userAddr].date = date; accessList[userAddr].isValue = true; LogUserRight(STATUS_PASS, ""); } function checkAccess(address user, bytes1 access) internal view returns (bool) { if (accessList[user].isValue) { if (accessList[user].accessRight & access == access) { return true; } } return false; } function internalRegisterCert(bytes32 certHash, bytes sig, uint registrationDate) internal returns (string, string) { address issuer; if (!checkAccess(msg.sender, ACCESS_POSTER)) { return (STATUS_FAIL, CODE_ACCESS_POSTER_NOT_AUTHORIZED); } issuer = recoverAddr(certHash, sig); if (!checkAccess(issuer, ACCESS_ISSUER)) { return (STATUS_FAIL, CODE_ACCESS_ISSUER_NOT_AUTHORIZED); } if (hashes[certHash].exists) { // check if doc has already been revoked if (revoked[certHash].exists) { return (STATUS_FAIL, MSG_REVOKED); } else { return (STATUS_FAIL, MSG_DOC_REGISTERED); } } // signed data (in r, s, v) hashes[certHash].sig = sig; // certificate registration date (YYYYmmdd) hashes[certHash].registerDate = registrationDate; // indicate the record exists hashes[certHash].exists = true; return (STATUS_PASS, ""); } function internalRegisterCertWithID(bytes32 certHash, bytes sig, bytes32 merkleHash, uint registrationDate, bytes32 id) internal returns (string, string) { string memory status; string memory message; // check if any record associated with id for (uint i = 0; i < idMap[id].length; i++) { if (idMap[id][i].exists == true && idMap[id][i].certhash == certHash) { return (STATUS_FAIL, MSG_DOC_REGISTERED); } } // check if merkle root has already been revoked if (merkleHash != 0x00) { if (revoked[merkleHash].exists && revoked[merkleHash].batchFlag) { return (STATUS_FAIL, MSG_BATCH_REVOKED); } } // check if merkle root is empty if (merkleHash == 0x00) { return (STATUS_FAIL, MSG_MERKLE_CANNOT_EMPTY); } // check if merkle is exists if (!hashes[merkleHash].exists) { return (STATUS_FAIL, MSG_MERKLE_NOT_REGISTERED); } // register certificate (status, message) = internalRegisterCert(certHash, sig, registrationDate); if (keccak256(status) != keccak256(STATUS_PASS)) { return (status, message); } // store record id by ID idMap[id].push(Lvl2Struct({recordId:merkleHash, certhash:certHash, exists:true})); return (STATUS_PASS, ""); } function internalRevokeCert(bytes32 certHash, bytes sigCertHash, bytes32 merkleHash, bool batchFlag, uint revocationDate) internal returns (string, string) { address issuer1; address issuer2; // check poster access right if (!checkAccess(msg.sender, ACCESS_POSTER)) { return (STATUS_FAIL, CODE_ACCESS_POSTER_NOT_AUTHORIZED); } // check issuer access right issuer1 = recoverAddr(certHash, sigCertHash); if (!checkAccess(issuer1, ACCESS_ISSUER)) { return (STATUS_FAIL, CODE_ACCESS_ISSUER_NOT_AUTHORIZED); } // if batch, ensure both certHash and merkleHash are same if (batchFlag) { if (certHash != merkleHash) { return (STATUS_FAIL, MSG_INVALID_CERT_MERKLE_NOT_MATCHED); } if (merkleHash == 0x00) { return (STATUS_FAIL, MSG_MERKLE_CANNOT_EMPTY); } } if (merkleHash != 0x00) { // check if doc (merkle root) is registered if (hashes[merkleHash].exists == false) { return (STATUS_FAIL, MSG_NOTREG); } // check if requested signature and stored signature is same by comparing two issuer addresses issuer2 = recoverAddr(merkleHash, hashes[merkleHash].sig); if (issuer1 != issuer2) { return (STATUS_FAIL, MSG_ISSUER_SIG_NOT_MATCHED); } } // check if doc has already been revoked if (revoked[certHash].exists) { return (STATUS_FAIL, MSG_REVOKED); } // store / update if (batchFlag) { revoked[certHash].batchFlag = true; } else { revoked[certHash].batchFlag = false; } revoked[certHash].exists = true; revoked[certHash].merkleHash = merkleHash; revoked[certHash].date = revocationDate; return (STATUS_PASS, ""); } // event as a form of return value, state mutating function cannot return value to external party event LogRegisterCert(string, string); function registerCert(bytes32 certHash, bytes sig, uint registrationDate) public { string memory status; string memory message; (status, message) = internalRegisterCert(certHash, sig, registrationDate); LogRegisterCert(status, message); } event LogRegisterCertWithID(string, string); function registerCertWithID(bytes32 certHash, bytes sig, bytes32 merkleHash, uint registrationDate, bytes32 id) public { string memory status; string memory message; // register certificate (status, message) = internalRegisterCertWithID(certHash, sig, merkleHash, registrationDate, id); LogRegisterCertWithID(status, message); } // for verification function internalVerifyCert(bytes32 certHash, bytes32 merkleHash, address issuer) internal view returns (string, string) { bytes32 tmpCertHash; // check if doc has already been revoked if (revoked[certHash].exists && !revoked[certHash].batchFlag) { return (STATUS_FAIL, MSG_REVOKED); } if (merkleHash != 0x00) { // check if merkle root has already been revoked if (revoked[merkleHash].exists && revoked[merkleHash].batchFlag) { return (STATUS_FAIL, MSG_REVOKED); } tmpCertHash = merkleHash; } else { tmpCertHash = certHash; } // check if doc in hash store if (hashes[tmpCertHash].exists) { if (recoverAddr(tmpCertHash, hashes[tmpCertHash].sig) != issuer) { return (STATUS_FAIL, MSG_INVALID); } return (STATUS_PASS, ""); } else { return (STATUS_FAIL, MSG_NOTREG); } } function verifyCert(bytes32 certHash, bytes32 merkleHash, address issuer) public view returns (string, string) { string memory status; string memory message; bool isAuthorized; // check verify access isAuthorized = checkVerifyAccess(); if (!isAuthorized) { return (STATUS_FAIL, CODE_ACCESS_VERIFY_NOT_AUTHORIZED); } (status, message) = internalVerifyCert(certHash, merkleHash, issuer); return (status, message); } function verifyCertWithID(bytes32 certHash, bytes32 merkleHash, bytes32 id, address issuer) public view returns (string, string) { string memory status; string memory message; bool isAuthorized; // check verify access isAuthorized = checkVerifyAccess(); if (!isAuthorized) { return (STATUS_FAIL, CODE_ACCESS_VERIFY_NOT_AUTHORIZED); } // check if any record associated with id for (uint i = 0; i < idMap[id].length; i++) { if (idMap[id][i].exists == true && idMap[id][i].certhash == certHash) { (status, message) = internalVerifyCert(certHash, merkleHash, issuer); return (status, message); } } // no record found return (STATUS_FAIL, MSG_NOFOUND); } function checkVerifyAccess() internal view returns (bool) { // check if sender is authorized for cert verification return checkAccess(msg.sender, ACCESS_VERIFIER); } // event as a form of return value, state mutating function cannot return value to external party event LogRevokeCert(string, string); function revokeCert(bytes32 certHash, bytes sigCertHash, bytes32 merkleHash, bool batchFlag, uint revocationDate) public { string memory status; string memory message; (status, message) = internalRevokeCert(certHash, sigCertHash, merkleHash, batchFlag, revocationDate); LogRevokeCert(status, message); } // event LogReissueCert(string, bytes32, string); event LogReissueCert(string, string); function reissueCert(bytes32 revokeCertHash, bytes revokeSigCertHash, bytes32 revokeMerkleHash, uint revocationDate, bytes32 registerCertHash, bytes registerSig, uint registrationDate) public { string memory status; string memory message; // revoke certificate (status, message) = internalRevokeCert(revokeCertHash, revokeSigCertHash, revokeMerkleHash, false, revocationDate); if (keccak256(status) != keccak256(STATUS_PASS)) { LogReissueCert(status, message); return; } // register certificate (status, message) = internalRegisterCert(registerCertHash, registerSig, registrationDate); LogReissueCert(status, message); if (keccak256(status) != keccak256(STATUS_PASS)) { revert(); } LogReissueCert(STATUS_PASS, ""); } event LogReissueCertWithID(string, string); function reissueCertWithID(bytes32 revokeCertHash, bytes revokeSigCertHash, bytes32 revokeMerkleHash, uint revocationDate, bytes32 registerCertHash, bytes registerSig, bytes32 registerMerkleHash, uint registrationDate, bytes32 id) public { string memory status; string memory message; // revoke certificate (status, message) = internalRevokeCert(revokeCertHash, revokeSigCertHash, revokeMerkleHash, false, revocationDate); if (keccak256(status) != keccak256(STATUS_PASS)) { LogReissueCertWithID(status, message); return; } // register certificate (status, message) = internalRegisterCertWithID(registerCertHash, registerSig, registerMerkleHash, registrationDate, id); LogReissueCertWithID(status, message); if (keccak256(status) != keccak256(STATUS_PASS)) { revert(); } LogReissueCertWithID(STATUS_PASS, ""); } function recoverAddr(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 33)) s := mload(add(sig, 65)) v := mload(add(sig, 1)) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(1)); } else { return ecrecover(hash, v, r, s); } } }
event LogReissueCert(string, bytes32, string);
event LogReissueCert(string, string);
5,429,582
[ 1, 2575, 1827, 426, 13882, 5461, 12, 1080, 16, 1731, 1578, 16, 533, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1827, 426, 13882, 5461, 12, 1080, 16, 533, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./Relic.sol"; interface LootOwner { function ownerOf(uint256 tokenId) external view returns (address); } interface GenesisLootOwner { function ownerOf(uint256 tokenId) external view returns (address); function getLootTokenIds(uint256 tokenId) external view returns(uint256[8] memory); function getOrder(uint256 tokenId) external view returns (string memory); } interface IRiftData { function addXP(uint256 xp, uint256 bagId) external; } contract Dungeon3Minter is Ownable, IRelicMinter { LootOwner internal _oloot; LootOwner internal _mloot; GenesisLootOwner internal _gloot; Relic internal _relic; string public _imageBaseURL; mapping(uint256 => bool) public _claims; mapping(address => bool) public _relayAddresses; address public _riftAddress; bool public _isXpRewardsEnabled; uint256[16] public _bestRaiderRelicNextIdsByRank = [ 252, 840, 924, 2016, 2100, 2184, 2268, 4368, 4452, 4536, 4620, 4704, 4788, 4872, 4956, 37296 ]; uint256[16] public _bestRaiderLastIdsByRank = [ 335, 923, 1007, 2099, 2183, 2267, 2351, 4451, 4535, 4619, 4703, 4787, 4871, 4955, 5039, 37379 ]; uint256[16] public _runnerUpRelicNextIdsByRank = [ 37380, 37710, 38040, 38370, 38700, 39030, 39360, 39690, 40020, 40350, 40680, 41010, 41340, 41670, 42000, 42330 ]; uint256[16] public _runnerUpRelicLastIdsByRank = [ 37709, 38039, 38369, 38699, 39029, 39359, 39689, 40019, 40349, 40679, 41009, 41339, 41669, 41999, 42329, 42659 ]; constructor( address olootAddress, address mlootAddress, address glootAddress, address relicAddress, address riftAddress, string memory imageBaseURL ) { _oloot = LootOwner(olootAddress); _mloot = LootOwner(mlootAddress); _gloot = GenesisLootOwner(glootAddress); _relic = Relic(relicAddress); _riftAddress = riftAddress; _imageBaseURL = imageBaseURL; } function getRaidId(uint256 tokenId, uint8 raiderType) public pure returns (uint256) { return (raiderType) | (tokenId << 8); } function getRaidDungeonRequest( uint dungeonId, uint256 raidTokenId, uint256 raidTokenType, uint8 v, bytes32 r, bytes32 s ) public view returns ( bool isOwner, uint256[8] memory itemIds, string memory order, address signer ) { bytes32 requestHash = keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encode( "raidDungeon", dungeonId, raidTokenId, raidTokenType )) )); signer = ecrecover(requestHash, v, r, s); isOwner = isOwnerOf(raidTokenId, raidTokenType, signer); if (raidTokenType == 0) { itemIds = [ raidTokenId, raidTokenId, raidTokenId, raidTokenId, raidTokenId, raidTokenId, raidTokenId, raidTokenId ]; order = "no order"; } else if (raidTokenType == 1) { itemIds = [ raidTokenId, raidTokenId, raidTokenId, raidTokenId, raidTokenId, raidTokenId, raidTokenId, raidTokenId ]; order = "no order"; } else if (raidTokenType == 2) { itemIds = _gloot.getLootTokenIds(raidTokenId); order = _gloot.getOrder(raidTokenId); } else { require(false, "invalid raid token type"); } return (isOwner, itemIds, order, signer); } function isOwnerOf(uint256 raidTokenId, uint raidTokenType, address addr) public view returns (bool) { if (raidTokenType == 0) { return addr == _oloot.ownerOf(raidTokenId); } else if (raidTokenType == 1) { return addr == _mloot.ownerOf(raidTokenId); } else if (raidTokenType == 2) { return addr == _gloot.ownerOf(raidTokenId); } else { return false; } } function isVerifiedClaimRequest( uint dungeonId, uint dungeonRank, uint256 raidTokenId, uint8 raidTokenType, uint8 raidRank, bytes memory claimCoupon ) public view returns ( bool ) { // extract signature parts from coupon (bytes32 r, bytes32 s, uint8 v) = splitSignature(claimCoupon); // extract signer from signature and request address signer = ecrecover(keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encode( dungeonId, dungeonRank, raidTokenId, raidTokenType, raidRank )) )), v, r, s); // never trust 0x0 require(signer != address(0x0), "invalid signer"); // return true if signed by the relay/oracle return _relayAddresses[signer]; } function claimRewards( uint8[] calldata dungeonIds, uint8[] calldata dungeonRanks, uint64[] calldata raidTokenIds, uint8[] calldata raidTokenTypes, uint8[] calldata raidRanks, bytes[] calldata claimCoupons ) public { // claim each request for (uint256 i = 0; i < raidTokenIds.length; i++) { claimReward( dungeonIds[i], dungeonRanks[i], raidTokenIds[i], raidTokenTypes[i], raidRanks[i], claimCoupons[i] ); } } function claimReward( uint8 dungeonId, uint8 dungeonRank, uint64 raidTokenId, uint8 raidTokenType, uint8 raidRank, bytes calldata claimCoupon ) public { // verify that the request is signed by the relay which is acting as an oracle for raids require(isVerifiedClaimRequest( dungeonId, dungeonRank, raidTokenId, raidTokenType, raidRank, claimCoupon ), "claim verification fail"); // get unique raid id uint256 raidId = getRaidId(raidTokenId, raidTokenType); // check not already claimed require(!_claims[raidId], "already claimed"); // verify that the sender is the owner of the given raidTokenId require(isOwnerOf(raidTokenId, raidTokenType, msg.sender), "raider does not own loot"); // Rift XP: gLoot bag IDs must be offset by adding ‘9997460’ to their value uint256 lootIdOffset; if (raidTokenType == 2) { lootIdOffset = 9997460; } // find and consume the relicId for the raidRank uint256 relicId; if (raidRank == 0) { relicId = _bestRaiderRelicNextIdsByRank[dungeonRank]; require(relicId <= _bestRaiderLastIdsByRank[dungeonRank], "no more relics available for rank"); _bestRaiderRelicNextIdsByRank[dungeonRank]++; if (_isXpRewardsEnabled) { IRiftData(_riftAddress).addXP((uint256(16 - dungeonRank) * 20) + 200, uint256(raidTokenId) + lootIdOffset); } } else { relicId = _runnerUpRelicNextIdsByRank[dungeonRank]; require(relicId <= _runnerUpRelicLastIdsByRank[dungeonRank], "no more relics available for rank"); _runnerUpRelicNextIdsByRank[dungeonRank]++; if (_isXpRewardsEnabled) { IRiftData(_riftAddress).addXP((uint256(16 - dungeonRank) * 10) + 200, uint256(raidTokenId) + lootIdOffset); } } // mark this raidToken as claimed _claims[raidId] = true; // set relic data bytes12 data = bytes12(uint96(dungeonId & 0xffffffffffffffffffffffff)); // mint it _relic.mint(msg.sender, relicId, data); } function isClaimed( uint8 raidTokenType, uint256 raidTokenId ) public view returns ( bool ) { uint256 raidId = getRaidId(raidTokenId, raidTokenType); return _claims[raidId]; } function splitSignature(bytes memory sig) public pure returns ( bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "invalid signature length"); assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28, "invalid signature version"); // implicitly return (r, s, v) } function setRelayAddress(address relayAddress, bool active) external onlyOwner { _relayAddresses[relayAddress] = active; } // // *** IRelicMinter Interface *** // function setImageBaseURL(string memory newImageBaseURL) public onlyOwner { _imageBaseURL = newImageBaseURL; } function getTokenOrderIndex(uint256 /*tokenId*/, bytes12 data) external override pure returns(uint) { uint96 dungeonId = uint96(data); return dungeonId % 16; } function getTokenProvenance(uint256 /*tokenId*/, bytes12 /*data*/) external override pure returns(string memory) { return "The Crypt: Chapter Three"; } function getAdditionalAttributes(uint256 /*tokenId*/, bytes12 /*data*/) external override pure returns(string memory) { return ""; } function getImageBaseURL() external override view returns(string memory) { return _imageBaseURL; } function enableXpRewards(bool enabled) external onlyOwner { _isXpRewardsEnabled = enabled; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1967/ERC1967ProxyImplementation.sol"; import "./OpenSea/ERC721TradableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; struct RelicProperties { uint256 relicTypeId; uint256 materialId; uint256 materialOffset; // this relic's number relative to material, e.g. Gold Skull #42 uint256 poleId; uint256 astralId; uint256 elementId; uint256 alignmentId; uint256 greatness; } interface IRelicMinter { // The relic minter can inject attributes into the metadata attributes array, // they will be added after the standard ones so should begin with a comma. // e.g. ,{"trait_type": "Extra Field", "value": "The Value"} function getAdditionalAttributes(uint256 tokenId, bytes12 data) external view returns(string memory); function getTokenOrderIndex(uint256 tokenId, bytes12 data) external view returns(uint); function getTokenProvenance(uint256 tokenId, bytes12 data) external view returns(string memory); function getImageBaseURL() external view returns(string memory); } contract Relic is ProxyImplementation, ERC721TradableUpgradeable { mapping(address => bool) private _whitelistedMinters; mapping(uint256 => uint256) public _tokenMintInfo; string public _placeholderImageURL; string public _animationBaseURL; string public _collectionName; string public _collectionDesc; string public _collectionImgURL; string public _collectionExtURL; uint256 public _feeBasisPoints; address public _feeRecipient; function init( string memory name, string memory symbol, address proxyRegistryAddress, string memory placeholderImageURL, string memory animationBaseURL, string memory collectionName, string memory collectionDesc, string memory collectionImgURL, string memory collectionExtURL, uint256 feeBasisPoints, address feeRecipient) public onlyOwner initializer { _initializeEIP712(name); __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name, symbol); __ERC721TradableUpgradeable_init_unchained(proxyRegistryAddress); _placeholderImageURL = placeholderImageURL; _animationBaseURL = animationBaseURL; _collectionName = collectionName; _collectionDesc = collectionDesc; _collectionImgURL = collectionImgURL; _collectionExtURL = collectionExtURL; _feeBasisPoints = feeBasisPoints; _feeRecipient = feeRecipient; } function exists(uint256 tokenId) public view returns(bool) { return _exists(tokenId); } function mint(address to, uint256 tokenId, bytes12 data) public { require(isMinterWhitelisted(_msgSender()), "minter not whitelisted"); // only need 20 bytes for the minter address, so might as well use the // other 12 bytes of the slot for something. The minter can pass // whatever they want, I'm thinking some kind of useful context, e.g. a // minter which manages multiple dungeons could use this field for // dungeon Id _tokenMintInfo[tokenId] = packTokenMintInfo(IRelicMinter(_msgSender()), data); _safeMint(to, tokenId); } function tokenURI(uint256 tokenId) public override view returns (string memory) { require(_exists(tokenId), "token doesn't exist"); RelicProperties memory relicProps = getRelicProperties(tokenId); (IRelicMinter relicMinter, bytes12 data) = unpackTokenMintInfo(_tokenMintInfo[tokenId]); uint orderIndex = relicMinter.getTokenOrderIndex(tokenId, data); string memory provenance = relicMinter.getTokenProvenance(tokenId, data); string memory baseImageURL = relicMinter.getImageBaseURL(); if (bytes(baseImageURL).length == 0) { baseImageURL = _placeholderImageURL; } string memory imageURL = getImageURLForToken(tokenId, baseImageURL, orderIndex, provenance); string memory attrs = string(abi.encodePacked( _getAttributes(relicProps), ",{\"trait_type\": \"Order\", \"value\": \"", getOrderSuffix(orderIndex), "\"}", ",{\"trait_type\": \"Provenance\", \"value\": \"", provenance, "\"}", relicMinter.getAdditionalAttributes(tokenId, data) )); return string(abi.encodePacked( "data:application/json;utf8,{" "\"name\": \"", getName(relicProps.relicTypeId, relicProps.materialId, relicProps.materialOffset), "\"," "\"description\": \"Loot dungeon relic\"," "\"image\": \"", imageURL, "\",", "\"external_url\": \"", imageURL,"\",", // TODO: this should be link to asset on TheCrupt "\"attributes\": [", attrs, "]}" )); } function contractURI() public view returns(string memory) { return string(abi.encodePacked( "data:application/json;utf8,{" "\"name\": \"", _collectionName, "\"," "\"description\": \"", _collectionDesc, "\"," "\"image\": \"", _collectionImgURL, "\",", "\"external_link\": \"", _collectionExtURL,"\",", "\"seller_fee_basis_points\": \"", StringsUpgradeable.toString(_feeBasisPoints),"\",", "\"fee_recipient\": \"", StringsUpgradeable.toHexString(uint256(uint160(_feeRecipient)), 20),"\"", "}" )); } function getRelicProperties(uint256 tokenId) public pure returns(RelicProperties memory) { RelicProperties memory props; uint256 relicsPerMaterialForCurrentType = 84; uint256 totalRelicsOfCurrentType; uint256 tokenIdStartForCurrentType; uint256 tokenIdEndForCurrentType; // exclusive while (true) { totalRelicsOfCurrentType = relicsPerMaterialForCurrentType << 2; tokenIdEndForCurrentType = tokenIdStartForCurrentType + totalRelicsOfCurrentType; if (tokenId < tokenIdEndForCurrentType) { break; } ++props.relicTypeId; tokenIdStartForCurrentType = tokenIdEndForCurrentType; relicsPerMaterialForCurrentType <<= 1; } // find out the offset of this token Id into its relic type, that is to // say if it's the Nth Skull, what is the value of N uint256 relicOffset = tokenId - tokenIdStartForCurrentType; // we want materials to be allocated in order from smallest to largest // token Id, so derive material from relic offset props.materialId = relicOffset / relicsPerMaterialForCurrentType; // we want to know that this is the Nth relic of type x material y, for // the token name e.g. Golden Skull #42 props.materialOffset = relicOffset % relicsPerMaterialForCurrentType; // First relic of each material set is greatness 20 then it is decremented per token until it loops at the minimum for its type uint256 minGreatness = getMiniumGreatness(props.relicTypeId); uint256 greatnessRange = 21 - minGreatness; props.greatness = 20 - (props.materialOffset % greatnessRange); // offset the attributes Id with a "random" number per relic + material // combination, so that all relics of a certain material don't start on // N Sun Earth Good Greatness 0 etc uint256 attributesId = relicOffset + uint256(keccak256(abi.encodePacked(props.relicTypeId, props.materialId))); props.alignmentId = (attributesId / greatnessRange) & 3; props.elementId = (attributesId / (greatnessRange * 4)) & 3; props.astralId = (attributesId / (greatnessRange * 16)) & 3; props.poleId = (attributesId / (greatnessRange * 64)) & 3; return props; } function packTokenMintInfo(IRelicMinter relicMinter, bytes12 data) public pure returns(uint256) { return (uint256(uint160(address(relicMinter))) << 96) | uint96(data); } function unpackTokenMintInfo(uint256 mintInfo) public pure returns(IRelicMinter relicMinter, bytes12 data) { relicMinter = IRelicMinter(address(uint160(mintInfo >> 96))); data = bytes12(uint96(mintInfo & 0xffffffffffffffffffffffff)); } function getRelicType(uint256 relicId) public pure returns(string memory) { string[7] memory relics = ["Skull", "Crown", "Medal", "Key", "Dagger", "Gem", "Coin"]; return relics[relicId]; } function getMaterial(uint256 materialId) public pure returns(string memory) { string[4] memory materials = ["Gold", "Ice", "Fire", "Jade"]; return materials[materialId]; } function getName(uint256 relicId, uint256 materialId, uint256 materialOffset) public pure returns(string memory) { return string(abi.encodePacked( getMaterial(materialId), " ", getRelicType(relicId), " #", StringsUpgradeable.toString(materialOffset + 1))); } function getAlignment(uint256 alignmentId) public pure returns(string memory) { string[4] memory alignment = ["Good", "Evil", "Lawful", "Chaos"]; return alignment[alignmentId]; } function getElement(uint256 elementId) public pure returns(string memory) { string[4] memory element = ["Earth", "Wind", "Fire", "Water"]; return element[elementId]; } function getAstral(uint256 astralId) public pure returns(string memory) { string[4] memory astral = ["Earth", "Sun", "Moon", "Stars"]; return astral[astralId]; } function getPole(uint256 poleId) public pure returns(string memory) { string[4] memory pole = ["North", "South", "East", "West"]; return pole[poleId]; } function getMiniumGreatness(uint256 relicId) public pure returns(uint256) { uint256[7] memory greatnesses = [(uint256)(20), 19, 18,17,15,10,0]; return greatnesses[relicId]; } function getOrderSuffix(uint orderId) public pure returns(string memory) { string[16] memory suffixes = [ "of Power", "of Giants", "of Titans", "of Skill", "of Perfection", "of Brilliance", "of Enlightenment", "of Protection", "of Anger", "of Rage", "of Fury", "of Vitriol", "of the Fox", "of Detection", "of Reflection", "of the Twins" ]; return suffixes[orderId]; } // encodes properties in relicProps for use in a URL, such as for animation_url function _getURLParams(RelicProperties memory relicProps) public pure returns(string memory) { return string(abi.encodePacked( "relicType=", getRelicType(relicProps.relicTypeId), "&material=", getMaterial(relicProps.materialId), "&pole=", getPole(relicProps.poleId), "&astral=", getAstral(relicProps.astralId), "&element=", getElement(relicProps.elementId), "&alignment=", getAlignment(relicProps.alignmentId), "&greatness=", StringsUpgradeable.toString(relicProps.greatness) )); } // encodes properties in relicProps for use in the attributes array of token // metadata function _getAttributes(RelicProperties memory relicProps) public pure returns(string memory) { bytes memory str = abi.encodePacked( "{\"trait_type\": \"Relic Type\", \"value\": \"", getRelicType(relicProps.relicTypeId),"\"}," "{\"trait_type\": \"Material\", \"value\": \"", getMaterial(relicProps.materialId),"\"}," "{\"trait_type\": \"Pole\", \"value\": \"", getPole(relicProps.poleId),"\"}," "{\"trait_type\": \"Astral\", \"value\": \"", getAstral(relicProps.astralId),"\"}," "{\"trait_type\": \"Element\", \"value\": \"", getElement(relicProps.elementId),"\"}," "{\"trait_type\": \"Alignment\", \"value\": \"", getAlignment(relicProps.alignmentId),"\"}," ); // had to break this into two calls to encodePacked as it runs out of stack otherwise str = abi.encodePacked(str, "{\"trait_type\": \"Greatness\", \"value\": \"", StringsUpgradeable.toString(relicProps.greatness),"\"}"); return string(str); } function getImageURLPart1(RelicProperties memory props) internal pure returns(string memory) { return string(abi.encodePacked( Strings.toString(props.materialId), "-", Strings.toString(props.relicTypeId), "-" )); } function getImageURLPart2(RelicProperties memory props) internal pure returns(string memory) { return string(abi.encodePacked( Strings.toString(props.astralId), "-", Strings.toString(props.elementId), "-", Strings.toString(props.poleId), "-" )); } function getImageURLPart3(RelicProperties memory props) internal pure returns(string memory) { return string(abi.encodePacked( Strings.toString(props.alignmentId), "-", Strings.toString(props.greatness), "-" )); } function getImageURLForToken(uint256 tokenId, string memory baseURL, uint orderIndex, string memory provenance) internal pure returns(string memory) { RelicProperties memory props = getRelicProperties(tokenId); return string(abi.encodePacked( baseURL, getImageURLPart1(props), Strings.toString(orderIndex), "-", getImageURLPart2(props), getImageURLPart3(props), provenance, ".png" )); } function isMinterWhitelisted(address minter) public view returns(bool) { return _whitelistedMinters[minter]; } function addWhitelistedMinter(address minter) public onlyOwner { require(AddressUpgradeable.isContract(minter), "minter is not a contract"); require(!isMinterWhitelisted(minter), "already whitelisted"); _whitelistedMinters[minter] = true; } function removeWhitelistedMinter(address minter) public onlyOwner { require(isMinterWhitelisted(minter), "not whitelisted"); _whitelistedMinters[minter] = false; } function setPlaceholderImageURL(string memory placeholderImageURL) public onlyOwner { _placeholderImageURL = placeholderImageURL; } function setAnimationBaseURL(string memory animationBaseURL) public onlyOwner { _animationBaseURL = animationBaseURL; } function setCollectionName(string memory collectionName) public onlyOwner { _collectionName = collectionName; } function setCollectionDesc(string memory collectionDesc) public onlyOwner { _collectionDesc = collectionDesc; } function setCollectionImgURL(string memory collectionImgURL) public onlyOwner { _collectionImgURL = collectionImgURL; } function setCollectionExtURL(string memory collectionExtURL) public onlyOwner { _collectionExtURL = collectionExtURL; } function setFeeBasisPoints(uint256 feeBasisPoints) public onlyOwner { _feeBasisPoints = feeBasisPoints; } function setFeeRecipient(address feeRecipient) public onlyOwner { _feeRecipient = feeRecipient; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./ERC1967Proxy.sol"; contract ProxyImplementation is Initializable { bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; modifier onlyAdmin() { require(admin() == msg.sender, "Implementation: caller is not admin"); _; } modifier onlyOwner() { require(owner() == msg.sender, "Implementation: caller is not owner"); _; } function getImplementation() public view returns(address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } function setImplementation(address implementation) public virtual onlyAdmin { require(AddressUpgradeable.isContract(implementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = implementation; } function admin() public view returns(address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } function owner() public view returns(address) { return admin(); } function setAdmin(address newAdmin) public virtual onlyAdmin { require(newAdmin != address(0), "invalid newAdmin address"); _setAdmin(newAdmin); } function renounceAdminPowers() public virtual onlyAdmin { _setAdmin(address(0)); } function _setAdmin(address newAdmin) private { StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "./ContextMixin.sol"; import "./NativeMetaTransactionUpgradeable.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721TradableUpgradeable is ContextMixin, ERC721Upgradeable, NativeMetaTransactionUpgradeable { using SafeMathUpgradeable for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; function __ERC721TradableUpgradeable_init_unchained(address _proxyRegistryAddress) internal initializer { proxyRegistryAddress = _proxyRegistryAddress; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/StorageSlot.sol"; contract Proxy { bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; constructor(address implementation, bytes memory data) payable { StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = implementation; StorageSlot.getAddressSlot(_ADMIN_SLOT).value = msg.sender; if (data.length > 0) { Address.functionDelegateCall(implementation, data, /*errorMessage*/ "init failed"); } } fallback() external payable { _fallback(); } receive() external payable { _fallback(); } function _fallback() private { address implementation = StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; // from OpenZeppelin/contracts assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 // 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 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeMathUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import {EIP712BaseUpgradeable} from "./EIP712BaseUpgradeable.sol"; contract NativeMetaTransactionUpgradeable is EIP712BaseUpgradeable { using SafeMathUpgradeable for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract EIP712BaseUpgradeable is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } }
this relic's number relative to material, e.g. Gold Skull #42
uint256 materialOffset;
10,061,184
[ 1, 2211, 1279, 335, 1807, 1300, 3632, 358, 9390, 16, 425, 18, 75, 18, 611, 1673, 10362, 420, 14856, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 9390, 2335, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; contract PayChecks is Ownable { struct Employee { address employeeAddress; uint16 payGradeId; } string public companyName; uint256 public lastPaymentTime = 0; Employee[] public employees; uint256[] public payGrades; mapping (address => uint32) public employeesId; constructor(string memory _companyName, address[] memory _employeesAddresses, uint16[] memory _payGradeIds, uint256[] memory _payGrades) isNotContract(_employeesAddresses) { require(_employeesAddresses.length == _payGrades.length, "_employeesAddresses and _payGrades must have the same length"); companyName = _companyName; payGrades = _payGrades; for (uint32 i = 0; i < _employeesAddresses.length; i++) { employees.push(Employee(_employeesAddresses[i], _payGradeIds[i])); // Check that pay grade of each employee is in the _payGrades id range require(_payGradeIds[i] < _payGrades.length, "Invalid pay grade id"); address employeeAddress = _employeesAddresses[i]; employeesId[employeeAddress] = i; } } /// @notice check that each employee is not a contract modifier isNotContract(address[] memory _employeesAddresses) { for (uint32 i = 0; i < _employeesAddresses.length; i++) { address employeeAddress = _employeesAddresses[i]; require(employeeAddress != address(0), "Invalid address 0"); uint256 size; assembly { size := extcodesize(employeeAddress) } require(size == 0, "Address cannot be a contract"); } _; } modifier isEmployee(address _address) { require(employees[employeesId[_address]].employeeAddress == _address, "This address does not correspond to any employee"); _; } modifier isValidPayGradeId(uint16 _payGradeId) { require(_payGradeId < payGrades.length, "Invalid pay grade ID"); _; } /// @notice Allows to add employees after contract construction function addEmployee(uint16 _newEmployeePayGradeId, address _newEmployeeAddress) external onlyOwner isValidPayGradeId(_newEmployeePayGradeId) { require(_newEmployeeAddress != address(0x0)); // Check that employee is not already registered require(employees.length == 0 || employees[employeesId[_newEmployeeAddress]].employeeAddress != _newEmployeeAddress, "This address already corresponds to an employee"); // Next employee id is current employees array length employeesId[_newEmployeeAddress] = uint32(employees.length); employees.push(Employee(_newEmployeeAddress, _newEmployeePayGradeId)); } /// @notice pay all employees function runSalaryPayment() external payable onlyOwner { for(uint32 i = 0; i < employees.length; i++) { Employee memory current = employees[i]; payable(current.employeeAddress).transfer(payGrades[current.payGradeId]); } lastPaymentTime = block.timestamp; } /// @notice compute the sum of all the salaries function computeTotalSalarialMass() external view returns (uint256) { uint256 total = 0; for(uint32 i = 0; i < employees.length; i++) { Employee memory current = employees[i]; total += payGrades[current.payGradeId]; } return total; } /// @notice change an employee's pay grade function changePayGradeForEmployee(uint16 _newPayGradeId, address _employeeAddress) external onlyOwner isEmployee(_employeeAddress) isValidPayGradeId(_newPayGradeId){ employees[employeesId[_employeeAddress]].payGradeId = _newPayGradeId; } /// @notice update the amount of a pay grade function updatePayGrade(uint16 _payGradeId, uint256 _newAmount) external onlyOwner isValidPayGradeId(_payGradeId) { payGrades[_payGradeId] = _newAmount; } /// @notice add a new pay grade function addPayGrade(uint16 _amount) external onlyOwner { payGrades.push(_amount); } }
@notice change an employee's pay grade
function changePayGradeForEmployee(uint16 _newPayGradeId, address _employeeAddress) external onlyOwner isEmployee(_employeeAddress) isValidPayGradeId(_newPayGradeId){ employees[employeesId[_employeeAddress]].payGradeId = _newPayGradeId; }
13,043,020
[ 1, 3427, 392, 24539, 1340, 1807, 8843, 7324, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2549, 9148, 14571, 323, 1290, 41, 27520, 12, 11890, 2313, 389, 2704, 9148, 14571, 323, 548, 16, 1758, 389, 351, 2817, 1340, 1887, 13, 3903, 1338, 5541, 353, 41, 27520, 24899, 351, 2817, 1340, 1887, 13, 4908, 9148, 14571, 323, 548, 24899, 2704, 9148, 14571, 323, 548, 15329, 203, 3639, 24539, 25521, 63, 351, 2817, 25521, 548, 63, 67, 351, 2817, 1340, 1887, 65, 8009, 10239, 14571, 323, 548, 273, 389, 2704, 9148, 14571, 323, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./libraries/SafeERC20.sol"; import "./libraries/SafeMath.sol"; import "./types/FloorAccessControlled.sol"; contract AlphaFloorMigration is FloorAccessControlled { using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 public FLOOR; IERC20 public aFLOOR; bool public isInitialized; modifier onlyInitialized() { require(isInitialized, "not initialized"); _; } modifier notInitialized() { require(!isInitialized, "already initialized" ); _; } constructor( address _authority ) FloorAccessControlled(IFloorAuthority(_authority)) {} function initialize ( address _FLOOR, address _aFLOOR ) public notInitialized() onlyGovernor { require(_FLOOR != address(0), "_FLOOR: Zero address"); require(_aFLOOR != address(0), "_aFLOOR: Zero address"); FLOOR = IERC20(_FLOOR); aFLOOR = IERC20(_aFLOOR); isInitialized = true; } /** * @notice swaps aFLOOR for FLOOR * @param _amount uint256 */ function migrate(uint256 _amount) external onlyInitialized() { require( aFLOOR.balanceOf(msg.sender) >= _amount, "amount above user balance" ); aFLOOR.safeTransferFrom(msg.sender, address(this), _amount); FLOOR.transfer(msg.sender, _amount); } /** * @notice governor can withdraw any remaining FLOOR. */ function withdraw() external onlyGovernor { uint256 amount = FLOOR.balanceOf(address(this)); FLOOR.transfer(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.7.5; import {IERC20} from "../interfaces/IERC20.sol"; /// @notice Safe IERC20 and ETH transfer library that safely handles missing return values. /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/TransferHelper.sol) /// Taken from Solmate library SafeERC20 { function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED"); } function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.transfer.selector, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED"); } function safeApprove( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.approve.selector, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED"); } function safeTransferETH(address to, uint256 amount) internal { (bool success, ) = to.call{value: amount}(new bytes(0)); require(success, "ETH_TRANSFER_FAILED"); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.5; // TODO(zx): Replace all instances of SafeMath with OZ implementation library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // Only used in the BondingCalculator.sol function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.7.5; import "../interfaces/IFloorAuthority.sol"; abstract contract FloorAccessControlled { /* ========== EVENTS ========== */ event AuthorityUpdated(IFloorAuthority indexed authority); string UNAUTHORIZED = "UNAUTHORIZED"; // save gas /* ========== STATE VARIABLES ========== */ IFloorAuthority public authority; /* ========== Constructor ========== */ constructor(IFloorAuthority _authority) { authority = _authority; emit AuthorityUpdated(_authority); } /* ========== MODIFIERS ========== */ modifier onlyGovernor() { require(msg.sender == authority.governor(), UNAUTHORIZED); _; } modifier onlyGuardian() { require(msg.sender == authority.guardian(), UNAUTHORIZED); _; } modifier onlyPolicy() { require(msg.sender == authority.policy(), UNAUTHORIZED); _; } modifier onlyVault() { require(msg.sender == authority.vault(), UNAUTHORIZED); _; } /* ========== GOV ONLY ========== */ function setAuthority(IFloorAuthority _newAuthority) external onlyGovernor { authority = _newAuthority; emit AuthorityUpdated(_newAuthority); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.7.5; 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: AGPL-3.0-or-later pragma solidity >=0.7.5; interface IFloorAuthority { /* ========== EVENTS ========== */ event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately); event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately); event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GovernorPulled(address indexed from, address indexed to); event GuardianPulled(address indexed from, address indexed to); event PolicyPulled(address indexed from, address indexed to); event VaultPulled(address indexed from, address indexed to); /* ========== VIEW ========== */ function governor() external view returns (address); function guardian() external view returns (address); function policy() external view returns (address); function vault() external view returns (address); }
* @notice governor can withdraw any remaining FLOOR./
function withdraw() external onlyGovernor { uint256 amount = FLOOR.balanceOf(address(this)); FLOOR.transfer(msg.sender, amount); }
427,982
[ 1, 75, 1643, 29561, 848, 598, 9446, 1281, 4463, 478, 1502, 916, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 3903, 1338, 43, 1643, 29561, 288, 203, 3639, 2254, 5034, 3844, 273, 478, 1502, 916, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 478, 1502, 916, 18, 13866, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x6b17D9a535e7Dcd46E7305c7AE9c5380E019f10b/sources/OLIVDelegator.sol
* @notice Delegates execution to an implementation contract @dev It returns to the external caller whatever the implementation returns or forwards reverts/ delegate all other functions to current implementation
function () external payable { require(msg.value == 0,"OLIVDelegator:fallback: cannot send value to fallback"); delegateAndReturn(); }
3,343,229
[ 1, 15608, 815, 4588, 358, 392, 4471, 6835, 225, 2597, 1135, 358, 326, 3903, 4894, 15098, 326, 4471, 1135, 578, 24578, 15226, 87, 19, 7152, 777, 1308, 4186, 358, 783, 4471, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 1832, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 374, 10837, 1741, 8188, 15608, 639, 30, 16471, 30, 2780, 1366, 460, 358, 5922, 8863, 203, 203, 3639, 7152, 1876, 990, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xeFC812A74Ea5dB6913E676F20fef66b22FC66432/sources/RedemptionPoolAlloyx.sol
Constants GRO has 18 decimals TOKENS Modifiers
contract RedemptionPoolAlloyX is Ownable { using SafeERC20 for IERC20; uint256 public constant DEADLINE = 1698251639; uint256 internal constant PRECISION = 1e18; address internal constant DAO = address(0x359F4fe841f246a095a82cb26F5819E10a91fe0d); IERC20 public constant GRO = IERC20(0x3Ec8798B81485A254928B70CDA1cf0A2BB0B74D7); IERC20 public constant ALLOYX = IERC20(0x4562724cAa90d866c35855b9baF71E5125CAD5B6); pragma solidity 0.8.20; import {Ownable} from "Ownable.sol"; import {IERC20} from "IERC20.sol"; import {SafeERC20} from "SafeERC20.sol"; import {RedemptionErrors} from "Errors.sol"; modifier onlyBeforeDeadline() { if (block.timestamp > DEADLINE) { revert RedemptionErrors.DeadlineExceeded(); } _; } modifier onlyBeforeDeadline() { if (block.timestamp > DEADLINE) { revert RedemptionErrors.DeadlineExceeded(); } _; } modifier onlyAfterDeadline() { if (block.timestamp <= DEADLINE) { revert RedemptionErrors.ClaimsPeriodNotStarted(); } _; } mapping(address => uint256) private _userGROBalance; mapping(address => uint256) private _userClaims; uint256 public totalGRO; uint256 public totalAlloyxDeposited; uint256 public totalAlloyxWithdrawn; event TotalGRODeposited(uint256 amount); event Withdraw(address indexed user, uint256 amount); event Claim(address indexed user, uint256 amount); event AlloyxDeposit(uint256 amount); modifier onlyAfterDeadline() { if (block.timestamp <= DEADLINE) { revert RedemptionErrors.ClaimsPeriodNotStarted(); } _; } mapping(address => uint256) private _userGROBalance; mapping(address => uint256) private _userClaims; uint256 public totalGRO; uint256 public totalAlloyxDeposited; uint256 public totalAlloyxWithdrawn; event TotalGRODeposited(uint256 amount); event Withdraw(address indexed user, uint256 amount); event Claim(address indexed user, uint256 amount); event AlloyxDeposit(uint256 amount); event Deposit(address indexed user, uint256 amount); constructor() { transferOwnership(DAO); } function getDURAPerGRO() public view returns (uint256) { return (totalAlloyxDeposited * PRECISION) / totalGRO; } function getDuraAvailable(address user) public view returns (uint256) { return (_userGROBalance[user] * totalAlloyxDeposited) / totalGRO - _userClaims[user]; } function getUserBalance(address user) external view returns (uint256) { return _userGROBalance[user]; } function getUserClaim(address user) external view returns (uint256) { return _userClaims[user]; } function getDeadline() external pure returns (uint256) { return DEADLINE; } function deposit(uint256 _amount) external onlyBeforeDeadline { GRO.safeTransferFrom(msg.sender, address(this), _amount); _userGROBalance[msg.sender] += _amount; totalGRO += _amount; emit Deposit(msg.sender, _amount); emit TotalGRODeposited(totalGRO); } function withdraw(uint256 _amount) external onlyBeforeDeadline { if (_userGROBalance[msg.sender] < _amount) { revert RedemptionErrors.InsufficientBalance(); } _userGROBalance[msg.sender] -= _amount; totalGRO -= _amount; GRO.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } function withdraw(uint256 _amount) external onlyBeforeDeadline { if (_userGROBalance[msg.sender] < _amount) { revert RedemptionErrors.InsufficientBalance(); } _userGROBalance[msg.sender] -= _amount; totalGRO -= _amount; GRO.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } function claim(uint256 _amount) external onlyAfterDeadline { if (_amount == 0) revert RedemptionErrors.InvalidClaim(); uint256 userClaim = getDuraAvailable(msg.sender); if (_amount > userClaim) { revert RedemptionErrors.InvalidClaim(); } totalAlloyxWithdrawn += _amount; ALLOYX.safeTransfer(msg.sender, _amount); emit Claim(msg.sender, _amount); } function claim(uint256 _amount) external onlyAfterDeadline { if (_amount == 0) revert RedemptionErrors.InvalidClaim(); uint256 userClaim = getDuraAvailable(msg.sender); if (_amount > userClaim) { revert RedemptionErrors.InvalidClaim(); } totalAlloyxWithdrawn += _amount; ALLOYX.safeTransfer(msg.sender, _amount); emit Claim(msg.sender, _amount); } _userClaims[msg.sender] += _amount; function depositAlloy(uint256 _amount) external onlyOwner { ALLOYX.safeTransferFrom(msg.sender, address(this), _amount); totalAlloyxDeposited += _amount; emit AlloyxDeposit(totalAlloyxDeposited); } function sweep(address _token) external onlyOwner onlyBeforeDeadline { if (_token == address(GRO)) revert RedemptionErrors.NoSweepGro(); IERC20(_token).safeTransfer(owner(), IERC20(_token).balanceOf(address(this))); } }
3,583,939
[ 1, 2918, 1171, 9079, 611, 1457, 711, 6549, 15105, 14275, 55, 21394, 3431, 3383, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 868, 19117, 375, 2864, 1067, 2466, 60, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 203, 565, 2254, 5034, 1071, 5381, 2030, 1880, 5997, 273, 2872, 10689, 2947, 2313, 5520, 31, 203, 565, 2254, 5034, 2713, 5381, 7071, 26913, 273, 404, 73, 2643, 31, 203, 565, 1758, 2713, 5381, 463, 20463, 273, 1758, 12, 20, 92, 4763, 29, 42, 24, 3030, 5193, 21, 74, 3247, 26, 69, 5908, 25, 69, 11149, 7358, 5558, 42, 8204, 3657, 41, 2163, 69, 12416, 3030, 20, 72, 1769, 203, 203, 565, 467, 654, 39, 3462, 1071, 5381, 611, 1457, 273, 467, 654, 39, 3462, 12, 20, 92, 23, 23057, 28, 7235, 28, 38, 28, 3461, 7140, 37, 2947, 7616, 6030, 38, 7301, 39, 9793, 21, 8522, 20, 37, 22, 9676, 20, 38, 5608, 40, 27, 1769, 203, 565, 467, 654, 39, 3462, 1071, 5381, 7981, 1502, 61, 60, 273, 467, 654, 39, 3462, 12, 20, 92, 24, 4313, 5324, 3247, 71, 37, 69, 9349, 72, 5292, 26, 71, 4763, 28, 2539, 70, 29, 12124, 42, 11212, 41, 13757, 25, 39, 1880, 25, 38, 26, 1769, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3462, 31, 203, 5666, 288, 5460, 429, 97, 628, 315, 5460, 429, 18, 18281, 14432, 203, 5666, 288, 45, 654, 39, 3462, 97, 628, 315, 45, 654, 39, 3462, 18, 18281, 14432, 203, 5666, 288, 9890, 654, 39, 3462, 97, 628, 315, 9890, 654, 39, 3462, 18, 18281, 14432, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2019-12-19 */ // hevm: flattened sources of src/Redeemer.sol pragma solidity =0.5.11 >0.4.13 >0.4.20 >=0.4.23 >=0.5.0 <0.6.0 >=0.5.5 <0.6.0 >=0.5.11 <0.6.0; ////// lib/dpass/lib/openzeppelin-contracts/src/GSN/Context.sol /* pragma solidity ^0.5.0; */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract 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; } } ////// lib/dpass/lib/openzeppelin-contracts/src/math/SafeMath.sol /* pragma solidity ^0.5.0; */ /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } ////// lib/dpass/lib/openzeppelin-contracts/src/drafts/Counters.sol /* pragma solidity ^0.5.0; */ /* import "../math/SafeMath.sol"; */ /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/IERC165.sol /* pragma solidity ^0.5.0; */ /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/ERC165.sol /* pragma solidity ^0.5.0; */ /* import "./IERC165.sol"; */ /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () 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; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../introspection/IERC165.sol"; */ /** * @dev Required interface of an ERC721 compliant contract. */ 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; } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Receiver.sol /* pragma solidity ^0.5.0; */ /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ 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); } ////// lib/dpass/lib/openzeppelin-contracts/src/utils/Address.sol /* pragma solidity ^0.5.5; */ /** * @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"); } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721.sol"; */ /* import "./IERC721Receiver.sol"; */ /* import "../../math/SafeMath.sol"; */ /* import "../../utils/Address.sol"; */ /* import "../../drafts/Counters.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ 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 function 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; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); 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 (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS _tokenApprovals[tokenId] = address(0); } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721Enumerable.sol"; */ /* import "./ERC721.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * 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 Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @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 { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_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 { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (block.gaslimit != lastTokenIndex) { //injected CONTRACT AFFECTED BY MINERS uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ 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); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./ERC721.sol"; */ /* import "./IERC721Metadata.sol"; */ /* import "../../introspection/ERC165.sol"; */ contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // 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 an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @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 (block.gaslimit != 0) { //injected CONTRACT AFFECTED BY MINERS delete _tokenURIs[tokenId]; } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Full.sol /* pragma solidity ^0.5.0; */ /* import "./ERC721.sol"; */ /* import "./ERC721Enumerable.sol"; */ /* import "./ERC721Metadata.sol"; */ /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } ////// lib/ds-auth/src/auth.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (block.coinbase == owner) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } ////// lib/dpass/src/Dpass.sol /* pragma solidity ^0.5.11; */ // /** // * How to use dapp and openzeppelin-solidity https://github.com/dapphub/dapp/issues/70 // * ERC-721 standart: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md // * // */ /* import "ds-auth/auth.sol"; */ /* import "openzeppelin-contracts/token/ERC721/ERC721Full.sol"; */ contract DpassEvents { event LogConfigChange(bytes32 what, bytes32 value1, bytes32 value2); event LogCustodianChanged(uint tokenId, address custodian); event LogDiamondAttributesHashChange(uint indexed tokenId, bytes8 hashAlgorithm); event LogDiamondMinted( address owner, uint indexed tokenId, bytes3 issuer, bytes16 report, bytes8 state ); event LogRedeem(uint indexed tokenId); event LogSale(uint indexed tokenId); event LogStateChanged(uint indexed tokenId, bytes32 state); } contract Dpass is DSAuth, ERC721Full, DpassEvents { string private _name = "Diamond Passport"; string private _symbol = "Dpass"; struct Diamond { bytes3 issuer; bytes16 report; bytes8 state; bytes20 cccc; uint24 carat; bytes8 currentHashingAlgorithm; // Current hashing algorithm to check in the proof mapping } Diamond[] diamonds; // List of Dpasses mapping(uint => address) public custodian; // custodian that holds a Dpass token mapping (uint => mapping(bytes32 => bytes32)) public proof; // Prof of attributes integrity [tokenId][hashingAlgorithm] => hash mapping (bytes32 => mapping (bytes32 => bool)) diamondIndex; // List of dpasses by issuer and report number [issuer][number] mapping (uint256 => uint256) public recreated; // List of recreated tokens. old tokenId => new tokenId mapping(bytes32 => mapping(bytes32 => bool)) public canTransit; // List of state transition rules in format from => to = true/false mapping(bytes32 => bool) public ccccs; constructor () public ERC721Full(_name, _symbol) { // Create dummy diamond to start real diamond minting from 1 Diamond memory _diamond = Diamond({ issuer: "Slf", report: "0", state: "invalid", cccc: "BR,IF,D,0001", carat: 1, currentHashingAlgorithm: "" }); diamonds.push(_diamond); _mint(address(this), 0); // Transition rules canTransit["valid"]["invalid"] = true; canTransit["valid"]["removed"] = true; canTransit["valid"]["sale"] = true; canTransit["valid"]["redeemed"] = true; canTransit["sale"]["valid"] = true; canTransit["sale"]["invalid"] = true; canTransit["sale"]["removed"] = true; } modifier onlyOwnerOf(uint _tokenId) { require(ownerOf(_tokenId) == msg.sender, "dpass-access-denied"); _; } modifier onlyApproved(uint _tokenId) { require( ownerOf(_tokenId) == msg.sender || isApprovedForAll(ownerOf(_tokenId), msg.sender) || getApproved(_tokenId) == msg.sender , "dpass-access-denied"); _; } modifier ifExist(uint _tokenId) { require(_exists(_tokenId), "dpass-diamond-does-not-exist"); _; } modifier onlyValid(uint _tokenId) { // TODO: DRY, _exists already check require(_exists(_tokenId), "dpass-diamond-does-not-exist"); Diamond storage _diamond = diamonds[_tokenId]; require(_diamond.state != "invalid", "dpass-invalid-diamond"); _; } /** * @dev Custom accessor to create a unique token * @param _to address of diamond owner * @param _issuer string the issuer agency name * @param _report string the issuer agency unique Nr. * @param _state diamond state, "sale" is the init state * @param _cccc bytes32 cut, clarity, color, and carat class of diamond * @param _carat uint24 carat of diamond with 2 decimals precision * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) * @param _custodian the custodian of minted dpass * @return Return Diamond tokenId of the diamonds list */ function mintDiamondTo( address _to, address _custodian, bytes3 _issuer, bytes16 _report, bytes8 _state, bytes20 _cccc, uint24 _carat, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth returns(uint) { require(ccccs[_cccc], "dpass-wrong-cccc"); _addToDiamondIndex(_issuer, _report); Diamond memory _diamond = Diamond({ issuer: _issuer, report: _report, state: _state, cccc: _cccc, carat: _carat, currentHashingAlgorithm: _currentHashingAlgorithm }); uint _tokenId = diamonds.push(_diamond) - 1; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; custodian[_tokenId] = _custodian; _mint(_to, _tokenId); emit LogDiamondMinted(_to, _tokenId, _issuer, _report, _state); return _tokenId; } /** * @dev Update _tokenId attributes * @param _attributesHash new attibutes hash value * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) */ function updateAttributesHash( uint _tokenId, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth onlyValid(_tokenId) { Diamond storage _diamond = diamonds[_tokenId]; _diamond.currentHashingAlgorithm = _currentHashingAlgorithm; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; emit LogDiamondAttributesHashChange(_tokenId, _currentHashingAlgorithm); } /** * @dev Link old and the same new dpass */ function linkOldToNewToken(uint _tokenId, uint _newTokenId) public auth { require(_exists(_tokenId), "dpass-old-diamond-doesnt-exist"); require(_exists(_newTokenId), "dpass-new-diamond-doesnt-exist"); recreated[_tokenId] = _newTokenId; } /** * @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 and not invalid token * @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 onlyValid(_tokenId) { _checkTransfer(_tokenId); super.transferFrom(_from, _to, _tokenId); } /* * @dev Check if transferPossible */ function _checkTransfer(uint256 _tokenId) internal view { bytes32 state = diamonds[_tokenId].state; require(state != "removed", "dpass-token-removed"); require(state != "invalid", "dpass-token-deleted"); } /** * @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 */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { _checkTransfer(_tokenId); super.safeTransferFrom(_from, _to, _tokenId); } /* * @dev Returns the current state of diamond */ function getState(uint _tokenId) public view ifExist(_tokenId) returns (bytes32) { return diamonds[_tokenId].state; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamondInfo(uint _tokenId) public view ifExist(_tokenId) returns ( address[2] memory ownerCustodian, bytes32[6] memory attrs, uint24 carat_ ) { Diamond storage _diamond = diamonds[_tokenId]; bytes32 attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; ownerCustodian[0] = ownerOf(_tokenId); ownerCustodian[1] = custodian[_tokenId]; attrs[0] = _diamond.issuer; attrs[1] = _diamond.report; attrs[2] = _diamond.state; attrs[3] = _diamond.cccc; attrs[4] = attributesHash; attrs[5] = _diamond.currentHashingAlgorithm; carat_ = _diamond.carat; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamond(uint _tokenId) public view ifExist(_tokenId) returns ( bytes3 issuer, bytes16 report, bytes8 state, bytes20 cccc, uint24 carat, bytes32 attributesHash ) { Diamond storage _diamond = diamonds[_tokenId]; attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; return ( _diamond.issuer, _diamond.report, _diamond.state, _diamond.cccc, _diamond.carat, attributesHash ); } /** * @dev Gets the Diamond issuer and it unique nr at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Issuer and unique Nr. a specific diamond */ function getDiamondIssuerAndReport(uint _tokenId) public view ifExist(_tokenId) returns(bytes32, bytes32) { Diamond storage _diamond = diamonds[_tokenId]; return (_diamond.issuer, _diamond.report); } /** * @dev Set cccc values that are allowed to be entered for diamonds * @param _cccc bytes32 cccc value that will be enabled/disabled * @param _allowed bool allow or disallow cccc */ function setCccc(bytes32 _cccc, bool _allowed) public auth { ccccs[_cccc] = _allowed; emit LogConfigChange("cccc", _cccc, _allowed ? bytes32("1") : bytes32("0")); } /** * @dev Set new custodian for dpass */ function setCustodian(uint _tokenId, address _newCustodian) public auth { require(_newCustodian != address(0), "dpass-wrong-address"); custodian[_tokenId] = _newCustodian; emit LogCustodianChanged(_tokenId, _newCustodian); } /** * @dev Get the custodian of Dpass. */ function getCustodian(uint _tokenId) public view returns(address) { return custodian[_tokenId]; } /** * @dev Enable transition _from -> _to state */ function enableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = true; emit LogConfigChange("canTransit", _from, _to); } /** * @dev Disable transition _from -> _to state */ function disableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = false; emit LogConfigChange("canNotTransit", _from, _to); } /** * @dev Set Diamond sale state * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setSaleState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("sale", _tokenId); emit LogSale(_tokenId); } /** * @dev Set Diamond invalid state * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setInvalidState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("invalid", _tokenId); _removeDiamondFromIndex(_tokenId); } /** * @dev Make diamond state as redeemed, change owner to contract owner * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function redeem(uint _tokenId) public ifExist(_tokenId) onlyOwnerOf(_tokenId) { _setState("redeemed", _tokenId); _removeDiamondFromIndex(_tokenId); emit LogRedeem(_tokenId); } /** * @dev Change diamond state. * @param _newState new token state * @param _tokenId represent the index of diamond */ function setState(bytes8 _newState, uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState(_newState, _tokenId); } // Private functions /** * @dev Validate transiton from currentState to newState. Revert on invalid transition * @param _currentState current diamond state * @param _newState new diamond state */ function _validateStateTransitionTo(bytes8 _currentState, bytes8 _newState) internal view { require(_currentState != _newState, "dpass-already-in-that-state"); require(canTransit[_currentState][_newState], "dpass-transition-now-allowed"); } /** * @dev Add Issuer and report with validation to uniqueness. Revert on invalid existance * @param _issuer issuer like GIA * @param _report issuer unique nr. */ function _addToDiamondIndex(bytes32 _issuer, bytes32 _report) internal { require(!diamondIndex[_issuer][_report], "dpass-issuer-report-not-unique"); diamondIndex[_issuer][_report] = true; } function _removeDiamondFromIndex(uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; diamondIndex[_diamond.issuer][_diamond.report] = false; } /** * @dev Change diamond state with logging. Revert on invalid transition * @param _newState new token state * @param _tokenId represent the index of diamond */ function _setState(bytes8 _newState, uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; _validateStateTransitionTo(_diamond.state, _newState); _diamond.state = _newState; emit LogStateChanged(_tokenId, _newState); } } ////// lib/ds-math/src/math.sol /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >0.4.13; */ contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } ////// lib/ds-note/src/note.sol /// note.sol -- the `note' modifier, for logging calls as events // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue } emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); _; } } ////// lib/ds-stop/src/stop.sol /// stop.sol -- mixin for enable/disable functionality // Copyright (C) 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "ds-auth/auth.sol"; */ /* import "ds-note/note.sol"; */ contract DSStop is DSNote, DSAuth { bool public stopped; modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function stop() public auth note { stopped = true; } function start() public auth note { stopped = false; } } ////// lib/ds-token/lib/erc20/src/erc20.sol /// erc20.sol -- API for the ERC20 token standard // See <https://github.com/ethereum/EIPs/issues/20>. // This file likely does not meet the threshold of originality // required for copyright to apply. As a result, this is free and // unencumbered software belonging to the public domain. /* pragma solidity >0.4.20; */ contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } ////// lib/ds-token/src/base.sol /// base.sol -- basic ERC20 implementation // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "erc20/erc20.sol"; */ /* import "ds-math/math.sol"; */ contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } } ////// lib/ds-token/src/token.sol /// token.sol -- ERC20 implementation with minting and burning // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "ds-stop/stop.sol"; */ /* import "./base.sol"; */ contract DSToken is DSTokenBase(0), DSStop { bytes32 public symbol; uint256 public decimals = 18; // standard token precision. override to customize constructor(bytes32 symbol_) public { symbol = symbol_; } event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function push(address dst, uint wad) public { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) public { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) public { transferFrom(src, dst, wad); } function mint(uint wad) public { mint(msg.sender, wad); } function burn(uint wad) public { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { _balances[guy] = add(_balances[guy], wad); _supply = add(_supply, wad); emit Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) { require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad); } require(_balances[guy] >= wad, "ds-token-insufficient-balance"); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); } // Optional token name bytes32 public name = ""; function setName(bytes32 name_) public auth { name = name_; } } ////// src/Wallet.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /** * @dev Interface to ERC20 tokens. */ contract TrustedErc20Wallet { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } /** * @dev Interface to ERC721 tokens. */ contract TrustedErci721Wallet { function balanceOf(address guy) public view returns (uint); function ownerOf(uint256 tokenId) public view returns (address); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address); function setApprovalForAll(address to, bool approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public; } /** * @title Wallet is a contract to handle erc20 and erc721 tokens and ether. * @dev This token is used to store and transfer tokens that were paid as fee by users. */ contract Wallet is DSAuth, DSStop, DSMath { event LogTransferEth(address src, address dst, uint256 amount); address public eth = address(0xee); bytes32 public name = "Wal"; // set human readable name for contract bytes32 public symbol = "Wal"; // set human readable name for contract function () external payable { } function transfer(address token, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, address(this), dst, amt); } function transferFrom(address token, address src, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, src, dst, amt); } function totalSupply(address token) public view returns (uint){ if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-total-supply-for-ether"); } else { return TrustedErc20Wallet(token).totalSupply(); } } function balanceOf(address token, address src) public view returns (uint) { if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return src.balance; } else { return TrustedErc20Wallet(token).balanceOf(src); } } function allowance(address token, address src, address guy) public view returns (uint) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-allowance-for-ether"); } else { return TrustedErc20Wallet(token).allowance(src, guy); } } function approve(address token, address guy, uint wad) public auth returns (bool) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-can-not-approve-ether"); } else { return TrustedErc20Wallet(token).approve(guy, wad); } } function balanceOf721(address token, address guy) public view returns (uint) { return TrustedErci721Wallet(token).balanceOf(guy); } function ownerOf721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).ownerOf(tokenId); } function approve721(address token, address to, uint256 tokenId) public { TrustedErci721Wallet(token).approve(to, tokenId); } function getApproved721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).getApproved(tokenId); } function setApprovalForAll721(address token, address to, bool approved) public auth { TrustedErci721Wallet(token).setApprovalForAll(to, approved); } function isApprovedForAll721(address token, address owner, address operator) public view returns (bool) { return TrustedErci721Wallet(token).isApprovedForAll(owner, operator); } function transferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).transferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId, bytes memory _data) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId, _data); } function transfer721(address token, address to, uint tokenId) public auth { TrustedErci721Wallet(token).transferFrom(address(this), to, tokenId); } /** * @dev send token or ether to destination */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ TrustedErc20Wallet erc20 = TrustedErc20Wallet(token); if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.timestamp > 0) erc20.transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Liquidity.sol /* pragma solidity ^0.5.11; */ /* import "./Wallet.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ contract Liquidity is Wallet { bytes32 public name = "Liq"; // set human readable name for contract bytes32 public symbol = "Liq"; // set human readable name for contract function burn(address dpt, address burner, uint256 burnValue) public auth { transfer(dpt, address(uint160(address(burner))), burnValue); } } ////// src/SimpleAssetManagement.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "dpass/Dpass.sol"; */ /** * @dev Contract to get ETH/USD price */ contract TrustedFeedLike { function peek() external view returns (bytes32, bool); } /** * @dev ExchangeContract to get buyPrice from */ contract TrustedDiamondExchangeAsm { function buyPrice(address token_, address owner_, uint256 tokenId_) external view returns (uint); } /** * @title Contract to handle diamond assets */ contract SimpleAssetManagement is DSAuth { event LogAudit(address sender, address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterwal_); event LogConfigChange(address sender, bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 amount); event LogBasePrice(address sender_, address token_, uint256 tokenId_, uint256 price_); event LogCdcValue(uint256 totalCdcV, uint256 cdcValue, address token); event LogCdcPurchaseValue(uint256 totalCdcPurchaseV, uint256 cdcPurchaseValue, address token); event LogDcdcValue(uint256 totalDcdcV, uint256 ddcValue, address token); event LogDcdcCustodianValue(uint256 totalDcdcCustV, uint256 dcdcCustV, address dcdc, address custodian); event LogDcdcTotalCustodianValue(uint256 totalDcdcCustV, uint256 totalDcdcV, address custodian); event LogDpassValue(uint256 totalDpassCustV, uint256 totalDpassV, address custodian); event LogForceUpdateCollateralDpass(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); event LogForceUpdateCollateralDcdc(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); mapping( address => mapping( uint => uint)) public basePrice; // the base price used for collateral valuation mapping(address => bool) public custodians; // returns true for custodians mapping(address => uint) // total base currency value of custodians collaterals public totalDpassCustV; mapping(address => uint) private rate; // current rate of a token in base currency mapping(address => uint) public cdcV; // base currency value of cdc token mapping(address => uint) public dcdcV; // base currency value of dcdc token mapping(address => uint) public totalDcdcCustV; // total value of all dcdcs at custodian mapping( address => mapping( address => uint)) public dcdcCustV; // dcdcCustV[dcdc][custodian] value of dcdc at custodian mapping(address => bool) public payTokens; // returns true for tokens allowed to make payment to custodians with mapping(address => bool) public dpasses; // returns true for dpass tokens allowed in this contract mapping(address => bool) public dcdcs; // returns true for tokens representing cdc assets (without gia number) that are allowed in this contract mapping(address => bool) public cdcs; // returns true for cdc tokens allowed in this contract mapping(address => uint) public decimals; // stores decimals for each ERC20 token eg: 1000000000000000000 denotes 18 decimal precision mapping(address => bool) public decimalsSet; // stores decimals for each ERC20 token mapping(address => address) public priceFeed; // price feed address for token mapping(address => uint) public tokenPurchaseRate; // the average purchase rate of a token. This is the ... // ... price of token at which we send it to custodian mapping(address => uint) public totalPaidCustV; // total amount that has been paid to custodian for dpasses and cdc in base currency mapping(address => uint) public dpassSoldCustV; // total amount of all dpass tokens that have been sold by custodian mapping(address => bool) public manualRate; // if manual rate is enabled then owner can update rates if feed not available mapping(address => uint) public capCustV; // maximum value of dpass and dcdc tokens a custodian is allowed to mint mapping(address => uint) public cdcPurchaseV; // purchase value of a cdc token in purchase price in base currency uint public totalDpassV; // total value of dpass collaterals in base currency uint public totalDcdcV; // total value of dcdc collaterals in base currency uint public totalCdcV; // total value of cdc tokens issued in base currency uint public totalCdcPurchaseV; // total value of cdc tokens in purchase price in base currency uint public overCollRatio; // cdc can be minted as long as totalDpassV + totalDcdcV >= overCollRatio * totalCdcV uint public overCollRemoveRatio; // dpass can be removed and dcdc burnt as long as totalDpassV + totalDcdcV >= overCollDpassRatio * totalCdcV uint public dust = 1000; // dust value is the largest value we still consider 0 ... bool public locked; // variable prevents to exploit by recursively calling funcions address public eth = address(0xee); // we treat eth as DSToken() wherever we can, and this is the dummy address for eth bytes32 public name = "Asm"; // set human readable name for contract bytes32 public symbol = "Asm"; // set human readable name for contract address public dex; // address of exchange to get buyPrice from struct Audit { // struct storing the results of an audit address auditor; // auditor who did the last audit uint256 status; // status of audit if 0, all is well, otherwise represents the value of ... // diamonds that there are problems with bytes32 descriptionHash; // hash of the description file that describes the last audit in detail. ... // ... Auditors must have a detailed description of all the findings they had at ... // ... custodian, and are legally fully responsible for their documents. bytes32 descriptionUrl; // url of the description file that details the results of the audit. File should be digitally signed. And the files total content should be hashed with keccak256() to make sure unmutability. uint nextAuditBefore; // proposed time of next audit. The audit should be at least at every 3 months. } mapping(address => Audit) public audit; // containing the last audit reports for all custodians. uint32 public auditInterval = 1776000; // represents 3 months of audit interwal in which an audit is mandatory for custodian. /** * @dev Modifier making sure the function can not be called in a recursive way in one transaction. */ modifier nonReentrant { require(!locked, "asm-reentrancy-detected"); locked = true; _; locked = false; } //-----------included-from-ds-math---------------------------------begin uint constant WAD = 10 ** 18; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end /** * @dev Set configuration variables of asset managment contract. * @param what_ bytes32 tells to function what to set. * @param value_ bytes32 setter variable. Its meaning is dependent on what_. * @param value1_ bytes32 setter variable. Its meaning is dependent on what_. * @param value2_ bytes32 setter variable. Its meaning is dependent on what_. * */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require(payTokens[token] || cdcs[token] || dcdcs[token], "asm-token-not-allowed-rate"); require(value > 0, "asm-rate-must-be-gt-0"); rate[token] = value; } else if (blockhash(block.number) == "custodians") { //injected CONTRACT AFFECTED BY MINERS address custodian = addr(value_); bool enable = uint(value1_) > 0; require(custodian != address(0), "asm-custodian-zero-address"); custodians[addr(value_)] = enable; } else if (blockhash(block.number) == "overCollRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRatio = uint(value_); require(overCollRatio >= 1 ether, "asm-system-must-be-overcollaterized"); _requireSystemCollaterized(); } else if (blockhash(block.number) == "overCollRemoveRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRemoveRatio = uint(value_); require(overCollRemoveRatio >= 1 ether, "asm-must-be-gt-1-ether"); require(overCollRemoveRatio <= overCollRatio, "asm-must-be-lt-overcollratio"); _requireSystemRemoveCollaterized(); } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(addr(value1_) != address(address(0x0)), "asm-wrong-pricefeed-address"); require(addr(value_) != address(address(0x0)), "asm-wrong-token-address"); priceFeed[addr(value_)] = addr(value1_); } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint decimal = uint256(value1_); require(token != address(0x0), "asm-wrong-address"); decimals[token] = 10 ** decimal; decimalsSet[token] = true; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); bool enable = uint(value1_) > 0; require(token != address(address(0x0)), "asm-wrong-token-address"); require(priceFeed[token] != address(address(0x0)), "asm-priceFeed-first"); manualRate[token] = enable; } else if (blockhash(block.number) == "payTokens") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "asm-pay-token-address-no-zero"); payTokens[token] = uint(value1_) > 0; } else if (blockhash(block.number) == "dcdcs") { //injected CONTRACT AFFECTED BY MINERS address newDcdc = addr(value_); bool enable = uint(value1_) > 0; require(newDcdc != address(0), "asm-dcdc-address-zero"); require(priceFeed[newDcdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newDcdc],"asm-no-decimals-set-for-token"); dcdcs[newDcdc] = enable; _updateTotalDcdcV(newDcdc); } else if (blockhash(block.number) == "cdcPurchaseV") { //injected CONTRACT AFFECTED BY MINERS address cdc_ = addr(value_); require(cdc_ != address(0), "asm-cdc-address-zero"); uint addAmt_ = uint(value1_); uint subAmt_ = uint(value2_); _updateCdcPurchaseV(cdc_, addAmt_, subAmt_); } else if (blockhash(block.number) == "cdcs") { //injected CONTRACT AFFECTED BY MINERS address newCdc = addr(value_); bool enable = uint(value1_) > 0; require(priceFeed[newCdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newCdc], "asm-add-decimals-first"); require(newCdc != address(0), "asm-cdc-address-zero"); require( DSToken(newCdc).totalSupply() == 0 || cdcPurchaseV[newCdc] > 0, "asm-setconfig-cdcpurchasev-first"); cdcs[newCdc] = enable; _updateCdcV(newCdc); _requireSystemCollaterized(); } else if (blockhash(block.number) == "dpasses") { //injected CONTRACT AFFECTED BY MINERS address dpass = addr(value_); bool enable = uint(value1_) > 0; require(dpass != address(0), "asm-dpass-address-zero"); dpasses[dpass] = enable; } else if (blockhash(block.number) == "approve") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); uint value = uint(value2_); require(decimalsSet[token],"asm-no-decimals-set-for-token"); require(dst != address(0), "asm-dst-zero-address"); DSToken(token).approve(dst, value); } else if (blockhash(block.number) == "setApproveForAll") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); bool enable = uint(value2_) > 0; require(dpasses[token],"asm-not-a-dpass-token"); require(dst != address(0), "asm-dst-zero-address"); Dpass(token).setApprovalForAll(dst, enable); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS dex = addr(value_); } else if (blockhash(block.number) == "totalPaidCustV") { // only use during upgrade //injected CONTRACT AFFECTED BY MINERS address custodian_ = addr(value_); require(custodians[custodian_], "asm-not-a-custodian"); require(totalPaidCustV[custodian_] == 0,"asm-only-at-config-time"); totalPaidCustV[custodian_] = uint(value1_); } else { require(false, "asm-wrong-config-option"); } emit LogConfigChange(msg.sender, what_, value_, value1_); } /** * @dev Set rate (price in base currency) for token. * @param token_ address token to set bse currency rate for * @param value_ uint256 the rate in base currency to set */ function setRate(address token_, uint256 value_) public auth { setConfig("rate", bytes32(uint(token_)), bytes32(value_), ""); } /** * @dev Get newest rate in base currency from priceFeed for token. This function returns the newest token price in base currency. Burns more gas than getRate(). * @param token_ address token to get most up-to-date rates. */ function getRateNewest(address token_) public view auth returns (uint) { return _getNewRate(token_); } /** * @dev Get currently stored rate in base currency from priceFeed for token. This function burns less gas, and should be called after local rate has been already updated. * @param token_ address to get rate for. */ function getRate(address token_) public view auth returns (uint) { return rate[token_]; } /* * @dev Convert address to bytes32 * @param b_ bytes32 turn this value to address */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Set base price_ for a diamond. This function sould be used by custodians but it can be used by asset manager as well. * @param token_ address token for whom we set baseprice. * @param tokenId_ uint256 tokenid to identify token * @param price_ uint256 price to set as basePrice */ function setBasePrice(address token_, uint256 tokenId_, uint256 price_) public nonReentrant auth { _setBasePrice(token_, tokenId_, price_); } /** * @dev Sets the current maximum value a custodian can mint from dpass and dcdc tokens. * @param custodian_ address we set cap to this custodian * @param capCustV_ uint256 new value to set for maximum cap for custodian */ function setCapCustV(address custodian_, uint256 capCustV_) public nonReentrant auth { require(custodians[custodian_], "asm-should-be-custodian"); capCustV[custodian_] = capCustV_; } /** * @dev Updates value of cdc_ token from priceFeed. This function is called by oracles but can be executed by anyone wanting update cdc_ value in the system. This function should be called every time the price of cdc has been updated. * @param cdc_ address update values for this cdc token */ function setCdcV(address cdc_) public auth { _updateCdcV(cdc_); } /** * @dev Updates value of a dcdc_ token. This function should be called by oracles but anyone can call it. This should be called every time the price of dcdc token was updated. * @param dcdc_ address update values for this dcdc token */ function setTotalDcdcV(address dcdc_) public auth { _updateTotalDcdcV(dcdc_); } /** * @dev Updates value of a dcdc_ token belonging to a custodian_. This function should be called by oracles or custodians but anyone can call it. * @param dcdc_ address the dcdc_ token we want to update the value for * @param custodian_ address the custodian_ whose total dcdc_ values will be updated. */ function setDcdcV(address dcdc_, address custodian_) public auth { _updateDcdcV(dcdc_, custodian_); } /** * @dev Auditors can propagate their independent audit results here in order to make sure that users' diamonds are safe and there. * @param custodian_ address the custodian, who the audit was done for. * @param status_ uint the status of result. 0 means everything is fine, else should be the value of amount in geopardy or questionable. * @param descriptionHash_ bytes32 keccak256() hash of the full audit statement available at descriptionUrl_. In the document all parameters * should be described concerning the availability, and quality of collateral at custodian. * @param descriptionUrl_ bytes32 the url of the audit document. Whenever this is published the document must already be online to avoid fraud. * @param auditInterval_ uint the proposed time in seconds until next audit. If auditor thinks more frequent audits are required he can express his wish here. */ function setAudit( address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterval_ ) public nonReentrant auth { uint32 minInterval_; require(custodians[custodian_], "asm-audit-not-a-custodian"); require(auditInterval_ != 0, "asm-audit-interval-zero"); minInterval_ = uint32(min(auditInterval_, auditInterval)); Audit memory audit_ = Audit({ auditor: msg.sender, status: status_, descriptionHash: descriptionHash_, descriptionUrl: descriptionUrl_, nextAuditBefore: block.timestamp + minInterval_ }); audit[custodian_] = audit_; emit LogAudit(msg.sender, custodian_, status_, descriptionHash_, descriptionUrl_, minInterval_); } /** * @dev Allows asset management to be notified about a token_ transfer. If system would get undercollaterized because of transfer it will be reverted. * @param token_ address the token_ that has been sent during transaction * @param src_ address the source address the token_ has been sent from * @param dst_ address the destination address the token_ has been sent to * @param amtOrId_ uint the amount of tokens sent if token_ is a DSToken or the id of token_ if token_ is a Dpass token_. */ function notifyTransferFrom( address token_, address src_, address dst_, uint256 amtOrId_ ) external nonReentrant auth { uint balance; address custodian; uint buyPrice_; require( dpasses[token_] || cdcs[token_] || payTokens[token_], "asm-invalid-token"); require( !dpasses[token_] || Dpass(token_).getState(amtOrId_) == "sale", "asm-ntf-token-state-not-sale"); if(dpasses[token_] && src_ == address(this)) { // custodian sells dpass to user custodian = Dpass(token_).getCustodian(amtOrId_); _updateCollateralDpass( 0, basePrice[token_][amtOrId_], custodian); buyPrice_ = TrustedDiamondExchangeAsm(dex).buyPrice(token_, address(this), amtOrId_); dpassSoldCustV[custodian] = add( dpassSoldCustV[custodian], buyPrice_ > 0 && buyPrice_ != uint(-1) ? buyPrice_ : basePrice[token_][amtOrId_]); Dpass(token_).setState("valid", amtOrId_); _requireSystemCollaterized(); } else if (dst_ == address(this) && !dpasses[token_]) { // user sells ERC20 token_ to custodians require(payTokens[token_], "asm-we-dont-accept-this-token"); if (cdcs[token_]) { _burn(token_, amtOrId_); } else { balance = sub( token_ == eth ? address(this).balance : DSToken(token_).balanceOf(address(this)), amtOrId_); // this assumes that first tokens are sent, than ... // ... notifyTransferFrom is called, if it is the other way ... // ... around then amtOrId_ must not be subrtacted from current ... // ... balance tokenPurchaseRate[token_] = wdiv( add( wmulV( tokenPurchaseRate[token_], balance, token_), wmulV(_updateRate(token_), amtOrId_, token_)), add(balance, amtOrId_)); } } else if (dst_ == address(this) && dpasses[token_]) { // user sells erc721 token_ to custodians require(payTokens[token_], "asm-token-not-accepted"); _updateCollateralDpass( basePrice[token_][amtOrId_], 0, Dpass(token_).getCustodian(amtOrId_)); Dpass(token_).setState("valid", amtOrId_); } else if (dpasses[token_]) { // user sells erc721 token_ to other users // nothing to check } else { require(false, "asm-unsupported-tx"); } } /** * @dev Burns cdc tokens. Also updates system collaterization. Cdc tokens are burnt when users pay with cdc on exchange or when users redeem cdcs. * @param token_ address cdc token_ that needs to be burnt * @param amt_ uint the amount to burn. */ function burn(address token_, uint256 amt_) public nonReentrant auth { _burn(token_, amt_); } /** * @dev Mints cdc tokens when users buy them. Also updates system collaterization. * @param token_ address cdc token_ that needs to be minted * @param dst_ address the address for whom cdc token_ will be minted for. */ function mint(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, amt_, 0); _requireSystemCollaterized(); } /** * @dev Mints dcdc tokens for custodians. This function should only be run by custodians. * @param token_ address dcdc token_ that needs to be minted * @param dst_ address the address for whom dcdc token will be minted for. * @param amt_ uint amount to be minted */ function mintDcdc(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || dst_ == msg.sender, "asm-can-not-mint-for-dst"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateDcdcV(token_, dst_); _requireCapCustV(dst_); } /** * @dev Burns dcdc token. This function should be used by custodians. * @param token_ address dcdc token_ that needs to be burnt. * @param src_ address the address from whom dcdc token will be burned. * @param amt_ uint amount to be burnt. */ function burnDcdc(address token_, address src_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || src_ == msg.sender, "asm-can-not-burn-from-src"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(src_, amt_); _updateDcdcV(token_, src_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(src_, _getCustodianCdcV(src_)); } /** * @dev Mint dpass tokens and update collateral values. * @param token_ address that is to be minted. Must be a dpass token address. * @param custodian_ address this must be the custodian that we mint the token for. Parameter necessary only for future compatibility. * @param issuer_ bytes3 the issuer of the certificate for diamond * @param report_ bytes16 the report number of the certificate of the diamond. * @param state_ bytes the state of token. Should be "sale" if it is to be sold on market, and "valid" if it is not to be sold. * @param cccc_ bytes20 cut, clarity, color, and carat (carat range) values of the diamond. Only a specific values of cccc_ is accepted. * @param carat_ uint24 exact weight of diamond in carats with 2 decimal precision. * @param attributesHash_ bytes32 the hash of ALL the attributes that are not stored on blockckhain to make sure no one can change them later on. * @param currentHashingAlgorithm_ bytes8 the algorithm that is used to construct attributesHash_. Together these values make meddling with diamond data very hard. * @param price_ uint256 the base price of diamond (not per carat price) */ function mintDpass( address token_, address custodian_, bytes3 issuer_, bytes16 report_, bytes8 state_, bytes20 cccc_, uint24 carat_, bytes32 attributesHash_, bytes8 currentHashingAlgorithm_, uint256 price_ ) public nonReentrant auth returns (uint256 id_) { require(dpasses[token_], "asm-mnt-not-a-dpass-token"); require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || custodian_ == msg.sender, "asm-mnt-no-mint-to-others"); id_ = Dpass(token_).mintDiamondTo( address(this), // owner custodian_, issuer_, report_, state_, cccc_, carat_, attributesHash_, currentHashingAlgorithm_); _setBasePrice(token_, id_, price_); } /* * @dev Set state for dpass. Should be used primarily by custodians. * @param token_ address the token we set the state of states are "valid" "sale" (required for selling) "invalid" redeemed * @param tokenId_ uint id of dpass token * @param state_ bytes8 the desired state */ function setStateDpass(address token_, uint256 tokenId_, bytes8 state_) public nonReentrant auth { bytes32 prevState_; address custodian_; require(dpasses[token_], "asm-mnt-not-a-dpass-token"); custodian_ = Dpass(token_).getCustodian(tokenId_); require( !custodians[msg.sender] || msg.sender == custodian_, "asm-ssd-not-authorized"); prevState_ = Dpass(token_).getState(tokenId_); if( prevState_ != "invalid" && prevState_ != "removed" && ( state_ == "invalid" || state_ == "removed" ) ) { _updateCollateralDpass(0, basePrice[token_][tokenId_], custodian_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(custodian_, _getCustodianCdcV(custodian_)); } else if( prevState_ == "redeemed" || prevState_ == "invalid" || prevState_ == "removed" || ( state_ != "invalid" && state_ != "removed" && state_ != "redeemed" ) ) { _updateCollateralDpass(basePrice[token_][tokenId_], 0, custodian_); } Dpass(token_).setState(state_, tokenId_); } /* * @dev Withdraw tokens for selling dpass, and cdc. Custodians do not receive money directly from selling dpass, ot cdc, but * they must withdraw their tokens. * @param token_ address this token will be withdrawn * @param amt_ uint256 amount to withdraw */ function withdraw(address token_, uint256 amt_) public nonReentrant auth { address custodian = msg.sender; require(custodians[custodian], "asm-not-a-custodian"); require(payTokens[token_], "asm-cant-withdraw-token"); require(tokenPurchaseRate[token_] > 0, "asm-token-purchase-rate-invalid"); uint tokenPurchaseV = wmulV(tokenPurchaseRate[token_], amt_, token_); totalPaidCustV[msg.sender] = add(totalPaidCustV[msg.sender], tokenPurchaseV); _requirePaidLessThanSold(custodian, _getCustodianCdcV(custodian)); sendToken(token_, address(this), msg.sender, amt_); } /* * @dev Return how much cdc token can be minted based on current collaterization. * @param token_ address cdc token that we want to find out how much is mintable. */ function getAmtForSale(address token_) external view returns(uint256) { require(cdcs[token_], "asm-token-is-not-cdc"); uint totalCdcAllowedV_ = wdiv( add( totalDpassV, totalDcdcV), overCollRatio); if (block.timestamp < add(totalCdcV, dust)) //injected CONTRACT AFFECTED BY MINERS return 0; return wdivT( sub( totalCdcAllowedV_, totalCdcV), _getNewRate(token_), token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base * token Value * @param a_ uint256 number that will be multiplied with decimals considered * @param b_ uint256 number that will be multiplied with decimals considered * @param token_ address token whose decimals the result will have */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with the result's decimals adjusted to match to token's precision * @param a_ uint256 number that will be numerator with decimals considered * @param b_ uint256 number that will be denominator with decimals considered * @param token_ address token whose decimals the result will have */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dpass tokens at custodian. * @param positiveV_ uint256 this value will be added to custodian's total dpass collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dpass collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDpass(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDpass(msg.sender, positiveV_, negativeV_, custodian_); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dcdc tokens of custodian. * @param positiveV_ uint256 this value will be added to custodian's total dcdc collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dcdc collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDcdc(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDcdc(msg.sender, positiveV_, negativeV_, custodian_); } /** * @dev Set base price_ for a diamond. Base price is the total price of diamonds. */ function _setBasePrice(address token_, uint256 tokenId_, uint256 price_) internal { bytes32 state_; address custodian_; require(dpasses[token_], "asm-invalid-token-address"); state_ = Dpass(token_).getState(tokenId_); custodian_ = Dpass(token_).getCustodian(tokenId_); require(!custodians[msg.sender] || msg.sender == custodian_, "asm-not-authorized"); if(Dpass(token_).ownerOf(tokenId_) == address(this) && (state_ == "valid" || state_ == "sale")) { _updateCollateralDpass(price_, basePrice[token_][tokenId_], custodian_); if(block.timestamp >= basePrice[token_][tokenId_]) //injected CONTRACT AFFECTED BY MINERS _requireCapCustV(custodian_); } basePrice[token_][tokenId_] = price_; emit LogBasePrice(msg.sender, token_, tokenId_, price_); } /* * @dev Default function for eth payment. We accept ether as payment. */ function () external payable { require(msg.value > 0, "asm-check-the-function-signature"); } /* * @dev Burn cdc tokens and update cdc variables. */ function _burn(address token_, uint256 amt_) internal { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, 0, amt_); } /** * @dev Get exchange rate for a token, and store it. */ function _updateRate(address token_) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token_)) > 0, "asm-updateRate-rate-gt-zero"); rate[token_] = rate_; } /* * @dev updates totalCdcPurchaseV and cdcPurchaseV when addAmt_ is added, or when subAmt_ is removed from cdc_. */ function _updateCdcPurchaseV(address cdc_, uint256 addAmt_, uint256 subAmt_) internal { uint currSupply_; uint prevPurchaseV_; if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS uint currentAddV_ = wmulV(addAmt_, _updateRate(cdc_), cdc_); cdcPurchaseV[cdc_] = add(cdcPurchaseV[cdc_], currentAddV_); totalCdcPurchaseV = add(totalCdcPurchaseV, currentAddV_); } else if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS currSupply_ = DSToken(cdc_).totalSupply(); prevPurchaseV_ = cdcPurchaseV[cdc_]; cdcPurchaseV[cdc_] = currSupply_ > dust ? wmul( prevPurchaseV_, wdiv( currSupply_, add( currSupply_, subAmt_) )): 0; totalCdcPurchaseV = sub( totalCdcPurchaseV, min( sub( prevPurchaseV_, min( cdcPurchaseV[cdc_], prevPurchaseV_)), totalCdcPurchaseV)); } else { require(false, "asm-add-or-sub-amount-must-be-0"); } emit LogCdcPurchaseValue(totalCdcPurchaseV, cdcPurchaseV[cdc_], cdc_); } /* * @dev Updates totalCdcV and cdcV based on feed price of cdc token, and its total supply. */ function _updateCdcV(address cdc_) internal { require(cdcs[cdc_], "asm-not-a-cdc-token"); uint newValue = wmulV(DSToken(cdc_).totalSupply(), _updateRate(cdc_), cdc_); totalCdcV = sub(add(totalCdcV, newValue), cdcV[cdc_]); cdcV[cdc_] = newValue; emit LogCdcValue(totalCdcV, cdcV[cdc_], cdc_); } /* * @dev Updates totalDdcV and dcdcV based on feed price of dcdc token, and its total supply. */ function _updateTotalDcdcV(address dcdc_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); uint newValue = wmulV(DSToken(dcdc_).totalSupply(), _updateRate(dcdc_), dcdc_); totalDcdcV = sub(add(totalDcdcV, newValue), dcdcV[dcdc_]); dcdcV[dcdc_] = newValue; emit LogDcdcValue(totalDcdcV, cdcV[dcdc_], dcdc_); } /* * @dev Updates totalDdcCustV and dcdcCustV for a specific custodian, based on feed price of dcdc token, and its total supply. */ function _updateDcdcV(address dcdc_, address custodian_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); require(custodians[custodian_], "asm-not-a-custodian"); uint newValue = wmulV(DSToken(dcdc_).balanceOf(custodian_), _updateRate(dcdc_), dcdc_); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], newValue), dcdcCustV[dcdc_][custodian_]); dcdcCustV[dcdc_][custodian_] = newValue; emit LogDcdcCustodianValue(totalDcdcCustV[custodian_], dcdcCustV[dcdc_][custodian_], dcdc_, custodian_); _updateTotalDcdcV(dcdc_); } /** * @dev Get token_ base currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) private view returns (uint rate_) { bool feedValid; bytes32 usdRateBytes; require( address(0) != priceFeed[token_], // require token to have a price feed "asm-no-price-feed"); (usdRateBytes, feedValid) = TrustedFeedLike(priceFeed[token_]).peek(); // receive DPT/USD price if (feedValid) { // if feed is valid, load DPT/USD rate from it rate_ = uint(usdRateBytes); } else { require(manualRate[token_], "Manual rate not allowed"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } /* * @dev Get the total value share of custodian from the total cdc minted. */ function _getCustodianCdcV(address custodian_) internal view returns(uint) { uint totalDpassAndDcdcV_ = add(totalDpassV, totalDcdcV); return wmul( totalCdcPurchaseV, totalDpassAndDcdcV_ > 0 ? wdiv( add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), totalDpassAndDcdcV_): 1 ether); } /** * @dev System must be overcollaterized at all time. When it is not, then no cdc can be minted. */ function _requireSystemCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRatio, totalCdcV) , "asm-system-undercollaterized"); } /** * @dev System must be overcollaterized at all time. When total cdc value times overCollRatio is not greater but * equal to total dpass value plus total dcdc value: no more cdc can be minted, but since overCollRemoveRatio is * less than overCollRatio, diamonds still can be removed by custodians. This is very helpful for them if system * is low on collateral. */ function _requireSystemRemoveCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRemoveRatio, totalCdcV) , "asm-sys-remove-undercollaterized"); } /** * @dev The total value paid to custodian (using withdraw()) must be less then the total value of current cdc * share, and dpass sold. */ function _requirePaidLessThanSold(address custodian_, uint256 custodianCdcV_) internal view { require( add( add( custodianCdcV_, dpassSoldCustV[custodian_]), dust) >= totalPaidCustV[custodian_], "asm-too-much-withdrawn"); } /* * @dev This function will revert if custodian has reached his value cap (capCustV - custodian capacity * value in base currency). Asset management enables to limit how much total worth * of diamonds each custodian can mint. This helps to avoid overexposure to some custodians, and avoid some * custodian fraud cases. */ function _requireCapCustV(address custodian_) internal view { if(block.timestamp != uint(-1)) //injected CONTRACT AFFECTED BY MINERS require( add(capCustV[custodian_], dust) >= add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), "asm-custodian-reached-maximum-coll-value"); } /* * @dev Updates total dpass value of a custodian, and the total dpass value. */ function _updateCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDpassCustV[custodian_] = sub( add( totalDpassCustV[custodian_], positiveV_), negativeV_); totalDpassV = sub( add( totalDpassV, positiveV_), negativeV_); emit LogDpassValue(totalDpassCustV[custodian_], totalDpassV, custodian_); } /** * @dev Updates total dcdc customer value and total dcdc value based on custodian collateral change. */ function _updateCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], positiveV_), negativeV_); totalDcdcV = sub( add( totalDcdcV, positiveV_), negativeV_); emit LogDcdcTotalCustodianValue(totalDcdcCustV[custodian_], totalDcdcV, custodian_); } /** * @dev Send token or ether to destination. */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.gaslimit > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Redeemer.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /* import "./SimpleAssetManagement.sol"; */ /* import "./DiamondExchange.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Liquidity.sol"; */ contract Redeemer is DSAuth, DSStop, DSMath { event LogRedeem(uint256 redeemId, address sender, address redeemToken_,uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian); address public eth = address(0xee); event LogTransferEth(address src, address dst, uint256 amount); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1, bytes32 value2); mapping(address => address) public dcdc; // dcdc[cdc] returns the dcdc token associated (having the same values) as cdc token uint256 public fixFee; // Fixed part of fee charged by Cdiamondcoin from redeemToken_ in base currency uint256 public varFee; // Variable part of fee charged by Cdiamondcoin from redeemToken_ address public dpt; // dpt token address SimpleAssetManagement public asm; // asset management contract DiamondExchange public dex; address payable public liq; // liquidity providing contract address bool public liqBuysDpt; // true if liquidity contract buys dpt on the fly, false otherwise address payable public burner; // burner contract to take dpt owners' profit address payable wal; // wallet to receive the operational costs uint public profitRate; // profit that is sent from fees to dpt owners bool locked; // variable to avoid reentrancy attacks against this contract uint redeemId; // id of the redeem transaction user can refer to uint dust = 1000; // dust value to handle round-off errors bytes32 public name = "Red"; // set human readable name for contract bytes32 public symbol = "Red"; // set human readable name for contract bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens modifier nonReentrant { require(!locked, "red-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck(address sender) { require(!kycEnabled || kyc[sender], "red-you-are-not-on-kyc-list"); _; } function () external payable { } function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-asm-address"); asm = SimpleAssetManagement(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "red-var-fee-too-high"); } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "red-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-red-address"); dex = DiamondExchange(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "red-profit-rate-out-of-range"); } else if (blockhash(block.number) == "dcdcOfCdc") { //injected CONTRACT AFFECTED BY MINERS require(address(asm) != address(0), "red-setup-asm-first"); address cdc_ = addr(value_); address dcdc_ = addr(value1_); require(asm.cdcs(cdc_), "red-setup-cdc-in-asm-first"); require(asm.dcdcs(dcdc_), "red-setup-dcdc-in-asm-first"); dcdc[cdc_] = dcdc_; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "red-wrong-address"); } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "red-wrong-address"); Liquidity(address(uint160(liq))).burn(dpt, address(uint160(burner)), 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "red-wrong-address"); require(dpt != address(0), "red-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "red-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); require(dust <= 1 ether, "red-pls-decrease-dust"); } else { require(false, "red-invalid-option"); } emit LogConfigChange(what_, value_, value1_, value2_); } /* * @dev Convert address to bytes32 */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /* * @dev Pay redeem costs and redeem for diamond. Using this funcitn is non-reversible. * @param sender_ address ethereum account of user who wants to redeem * @param redeemToken_ address token address that user wants to redeem token can be both * dpass and cdc tokens * @param redeemAmtOrId_ uint256 if token is cdc then represents amount, and if dpass then id of diamond * @param feeToken_ address token to pay fee with. This token can only be erc20. * @param feeAmt_ uint256 amount of token to be paid as redeem fee. * @param custodian_ address custodian to get diamond from. If token is dpass, then custodian must match * the custodian of dpass token id, if cdc then any custodian can be who has enough matching dcdc tokens. */ function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant kycCheck(sender) returns (uint256) { require(feeToken_ != eth || feeAmt_ == msg.value, "red-eth-not-equal-feeamt"); if( asm.dpasses(redeemToken_) ) { Dpass(redeemToken_).redeem(redeemAmtOrId_); require(custodian_ == address(uint160(Dpass(redeemToken_).getCustodian(redeemAmtOrId_))), "red-wrong-custodian-provided"); } else if ( asm.cdcs(redeemToken_) ) { require( DSToken(dcdc[redeemToken_]) .balanceOf(custodian_) > redeemAmtOrId_, "red-custodian-has-not-enough-cdc"); require(redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); DSToken(redeemToken_).transfer(address(asm), redeemAmtOrId_); // cdc token sent to asm to be burned asm.notifyTransferFrom( // burn cdc token at asm redeemToken_, address(this), address(asm), redeemAmtOrId_); } else { require(false, "red-token-nor-cdc-nor-dpass"); } uint feeToCustodian_ = _sendFeeToCdiamondCoin(redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_); _sendToken(feeToken_, address(this), custodian_, feeToCustodian_); emit LogRedeem(++redeemId, sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); return redeemId; } /** * @dev Put user on whitelist to redeem diamonds. * @param user_ address the ethereum account to enable * @param enable_ bool if true enables, otherwise disables user to use redeem */ function setKyc(address user_, bool enable_) public auth { setConfig( "kyc", bytes32(uint(user_)), enable_ ? bytes32(uint(1)) : bytes32(uint(0)), ""); } /** * @dev send token or ether to destination */ function _sendFeeToCdiamondCoin( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_ ) internal returns (uint feeToCustodianT_){ uint profitV_; uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); uint feeT_ = _getFeeT(feeToken_, redeemTokenV_); uint profitT_ = wmul(profitRate, feeT_); if( block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS DSToken(feeToken_).transfer(burner, profitT_); DSToken(feeToken_).transfer(wal, sub(feeT_, profitT_)); } else { profitV_ = dex.wmulV(profitT_, dex.getLocalRate(feeToken_), feeToken_); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); } else { DSToken(dpt).transferFrom( liq, burner, dex.wdivT(profitV_, dex.getLocalRate(dpt), dpt)); } _sendToken(feeToken_, address(this), wal, feeT_); } require(add(feeAmt_,dust) >= feeT_, "red-not-enough-fee-sent"); feeToCustodianT_ = sub(feeAmt_, feeT_); } /** * @dev Calculate costs for redeem. These are only concerning the fees the system charges. * Delivery costs charged by custodians are additional to these and must be added to the i * cost returned here. * @param redeemToken_ address token that will be redeemed. Cdc or dpass token address required. * @param redeemAmtOrId_ uint256 amount of token to be redeemed * @param feeToken_ address token that will be used to pay fee. * @return amount of fee token that must be sent as fee to system. Above this value users must * add the handling fee of custodians to have a successfull redeem. */ function getRedeemCosts(address redeemToken_, uint256 redeemAmtOrId_, address feeToken_) public view returns(uint feeT_) { require(asm.dpasses(redeemToken_) || redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); feeT_ = _getFeeT(feeToken_, redeemTokenV_); } /** * @dev Calculdate the base currency value of redeem token if it is an erc20 or if it is an erc721 token. */ function _calcRedeemTokenV(address redeemToken_, uint256 redeemAmtOrId_) internal view returns(uint redeemTokenV_) { if(asm.dpasses(redeemToken_)) { redeemTokenV_ = asm.basePrice(redeemToken_, redeemAmtOrId_); } else { redeemTokenV_ = dex.wmulV( redeemAmtOrId_, dex.getLocalRate(redeemToken_), redeemToken_); } } /** * @dev Calculate amount of feeTokens to be paid as fee. */ function _getFeeT(address feeToken_, uint256 redeemTokenV_) internal view returns (uint) { return dex.wdivT( add( wmul( varFee, redeemTokenV_), fixFee), dex.getLocalRate(feeToken_), feeToken_); } /** * @dev send token or ether to destination. */ function _sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.number > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/DiamondExchange.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "./Liquidity.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Redeemer.sol"; */ /** * @dev Interface to get ETH/USD price */ contract TrustedFeedLikeDex { function peek() external view returns (bytes32, bool); } /** * @dev Interface to calculate user fee based on amount */ contract TrustedFeeCalculator { function calculateFee( address sender, uint256 value, address sellToken, uint256 sellAmtOrId, address buyToken, uint256 buyAmtOrId ) external view returns (uint); function getCosts( address user, // user for whom we want to check the costs for address sellToken_, uint256 sellId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256 sellAmtOrId_, uint256 feeDpt_, uint256 feeV_, uint256 feeSellT_) { // calculate expected sell amount when user wants to buy something anc only knows how much he wants to buy from a token and whishes to know how much it will cost. } } /** * @dev Interface to do redeeming of tokens */ contract TrustedRedeemer { function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable returns (uint256); } /** * @dev Interface for managing diamond assets */ contract TrustedAsm { function notifyTransferFrom(address token, address src, address dst, uint256 id721) external; function basePrice(address erc721, uint256 id721) external view returns(uint256); function getAmtForSale(address token) external view returns(uint256); function mint(address token, address dst, uint256 amt) external; } /** * @dev Interface ERC721 contract */ contract TrustedErc721 { function transferFrom(address src, address to, uint256 amt) external; function ownerOf(uint256 tokenId) external view returns (address); } /** * @dev Interface for managing diamond assets */ contract TrustedDSToken { function transferFrom(address src, address dst, uint wad) external returns (bool); function totalSupply() external view returns (uint); function balanceOf(address src) external view returns (uint); function allowance(address src, address guy) external view returns (uint); } /** * @dev Diamond Exchange contract for events. */ contract DiamondExchangeEvents { event LogBuyTokenWithFee( uint256 indexed txId, address indexed sender, address custodian20, address sellToken, uint256 sellAmountT, address buyToken, uint256 buyAmountT, uint256 feeValue ); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 val); } /** * @title Diamond Exchange contract * @dev This contract can exchange ERC721 tokens and ERC20 tokens as well. Primary * usage is to buy diamonds or buying diamond backed stablecoins. */ contract DiamondExchange is DSAuth, DSStop, DiamondExchangeEvents { TrustedDSToken public cdc; // CDC token contract address public dpt; // DPT token contract mapping(address => uint256) private rate; // exchange rate for a token mapping(address => uint256) public smallest; // set minimum amount of sellAmtOrId_ mapping(address => bool) public manualRate; // manualRate is allowed for a token (if feed invalid) mapping(address => TrustedFeedLikeDex) public priceFeed; // price feed address for token mapping(address => bool) public canBuyErc20; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc20; // stores allowed ERC20 tokens to sell mapping(address => bool) public canBuyErc721; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc721; // stores allowed ERC20 tokens to sell mapping(address => mapping(address => bool)) // stores tokens that seller does not accept, ... public denyToken; // ... and also token pairs that can not be traded mapping(address => uint) public decimals; // stores decimals for each ERC20 token mapping(address => bool) public decimalsSet; // stores if decimals were set for ERC20 token mapping(address => address payable) public custodian20; // custodian that holds an ERC20 token for Exchange mapping(address => bool) public handledByAsm; // defines if token is managed by Asset Management mapping( address => mapping( address => mapping( uint => uint))) public buyPrice; // buyPrice[token][owner][tokenId] price of dpass token ... // ... defined by owner of dpass token mapping(address => bool) redeemFeeToken; // tokens allowed to pay redeem fee with TrustedFeeCalculator public fca; // fee calculator contract address payable public liq; // contract providing DPT liquidity to pay for fee address payable public wal; // wallet address, where we keep all the tokens we received as fee address public burner; // contract where accured fee of DPT is stored before being burned TrustedAsm public asm; // Asset Management contract uint256 public fixFee; // Fixed part of fee charged for buying 18 decimals precision in base currency uint256 public varFee; // Variable part of fee charged for buying 18 decimals precision in base currency uint256 public profitRate; // the percentage of profit that is burned on all fees received. ... // ... 18 decimals precision uint256 public callGas = 2500; // using this much gas when Ether is transferred uint256 public txId; // Unique id of each transaction. bool public takeProfitOnlyInDpt = true; // If true, it takes cost + profit in DPT, if false only profit in DPT uint256 public dust = 10000; // Numbers below this amount are considered 0. Can only be used ... bytes32 public name = "Dex"; // set human readable name for contract bytes32 public symbol = "Dex"; // set human readable name for contract // ... along with 18 decimal precisions numbers. bool liqBuysDpt; // if true then liq contract is called directly to buy necessary dpt, otherwise we... // ... just send DPT from liq contracts address to burner. bool locked; // protect against reentrancy attacks address eth = address(0xee); // to handle ether the same way as tokens we associate a fake address to it bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens address payable public redeemer; // redeemer contract to handle physical diamond delivery to users //-----------included-from-ds-math---------------------------------begin uint constant WAD = 1 ether; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end modifier nonReentrant { require(!locked, "dex-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck { require(!kycEnabled || kyc[msg.sender], "dex-you-are-not-on-kyc-list"); _; } /** * @dev Fallback function to buy tokens. */ function () external payable { buyTokensWithFee(eth, msg.value, address(cdc), uint(-1)); } /** * @dev Set configuration values for contract. Instead of several small functions * that bloat the abi, this monolitic function can be used to configure Diamond i * Exchange contract. * @param what_ bytes32 determines what change the owner(contract) wants to make. * @param value_ bytes32 depending on what_ can be used to configure the system * @param value1_ bytes32 depending on what_ can be used to configure the system */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_) public auth { if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "dex-profit-rate-out-of-range"); } else if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-rate"); require(value > 0, "dex-rate-must-be-greater-than-0"); rate[token] = value; } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "dex-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "allowTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = false; } else if (blockhash(block.number) == "denyTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = true; } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "dex-var-fee-too-high"); } else if (blockhash(block.number) == "redeemFeeToken") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "dex-zero-address-redeemfee-token"); redeemFeeToken[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-manualrate"); manualRate[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(canSellErc20[addr(value_)] || canBuyErc20[addr(value_)], "dex-token-not-allowed-pricefeed"); require(addr(value1_) != address(address(0x0)), "dex-wrong-pricefeed-address"); priceFeed[addr(value_)] = TrustedFeedLikeDex(addr(value1_)); } else if (blockhash(block.number) == "takeProfitOnlyInDpt") { //injected CONTRACT AFFECTED BY MINERS takeProfitOnlyInDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "dex-wrong-address"); Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "dex-wrong-address"); require(dpt != address(0), "dex-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "dex-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "handledByAsm") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(canBuyErc20[token] || canBuyErc721[token], "dex-token-not-allowed-handledbyasm"); handledByAsm[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); asm = TrustedAsm(addr(value_)); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "cdc") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); cdc = TrustedDSToken(addr(value_)); } else if (blockhash(block.number) == "fca") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); fca = TrustedFeeCalculator(addr(value_)); } else if (blockhash(block.number) == "custodian20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); custodian20[addr(value_)] = address(uint160(addr(value1_))); } else if (blockhash(block.number) == "smallest") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-small"); smallest[token] = value; } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token_ = addr(value_); require(token_ != address(0x0), "dex-wrong-address"); uint decimal = uint256(value1_); decimals[token_] = 10 ** decimal; decimalsSet[token_] = true; } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "callGas") { //injected CONTRACT AFFECTED BY MINERS callGas = uint256(value_); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "canBuyErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-buytoken-decimals-not-set"); canBuyErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-selltoken-decimals-not-set"); canSellErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canBuyErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canBuyErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canSellErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "dex-wrong-address"); require(decimalsSet[dpt], "dex-dpt-decimals-not-set"); } else if (blockhash(block.number) == "redeemer") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-redeemer-address"); redeemer = address(uint160(addr(value_))); } else { value1_; require(false, "dex-no-such-option"); } emit LogConfigChange(what_, value_, value1_); } /** * @dev Redeem token and pay fee for redeem. * @param redeemToken_ address this is the token address user wants to redeem * @param redeemAmtOrId_ uint256 if redeemToken_ is erc20 token this is the amount to redeem, if erc721 then this is the id * @param feeToken_ address the token user wants to pay for redeem fee with * @param feeAmt_ address amount user pays for redeem (note there is no function to cancel this redeem) * @param custodian_ address the custodians address that user wants to get his diamonds from (if redeemToken_ is dpass, user must set the custodian of the token here) */ function redeem( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant returns(uint redeemId) { // kyc check will thake place on redeem contract. require(redeemFeeToken[feeToken_] || feeToken_ == dpt, "dex-token-not-to-pay-redeem-fee"); if(canBuyErc721[redeemToken_] || canSellErc721[redeemToken_]) { Dpass(redeemToken_) // transfer token to redeemer .transferFrom( msg.sender, redeemer, redeemAmtOrId_); } else if (canBuyErc20[redeemToken_] || canSellErc20[redeemToken_]) { _sendToken(redeemToken_, msg.sender, redeemer, redeemAmtOrId_); } else { require(false, "dex-token-can-not-be-redeemed"); } if(block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return TrustedRedeemer(redeemer) .redeem .value(msg.value) (msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } else { _sendToken(feeToken_, msg.sender, redeemer, feeAmt_); return TrustedRedeemer(redeemer) .redeem(msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } } /** * @dev 1oken purchase with fee. (If user has DPT he must approve this contract, * otherwise transaction will fail.) * @param sellToken_ address token user wants to sell * @param sellAmtOrId_ uint256 if sellToken_ is erc20 token then this is the amount (if set to highest possible, it means user wants to exchange all necessary tokens in his posession to buy the buyToken_), if token is Dpass(erc721) token, then this is the tokenId * @param buyToken_ address token user wants to buy * @param buyAmtOrId_ uint256 if buyToken_ is erc20, then this is the amount(setting highest integer will make buy as much buyTokens: as possible), and it is tokenId otherwise */ function buyTokensWithFee ( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public payable stoppable nonReentrant kycCheck { uint buyV_; uint sellV_; uint feeV_; uint sellT_; uint buyT_; require(!denyToken[sellToken_][buyToken_], "dex-cant-use-this-token-to-buy"); require(smallest[sellToken_] <= sellAmtOrId_, "dex-trade-value-too-small"); _updateRates(sellToken_, buyToken_); // update currency rates (buyV_, sellV_) = _getValues( // calculate highest possible buy and sell values (here they might not match) sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); feeV_ = calculateFee( // calculate fee user has to pay for exchange msg.sender, min(buyV_, sellV_), sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); (sellT_, buyT_) = _takeFee( // takes the calculated fee from user in DPT or sellToken_ ... feeV_, // ... calculates final sell and buy values (in base currency) sellV_, buyV_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); _transferTokens( // transfers tokens to user and seller sellT_, buyT_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_, feeV_); } /** * @dev Get sell and buy token values in base currency */ function _getValues( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns (uint256 buyV, uint256 sellV) { uint sellAmtT_ = sellAmtOrId_; uint buyAmtT_ = buyAmtOrId_; uint maxT_; require(buyToken_ != eth, "dex-we-do-not-sell-ether"); // we can not sell Ether with this smart contract currently require(sellToken_ == eth || msg.value == 0, // we don't accept ETH if user wants to sell other token "dex-do-not-send-ether"); if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token maxT_ = sellToken_ == eth ? msg.value : min( TrustedDSToken(sellToken_).balanceOf(msg.sender), TrustedDSToken(sellToken_).allowance( msg.sender, address(this))); require(maxT_ > 0, "dex-please-approve-us"); require( sellToken_ == eth || // disregard Ether sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= maxT_, // sellAmtOrId_ should be less then sellToken_ available to this contract "dex-sell-amount-exceeds-allowance"); require( sellToken_ != eth || // regard Ether only sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= msg.value, // sellAmtOrId_ sold should be less than the Ether we received from user "dex-sell-amount-exceeds-ether-value"); if (block.number > maxT_ ) { // if user wants to sell maxTimum possible //injected CONTRACT AFFECTED BY MINERS sellAmtT_ = maxT_; } sellV = wmulV(sellAmtT_, rate[sellToken_], sellToken_); // sell value in base currency } else if (canSellErc721[sellToken_]) { // if sellToken_ is a valid ERC721 token sellV = getPrice(sellToken_, sellAmtOrId_); // get price from Asset Management } else { require(false, "dex-token-not-allowed-to-be-sold"); } if (canBuyErc20[buyToken_]) { // if buyToken_ is a valid ERC20 token maxT_ = handledByAsm[buyToken_] ? // set buy amount to maxT_ possible asm.getAmtForSale(buyToken_) : // if managed by asset management get available min( // if not managed by asset management get maxT_ available TrustedDSToken(buyToken_).balanceOf( custodian20[buyToken_]), TrustedDSToken(buyToken_).allowance( custodian20[buyToken_], address(this))); require(maxT_ > 0, "dex-0-token-is-for-sale"); require( // require token's buy amount to be less or equal than available to us buyToken_ == eth || // disregard Ether buyAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning buyAmtOrId_ <= maxT_, // amount must be less or equal that maxT_ available "dex-buy-amount-exceeds-allowance"); if (block.number > maxT_) { // user wants to buy the maxTimum possible //injected CONTRACT AFFECTED BY MINERS buyAmtT_ = maxT_; } buyV = wmulV(buyAmtT_, rate[buyToken_], buyToken_); // final buy value in base currency } else if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token require(canSellErc20[sellToken_], // require that at least one of sell and buy token is ERC20 "dex-one-of-tokens-must-be-erc20"); buyV = getPrice( // calculate price with Asset Management contract buyToken_, buyAmtOrId_); } else { require(false, "dex-token-not-allowed-to-be-bought"); // token can not be bought here } } /** * @dev Calculate fee locally or using an external smart contract * @return the fee amount in base currency * @param sender_ address user we want to get the fee for * @param value_ uint256 base currency value of transaction for which the fee will be derermined * @param sellToken_ address token to be sold by user * @param sellAmtOrId_ uint256 amount or id of token * @param buyToken_ address token to be bought by user * @param buyAmtOrId_ uint256 amount or id of buytoken */ function calculateFee( address sender_, uint256 value_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256) { if (fca == TrustedFeeCalculator(0)) { return add(fixFee, wmul(varFee, value_)); // calculate proportional fee locally } else { return fca.calculateFee( // calculate fee using external smart contract sender_, value_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); } } /** * @dev Taking feeV_ from user. If user has DPT takes it, if there is none buys it for user. * @return the amount of remaining ETH after buying feeV_ if it was required */ function _takeFee( uint256 feeV_, uint256 sellV_, uint256 buyV_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns(uint256 sellT, uint256 buyT) { uint feeTakenV_; uint amtT_; address token_; address src_; uint restFeeV_; feeTakenV_ = sellToken_ != dpt ? // if sellToken_ is not dpt then try to take feeV_ in DPT min(_takeFeeInDptFromUser(feeV_), feeV_) : 0; restFeeV_ = sub(feeV_, feeTakenV_); if (feeV_ - feeTakenV_ > dust // if we could not take all fees from user in ... && feeV_ - feeTakenV_ <= feeV_) { // ... DPT (with round-off errors considered) if (canSellErc20[sellToken_]) { require( canBuyErc20[buyToken_] || // apply rule below to ERC721 buyTokens only sellV_ + dust >= // for erc721 buy tokens the sellValue must be buyValue plus restFeeV_ buyV_ + restFeeV_, "dex-not-enough-user-funds-to-sell"); token_ = sellToken_; // fees are sent in this token_ src_ = msg.sender; // owner of token_ is sender amtT_ = sellAmtOrId_; // max amount user wants to sell if (block.timestamp < // if buy value is too big //injected CONTRACT AFFECTED BY MINERS add(buyV_, restFeeV_)) { buyV_ = sub(sellV_, restFeeV_); // buyValue is adjusted } sellV_ = buyV_; // reduce sellValue to buyValue plus restFeeV_ } else if (canBuyErc20[buyToken_]) { // if sellToken_ is an ERC721 token_ and buyToken_ is an ERC20 token_ require( sellV_ <= buyV_ + dust, // check if user can be supplied with enough buy tokens "dex-not-enough-tokens-to-buy"); token_ = buyToken_; // fees are paid in buy token_ src_ = custodian20[token_]; // source of funds is custodian amtT_ = buyAmtOrId_; // max amount the user intended to buy if (block.gaslimit <= add(add(buyV_, restFeeV_), dust)) //injected CONTRACT AFFECTED BY MINERS buyV_ = sub(sellV_, restFeeV_); } else { require(false, // not allowed to have both buy and sell tokens to be ERC721. ... "dex-no-token-to-get-fee-from"); // ... We should never end up here since dex-one-of-tokens-must-be-erc20 ... // ... will be fired first. It is here for precaution. } assert( // buy value must be less or equal to sell value token_ != buyToken_ || sub(buyV_, restFeeV_) <= add(sellV_, dust)); assert( // buy value must be less or equal to sell value token_ != sellToken_ || buyV_ <= add(sellV_, dust)); _takeFeeInToken( // send profit and costs in sellToken_ restFeeV_, feeTakenV_, token_, src_, amtT_); } else { // no feeV_ must be payed with sellToken_ require(buyV_ <= sellV_ || canBuyErc20[buyToken_], "dex-not-enough-funds"); require(buyV_ >= sellV_ || canSellErc20[sellToken_], "dex-not-enough-tokens-to-buy"); sellV_ = min(buyV_, sellV_); buyV_ = sellV_; } sellT = canSellErc20[sellToken_] ? // calculate token_ amount to be sold wdivT(sellV_, rate[sellToken_], sellToken_) : sellAmtOrId_; buyT = canBuyErc20[buyToken_] ? wdivT(buyV_, rate[buyToken_], buyToken_) : buyAmtOrId_; if (block.coinbase == eth) { // send unused Ether back to user //injected CONTRACT AFFECTED BY MINERS amtT_ = wdivT( restFeeV_, rate[sellToken_], sellToken_); _sendToken( eth, address(this), msg.sender, sub(msg.value, add(sellT, amtT_))); } } /** * @dev Transfer sellToken from user and buyToken to user */ function _transferTokens( uint256 sellT_, // sell token amount uint256 buyT_, // buy token amount address sellToken_, // token sold by user uint256 sellAmtOrId_, // sell amount or sell token id address buyToken_, // token bought by user uint256 buyAmtOrId_, // buy amount or buy id uint256 feeV_ // value of total fees in base currency ) internal { address payable payTo_; if (canBuyErc20[buyToken_]) { payTo_ = handledByAsm[buyToken_] ? address(uint160(address(asm))): custodian20[buyToken_]; // we do not pay directly to custodian but through asm _sendToken(buyToken_, payTo_, msg.sender, buyT_); // send buyToken_ from custodian to user } if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token payTo_ = address(uint160(address( // we pay to owner Dpass(buyToken_).ownerOf(buyAmtOrId_)))); asm.notifyTransferFrom( // notify Asset management about the transfer buyToken_, payTo_, msg.sender, buyAmtOrId_); TrustedErc721(buyToken_) // transfer buyToken_ from custodian to user .transferFrom( payTo_, msg.sender, buyAmtOrId_); } _sendToken(sellToken_, msg.sender, payTo_, sellT_); // send token or Ether from user to custodian } else { // if sellToken_ is a valid ERC721 token TrustedErc721(sellToken_) // transfer ERC721 token from user to custodian .transferFrom( msg.sender, payTo_, sellAmtOrId_); sellT_ = sellAmtOrId_; } require(!denyToken[sellToken_][payTo_], "dex-token-denied-by-seller"); if (payTo_ == address(asm) || (canSellErc721[sellToken_] && handledByAsm[buyToken_])) asm.notifyTransferFrom( // notify Asset Management contract about transfer sellToken_, msg.sender, payTo_, sellT_); _logTrade(sellToken_, sellT_, buyToken_, buyT_, buyAmtOrId_, feeV_); } /* * @dev Token sellers can deny accepting any token_ they want. * @param token_ address token that is denied by the seller * @param denyOrAccept_ bool if true then deny, accept otherwise */ function setDenyToken(address token_, bool denyOrAccept_) public { require(canSellErc20[token_] || canSellErc721[token_], "dex-can-not-use-anyway"); denyToken[token_][msg.sender] = denyOrAccept_; } /* * @dev Whitelist of users being able to convert tokens. * @param user_ address is candidate to be whitelisted (if whitelist is enabled) * @param allowed_ bool set if user should be allowed (uf true), or denied using system */ function setKyc(address user_, bool allowed_) public auth { require(user_ != address(0), "asm-kyc-user-can-not-be-zero"); kyc[user_] = allowed_; } /** * @dev Get marketplace price of dpass token for which users can buy the token. * @param token_ address token to get the buyPrice for. * @param tokenId_ uint256 token id to get buy price for. */ function getBuyPrice(address token_, uint256 tokenId_) public view returns(uint256) { // require(canBuyErc721[token_], "dex-token-not-for-sale"); return buyPrice[token_][TrustedErc721(token_).ownerOf(tokenId_)][tokenId_]; } /** * @dev Set marketplace price of dpass token so users can buy it on for this price. * @param token_ address price is set for this token. * @param tokenId_ uint256 tokenid to set price for * @param price_ uint256 marketplace price to set */ function setBuyPrice(address token_, uint256 tokenId_, uint256 price_) public { address seller_ = msg.sender; require(canBuyErc721[token_], "dex-token-not-for-sale"); if ( msg.sender == Dpass(token_).getCustodian(tokenId_) && address(asm) == Dpass(token_).ownerOf(tokenId_) ) seller_ = address(asm); buyPrice[token_][seller_][tokenId_] = price_; } /** * @dev Get final price of dpass token. Function tries to get rpce from marketplace * price (buyPrice) and if that is zero, then from basePrice. * @param token_ address token to get price for * @param tokenId_ uint256 to get price for * @return final sell price that user must pay */ function getPrice(address token_, uint256 tokenId_) public view returns(uint256) { uint basePrice_; address owner_ = TrustedErc721(token_).ownerOf(tokenId_); uint buyPrice_ = buyPrice[token_][owner_][tokenId_]; require(canBuyErc721[token_], "dex-token-not-for-sale"); if( buyPrice_ == 0 || buyPrice_ == uint(-1)) { basePrice_ = asm.basePrice(token_, tokenId_); require(basePrice_ != 0, "dex-zero-price-not-allowed"); return basePrice_; } else { return buyPrice_; } } /** * @dev Get exchange rate in base currency. This function burns small amount of gas, because it returns the locally stored exchange rate for token_. It should only be used if user is sure that the rate was recently updated. * @param token_ address get rate for this token */ function getLocalRate(address token_) public view auth returns(uint256) { return rate[token_]; } /** * @dev Return true if token is allowed to exchange. * @param token_ the token_ addres in question * @param buy_ if true we ask if user can buy_ the token_ from exchange, * otherwise if user can sell to exchange. */ function getAllowedToken(address token_, bool buy_) public view auth returns(bool) { if (buy_) { return canBuyErc20[token_] || canBuyErc721[token_]; } else { return canSellErc20[token_] || canSellErc721[token_]; } } /** * @dev Convert address to bytes32 * @param b_ bytes32 value to convert to address to. */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Retrieve the decimals of a token. Decimals are stored in a special way internally to apply the least calculations to get precision adjusted results. * @param token_ address the decimals are calculated for this token */ function getDecimals(address token_) public view returns (uint8) { require(decimalsSet[token_], "dex-token-with-unset-decimals"); uint dec = 0; while(dec <= 77 && decimals[token_] % uint(10) ** dec == 0){ dec++; } dec--; return uint8(dec); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed * @param token_ address get rate for this token */ function getRate(address token_) public view auth returns (uint) { return _getNewRate(token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base token value. * @param a_ uint256 multiply this number * @param b_ uint256 multiply this number * @param token_ address get results with the precision of this token */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with decimals adjusted to match to tokens precision * @param a_ uint256 divide this number * @param b_ uint256 divide by this number * @param token_ address get result with the precision of this token */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) internal view returns (uint rate_) { bool feedValid_; bytes32 baseRateBytes_; require( TrustedFeedLikeDex(address(0x0)) != priceFeed[token_], // require token to have a price feed "dex-no-price-feed-for-token"); (baseRateBytes_, feedValid_) = priceFeed[token_].peek(); // receive DPT/USD price if (feedValid_) { // if feed is valid, load DPT/USD rate from it rate_ = uint(baseRateBytes_); } else { require(manualRate[token_], "dex-feed-provides-invalid-data"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } // // internal functions // /* * @dev updates locally stored rates of tokens from feeds */ function _updateRates(address sellToken_, address buyToken_) internal { if (canSellErc20[sellToken_]) { _updateRate(sellToken_); } if (canBuyErc20[buyToken_]){ _updateRate(buyToken_); } _updateRate(dpt); } /* * @dev log the trade event */ function _logTrade( address sellToken_, uint256 sellT_, address buyToken_, uint256 buyT_, uint256 buyAmtOrId_, uint256 feeV_ ) internal { address custodian_ = canBuyErc20[buyToken_] ? custodian20[buyToken_] : Dpass(buyToken_).getCustodian(buyAmtOrId_); txId++; emit LogBuyTokenWithFee( txId, msg.sender, custodian_, sellToken_, sellT_, buyToken_, buyT_, feeV_); } /** * @dev Get exchange rate for a token */ function _updateRate(address token) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token)) > 0, "dex-rate-must-be-greater-than-0"); rate[token] = rate_; } /** * @dev Calculate and send profit and cost */ function _takeFeeInToken( uint256 feeV_, // feeV_ that user still owes to CDiamondCoin after paying feeV_ in DPT uint256 feeTakenV_, // feeV_ already taken from user in DPT address token_, // token_ that must be sent as feeV_ address src_, // source of token_ sent uint256 amountT_ // total amount of tokens the user wanted to pay initially ) internal { uint profitV_; uint profitDpt_; uint feeT_; uint profitPaidV_; uint totalProfitV_; totalProfitV_ = wmul(add(feeV_, feeTakenV_), profitRate); profitPaidV_ = takeProfitOnlyInDpt ? // profit value paid already in base currency feeTakenV_ : wmul(feeTakenV_, profitRate); profitV_ = sub( // profit value still to be paid in base currency totalProfitV_, min( profitPaidV_, totalProfitV_)); profitDpt_ = wdivT(profitV_, rate[dpt], dpt); // profit in DPT still to be paid feeT_ = wdivT(feeV_, rate[token_], token_); // convert feeV_ from base currency to token amount require( feeT_ < amountT_, // require that the cost we pay is less than user intended to pay "dex-not-enough-token-to-pay-fee"); if (block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS _sendToken(dpt, src_, address(uint160(address(burner))), profitDpt_); _sendToken(dpt, src_, wal, sub(feeT_, profitDpt_)); } else { if (liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); // if liq contract buys DPT on the fly } else { _sendToken(dpt, // if liq contract stores DPT that can be sent to burner by us liq, address(uint160(address(burner))), profitDpt_); } _sendToken(token_, src_, wal, feeT_); // send user token_ to wallet } } /** * @dev Take fee in DPT from user if it has any * @param feeV_ the fee amount in base currency * @return the remaining fee amount in DPT */ function _takeFeeInDptFromUser( uint256 feeV_ // total feeV_ to be paid ) internal returns(uint256 feeTakenV_) { TrustedDSToken dpt20_ = TrustedDSToken(dpt); uint profitDpt_; uint costDpt_; uint feeTakenDpt_; uint dptUser = min( dpt20_.balanceOf(msg.sender), dpt20_.allowance(msg.sender, address(this)) ); if (block.gaslimit == 0) return 0; //injected CONTRACT AFFECTED BY MINERS uint feeDpt = wdivT(feeV_, rate[dpt], dpt); // feeV_ in DPT uint minDpt = min(feeDpt, dptUser); // get the maximum possible feeV_ amount if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS if (takeProfitOnlyInDpt) { // only profit is paid in dpt profitDpt_ = min(wmul(feeDpt, profitRate), minDpt); } else { profitDpt_ = wmul(minDpt, profitRate); costDpt_ = sub(minDpt, profitDpt_); _sendToken(dpt, msg.sender, wal, costDpt_); // send cost } _sendToken(dpt, // send profit to burner msg.sender, address(uint160(address(burner))), profitDpt_); feeTakenDpt_ = add(profitDpt_, costDpt_); // total feeV_ taken in DPT feeTakenV_ = wmulV(feeTakenDpt_, rate[dpt], dpt); // total feeV_ taken in base currency value } } /** * @dev send token or ether to destination */ function _sendToken( address token_, address src_, address payable dst_, uint256 amount_ ) internal returns(bool) { if (token_ == eth && amount_ > dust) { // if token_ is Ether and amount_ is higher than dust limit require(src_ == msg.sender || src_ == address(this), "dex-wrong-src-address-provided"); dst_.transfer(amount_); emit LogTransferEth(src_, dst_, amount_); } else { if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS if( handledByAsm[token_] && src_ == address(asm)) { // if token_ is handled by asm (so it is minted and burnt) and we have to mint it asm.mint(token_, dst_, amount_); } else { TrustedDSToken(token_).transferFrom(src_, dst_, amount_); // transfer all of token_ to dst_ } } } return true; } }
calculate expected sell amount when user wants to buy something anc only knows how much he wants to buy from a token and whishes to know how much it will cost.
) public view returns (uint256 sellAmtOrId_, uint256 feeDpt_, uint256 feeV_, uint256 feeSellT_) { }
13,090,985
[ 1, 11162, 2665, 357, 80, 3844, 1347, 729, 14805, 358, 30143, 5943, 392, 71, 1338, 21739, 3661, 9816, 3904, 14805, 358, 30143, 628, 279, 1147, 471, 600, 1468, 281, 358, 5055, 3661, 9816, 518, 903, 6991, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 1071, 1476, 1135, 261, 11890, 5034, 357, 80, 31787, 1162, 548, 67, 16, 2254, 5034, 14036, 40, 337, 67, 16, 2254, 5034, 14036, 58, 67, 16, 2254, 5034, 14036, 55, 1165, 56, 67, 13, 288, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-12 */ /* Welcome to ██████╗ ██████╗ ██╗██████╗ ██████╗ ███████╗██╗ ██╗ ██╔══██╗██╔══██╗██║██╔══██╗██╔════╝ ██╔════╝╚██╗██╔╝ ██████╔╝██████╔╝██║██║ ██║██║ ███╗█████╗ ╚███╔╝ ██╔══██╗██╔══██╗██║██║ ██║██║ ██║██╔══╝ ██╔██╗ ██████╔╝██║ ██║██║██████╔╝╚██████╔╝███████╗██╔╝ ██╗ ╚═════╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ Powerful and fastest Atomic Swap as a service provider Powered by xFox.io -------------- Go to dApp : https://www.bridgex.app/ DOcumentation : https://docs.bridgex.app/ */ pragma solidity ^0.8.4; // SPDX-License-Identifier: MIT /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /* * @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) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ 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; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function decimals() external view returns (uint8); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } /** * @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); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } contract BridgeX is Ownable, Pausable, ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; //Defining a Project struct Project { address tokenAddress; uint balance; bool active; address owner; uint max_amount; uint swapCommissionPercent; address swapCommissionReceiver; uint minOracleFee; bool ownerVerified; mapping(uint => Chain) chains; //ChainID => chainData mapping(bytes32 => Swap) swaps; //SwapID => swapData } struct Chain { address tokenAddress; bool active; uint swapCount; uint minOracleFee; } struct Swap { uint swapCount; uint chainID; address from; address to; uint amount; bool isCompleted; } mapping(bytes32 => Project) public projects; //UniquePRojectID => projectdata uint public totalProjects = 0; //Total number of projects uint public totalSwaps = 0; //Total number of swaps performed in this contract //Oracle address address payable public oracleAddress; //SUDO Settings uint public PROJECT_CREATION_COST; address payable public SERVICE_PROVIDER_ADDRESS; //Events event SwapStart ( bytes32 indexed projectId, bytes32 indexed swapId, uint swapCount, uint toChainID, address indexed fromAddr, address toAddr, uint amount ); event SwapEnd ( bytes32 indexed projectId, bytes32 indexed swapId, uint swapCount, uint fromChainID, address indexed fromAddr, address toAddr, uint amount ); event SwapCompleted( bytes32 indexed projectId, bytes32 indexed swapId ); event newProjectCreated( bytes32 indexed projectId, address indexed tokenAddress, address indexed owner, uint initialSupply ); event newProjectChainCreated( bytes32 indexed projectId, uint chainId, address tokenAddress ); event commissionReceived( bytes32 indexed projectId, bytes32 indexed swapId, uint amount ); event projectStatusChanged( bytes32 indexed projectId, bool newStatus ); //Modifiers modifier onlyActiveChains(bytes32 projectId, uint chainID){ require(chainID != _getChainID(), "BRIDGEX: Swap must be created to different chain ID"); require(projects[projectId].chains[chainID].active == true, "BRIDGEX: Only active chains"); _; } modifier notContract() { require(!_isContract(msg.sender), "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); _; } modifier onlyTokenOwner(bytes32 projectId) { require(projects[projectId].owner == _msgSender(), "ERROR: caller is not the Token Owner"); _; } modifier OnlyOracle() { require(oracleAddress == _msgSender(), "ERROR: caller is not the Oracle"); _; } constructor(address payable _oracleAddress, address payable _serviceProvider, uint _projectCreationCost) { oracleAddress = _oracleAddress; SERVICE_PROVIDER_ADDRESS = _serviceProvider; PROJECT_CREATION_COST = _projectCreationCost; } //Initite swap operation by users function swapStart(bytes32 projectId, uint toChainID, address to, uint amount) public payable onlyActiveChains(projectId, toChainID) whenNotPaused notContract nonReentrant { require(projects[projectId].active == true, "BRIDGE: Bridge Pool is inactive"); require(msg.value.mul(1 gwei) >= projects[projectId].minOracleFee.add(projects[projectId].chains[toChainID].minOracleFee), "BRIDGE: Insufficient Oracle Fee"); require(amount <= projects[projectId].max_amount, "BRIDGEX: Amount must be within max range"); require(to == msg.sender, "BRIDGEX: Swaps allowed between same address only"); require(IERC20(projects[projectId].tokenAddress).allowance(msg.sender, address(this)) >= amount, "BRIDGEX: Not enough allowance"); _depositToken(projectId, amount); //Prepare commission to token owners uint commission; if(projects[projectId].swapCommissionPercent > 0 && msg.sender != projects[projectId].swapCommissionReceiver){ commission = calculateCommission(projectId, amount); amount = amount.sub(commission); _withdrawCommission(projectId, commission); emit commissionReceived(projectId, projectId, commission); } //Increment swap count in chain projects[projectId].chains[toChainID].swapCount = projects[projectId].chains[toChainID].swapCount.add(1); uint _swapCount = projects[projectId].chains[toChainID].swapCount; uint _chainID = _getChainID(); Swap memory swap = Swap({ swapCount: _swapCount, chainID: _chainID, from: msg.sender, to: to, amount: amount, isCompleted: false }); bytes32 swapId = keccak256(abi.encode(projectId, _swapCount, _chainID, toChainID, msg.sender, to, amount)); require(projects[projectId].swaps[swapId].swapCount == 0, "BRIDGEX: It's available just 1 swap with same: projectId, chainID, swapCount, from, to, amount"); projects[projectId].swaps[swapId] = swap; //Send oracle fees to oracle address if(msg.value > 0) { if (!oracleAddress.send(msg.value)) { oracleAddress.transfer(msg.value); } } emit SwapStart(projectId, swapId, _swapCount, toChainID, msg.sender, to, amount); } //Intermediate swap operation by oracle function swapEnd(bytes32 projectId, bytes32 swapId, uint swapCount, uint fromChainID, address from, address to, uint amount) public OnlyOracle onlyActiveChains(projectId, fromChainID) whenNotPaused { require(amount > 0 && to != address(0), "BRIDGEX: Primary Swap condition fail!"); require(amount <= projects[projectId].balance, "BRIDGEX: Not enough token balance in bridge contract"); uint _chainID = _getChainID(); bytes32 processedSwapId = keccak256(abi.encode(projectId, swapCount, fromChainID, _chainID, from, to, amount)); require(processedSwapId == swapId, "BRIDGEX: Swap ID Arguments do not match"); require(projects[projectId].swaps[processedSwapId].isCompleted == false, "BRIDGEX: Swap already completed!"); Swap memory swap = Swap({ swapCount: swapCount, chainID: fromChainID, from: from, to: to, amount: amount, isCompleted: true }); projects[projectId].swaps[processedSwapId] = swap; totalSwaps = totalSwaps.add(1); _transferToken(projectId, to, amount); emit SwapEnd(projectId, processedSwapId, swapCount, fromChainID, from, to, amount); } function setSwapComplete(bytes32 projectId, bytes32 swapId) external OnlyOracle{ require(projects[projectId].swaps[swapId].isCompleted == false, "BRIDGEX: Swap already completed!"); require(projects[projectId].swaps[swapId].swapCount != 0, "BRIDGEX: Event ID not found"); require(projects[projectId].swaps[swapId].chainID == _getChainID(), "BRIDGEX: Swap from another chain should be completed from swapEnd()"); projects[projectId].swaps[swapId].isCompleted = true; totalSwaps = totalSwaps.add(1); emit SwapCompleted(projectId, swapId); } //Token owner functions function configureAddSupply(bytes32 projectId, uint _supplyTokens) external onlyTokenOwner(projectId) { //Deposit tokens to the bridge pool require(IERC20(projects[projectId].tokenAddress).allowance(msg.sender, address(this)) >= _supplyTokens, "BRIDGEX: Not enough allowance"); IERC20(projects[projectId].tokenAddress).safeTransferFrom(msg.sender, address(this), _supplyTokens); projects[projectId].balance = projects[projectId].balance.add(_supplyTokens); } function configureRemoveSupply(bytes32 projectId, uint _pullOutTokens) external onlyTokenOwner(projectId) { require(projects[projectId].active == false, "BRIDGEX: Project status must be inactive."); require(_pullOutTokens <= projects[projectId].balance, "BRIDGEX: Project not enough balance."); _transferToken(projectId, msg.sender, _pullOutTokens); } function configureProjectSettings(bytes32 projectId, uint _maxAmount, bool _enableCommission, uint _swapCommissionPercent, address _swapCommissionReceiver) external onlyTokenOwner(projectId) { require(_swapCommissionReceiver != address(0), "BRIDGEX: Receiver address cannot be null"); require(_swapCommissionPercent < 10000, "BRIDGEX: Commission must be less than 10000"); require(projects[projectId].owner != address(0), "BRIDGEX: Project Not Found!"); projects[projectId].max_amount = _maxAmount; if(_enableCommission) { projects[projectId].swapCommissionPercent = _swapCommissionPercent; projects[projectId].swapCommissionReceiver = _swapCommissionReceiver; } else { projects[projectId].swapCommissionPercent = 0; projects[projectId].swapCommissionReceiver = address(0); } } function configureProjectStatus(bytes32 projectId, bool _status) external onlyTokenOwner(projectId) { require(projects[projectId].owner != address(0), "BRIDGEX: Project Not Found!"); projects[projectId].active = _status; emit projectStatusChanged(projectId, _status); } function configureTransferProjectOwner(bytes32 projectId, address _newOwner) external onlyTokenOwner(projectId) { require(projects[projectId].owner != address(0), "BRIDGEX: Project Not Found!"); projects[projectId].owner = _newOwner; } //Super Admin Functions function sudoSetMultipleProjectsOracleFee(bytes32[] memory projectIds, uint[] memory chainIds, uint[] memory bridge_minOracleFee, uint[] memory chain_minOracleFee) external onlyOwner { for(uint i = 0; i < projectIds.length; i++) { if(projects[projectIds[i]].owner != address(0)) { projects[projectIds[i]].minOracleFee = bridge_minOracleFee[i]; } else { continue; } //Set chain ID oracle fees for this project for(uint j = 0; j < chainIds.length; j++) { if(projects[projectIds[i]].chains[chainIds[j]].tokenAddress != address(0)) { projects[projectIds[i]].chains[chainIds[j]].minOracleFee = chain_minOracleFee[j]; } } } } function sudoSetMultipleProjectsStatus(bytes32[] memory projectIds, bool[] memory _status) external onlyOwner { for(uint i = 0; i < projectIds.length; i++) { if(projects[projectIds[i]].owner != address(0)) { projects[projectIds[i]].active = _status[i]; emit projectStatusChanged(projectIds[i], _status[i]); } } } function sudoConfigureTokenOwner(bytes32 projectId, address _owner) external onlyOwner { projects[projectId].owner = _owner; } function sudoConfigureChain(bytes32 projectId, uint chainID, address token_address, bool status, uint minOracleFee) external onlyOwner { require(chainID != _getChainID(), "BRIDGEX: Can`t change chain to current Chain ID"); require(projects[projectId].chains[chainID].tokenAddress != address(0), "BRIDGEX: Chain is not registered"); projects[projectId].chains[chainID].tokenAddress = token_address; projects[projectId].chains[chainID].active = status; projects[projectId].chains[chainID].minOracleFee = minOracleFee; } function sudoVerifyProjectWithOwner(bytes32 projectId) external onlyOwner { projects[projectId].ownerVerified = true; } function sudoAdjustProjectBalance(bytes32 projectId, uint _correctedAmount) external onlyOwner { projects[projectId].balance = _correctedAmount; } function sudoDeleteProject(bytes32 projectId) external onlyOwner { delete projects[projectId]; totalProjects--; } function sudoChangeProviderAddress(address payable _newAddress) external onlyOwner { SERVICE_PROVIDER_ADDRESS = _newAddress; } function changeCreationCost(uint _newCost) public OnlyOracle { PROJECT_CREATION_COST = _newCost; } //Creation Functions function createNewProject(bytes32 projectId, bool firstTimeChain, address[] calldata addressArray, uint[] calldata uintArray, uint _addSupply) external payable returns(bytes32) { require(msg.sender == owner() || msg.value.mul(1 gwei) >= PROJECT_CREATION_COST, "BRIDGEX: Insufficient amount sent to create project."); bytes32 newProjectId; if(firstTimeChain) { newProjectId = keccak256(abi.encode(addressArray[0], addressArray[1])); } else { newProjectId = projectId; } require(projects[newProjectId].tokenAddress == address(0), "BRIDGEX: Project already created!"); Project storage project = projects[newProjectId]; project.tokenAddress = addressArray[0]; project.active = true; project.owner = addressArray[1]; project.max_amount = uintArray[0]; project.swapCommissionPercent = uintArray[1]; project.swapCommissionReceiver = addressArray[2]; project.minOracleFee = uintArray[2]; totalProjects++; //Send creation cost to relay wallet if(msg.value > 0) { if (!SERVICE_PROVIDER_ADDRESS.send(msg.value)) { SERVICE_PROVIDER_ADDRESS.transfer(msg.value); } } //Deposit tokens to the bridge pool require(IERC20(projects[newProjectId].tokenAddress).allowance(msg.sender, address(this)) >= _addSupply, "BRIDGEX: Not enough allowance"); IERC20(projects[newProjectId].tokenAddress).safeTransferFrom(msg.sender, address(this), _addSupply); projects[newProjectId].balance = projects[newProjectId].balance.add(_addSupply); //Emit event new project created emit newProjectCreated(newProjectId, addressArray[0], addressArray[1], _addSupply); return newProjectId; } //Token Owner Add New Chain function addNewChainToProject(bytes32 projectId, uint _chainID, address _tokenAddress, uint _minOracleFee) public onlyTokenOwner(projectId) returns(bool){ require(_chainID != _getChainID(), "ORACLE: Can`t add current chain ID"); require(projects[projectId].chains[_chainID].tokenAddress == address(0), "ORACLE: ChainID has already been registered"); Chain memory chain = Chain({ tokenAddress: _tokenAddress, active: true, swapCount: 0, minOracleFee: _minOracleFee }); projects[projectId].chains[_chainID] = chain; emit newProjectChainCreated(projectId, _chainID, _tokenAddress); return true; } //Helper Functions function pause() external onlyOwner whenNotPaused { _pause(); emit Paused(msg.sender); } function unpause() external onlyOwner whenPaused { _unpause(); emit Unpaused(msg.sender); } function _transferToken(bytes32 projectId, address to, uint amount) private { IERC20(projects[projectId].tokenAddress).safeTransfer(to, amount); projects[projectId].balance = projects[projectId].balance.sub(amount); } function _depositToken(bytes32 projectId, uint amount) private { IERC20(projects[projectId].tokenAddress).safeTransferFrom(msg.sender, address(this), amount); projects[projectId].balance = projects[projectId].balance.add(amount); } //Calculates Commission to be sent to token owner function calculateCommission(bytes32 projectId, uint amount) public view returns(uint fee){ fee = projects[projectId].swapCommissionReceiver != address(0) ? amount.mul(projects[projectId].swapCommissionPercent).div(10000) : 0; } //Internal function to send commission function _withdrawCommission(bytes32 projectId, uint commission) internal{ if(commission > 0 && projects[projectId].swapCommissionReceiver != address(0)){ _transferToken(projectId, projects[projectId].swapCommissionReceiver, commission); } } function _getChainID() internal view returns (uint) { uint id; assembly { id := chainid() } return id; } function _isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } //DAPP helper functions //Get token balance of a project function seeProjectTokenBalance(bytes32 projectId) public view returns(uint balanceOf){ return projects[projectId].balance; } //Get Token balance by contract address function seeAnyTokenBalance(address tokenAddress) public view returns(uint balanceOf){ return IERC20(tokenAddress).balanceOf(address(this)); } //Get swapData by Swapid function seeSwapData(bytes32 projectId, bytes32 swapId) public view returns(uint counter, uint chainID, address from, uint amount, bool isCompleted){ return ( projects[projectId].swaps[swapId].swapCount, projects[projectId].swaps[swapId].chainID, projects[projectId].swaps[swapId].from, projects[projectId].swaps[swapId].amount, projects[projectId].swaps[swapId].isCompleted ); } //Get chainData by chainId function seeChainData(bytes32 projectId, uint chainId) public view returns(address tokenAddress, bool active, uint swapCount, uint minOracleFee){ return ( projects[projectId].chains[chainId].tokenAddress, projects[projectId].chains[chainId].active, projects[projectId].chains[chainId].swapCount, projects[projectId].chains[chainId].minOracleFee ); } //Emergency Functions //Emergency Withdraw Tokens sent to contract function emergencyWithdrawTokens(address _tokenAddress, address _toAddress, uint256 _amount) external onlyOwner { IERC20(_tokenAddress).safeTransfer(_toAddress, _amount); } //Emergency withdraw Primary Coin sent to contract function emergencyWithdrawAsset(address payable toAddress) external onlyOwner { if(!toAddress.send(address(this).balance)) { return toAddress.transfer(address(this).balance); } } }
Intermediate swap operation by oracle
function swapEnd(bytes32 projectId, bytes32 swapId, uint swapCount, uint fromChainID, address from, address to, uint amount) public OnlyOracle onlyActiveChains(projectId, fromChainID) whenNotPaused { require(amount > 0 && to != address(0), "BRIDGEX: Primary Swap condition fail!"); require(amount <= projects[projectId].balance, "BRIDGEX: Not enough token balance in bridge contract"); uint _chainID = _getChainID(); bytes32 processedSwapId = keccak256(abi.encode(projectId, swapCount, fromChainID, _chainID, from, to, amount)); require(processedSwapId == swapId, "BRIDGEX: Swap ID Arguments do not match"); require(projects[projectId].swaps[processedSwapId].isCompleted == false, "BRIDGEX: Swap already completed!"); Swap memory swap = Swap({ swapCount: swapCount, chainID: fromChainID, from: from, to: to, amount: amount, isCompleted: true }); projects[projectId].swaps[processedSwapId] = swap; totalSwaps = totalSwaps.add(1); _transferToken(projectId, to, amount); emit SwapEnd(projectId, processedSwapId, swapCount, fromChainID, from, to, amount); }
2,448,725
[ 1, 2465, 6785, 7720, 1674, 635, 20865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7720, 1638, 12, 3890, 1578, 9882, 16, 1731, 1578, 7720, 548, 16, 2254, 7720, 1380, 16, 2254, 628, 3893, 734, 16, 1758, 628, 16, 1758, 358, 16, 2254, 3844, 13, 1071, 5098, 23601, 1338, 3896, 15945, 12, 4406, 548, 16, 628, 3893, 734, 13, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 8949, 405, 374, 597, 358, 480, 1758, 12, 20, 3631, 315, 7192, 734, 43, 2294, 30, 15884, 12738, 2269, 2321, 4442, 1769, 203, 3639, 2583, 12, 8949, 1648, 10137, 63, 4406, 548, 8009, 12296, 16, 315, 7192, 734, 43, 2294, 30, 2288, 7304, 1147, 11013, 316, 10105, 6835, 8863, 203, 3639, 2254, 389, 5639, 734, 273, 389, 588, 3893, 734, 5621, 203, 203, 3639, 1731, 1578, 5204, 12521, 548, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 4406, 548, 16, 7720, 1380, 16, 628, 3893, 734, 16, 389, 5639, 734, 16, 628, 16, 358, 16, 3844, 10019, 203, 3639, 2583, 12, 11005, 12521, 548, 422, 7720, 548, 16, 315, 7192, 734, 43, 2294, 30, 12738, 1599, 13599, 741, 486, 845, 8863, 203, 3639, 2583, 12, 13582, 63, 4406, 548, 8009, 5328, 6679, 63, 11005, 12521, 548, 8009, 291, 9556, 422, 629, 16, 315, 7192, 734, 43, 2294, 30, 12738, 1818, 5951, 4442, 1769, 203, 540, 203, 3639, 12738, 3778, 7720, 273, 12738, 12590, 203, 5411, 7720, 1380, 30, 7720, 1380, 16, 203, 5411, 27756, 30, 628, 3893, 734, 16, 203, 5411, 628, 30, 628, 16, 203, 5411, 358, 30, 358, 16, 203, 5411, 3844, 30, 3844, 16, 203, 2 ]
//Address: 0x4221eb87b28de194e916f2b09274471fb0b01b1c //Contract name: TrueDeckToken //Balance: 0 Ether //Verification Date: 5/29/2018 //Transacion Count: 19 // CODE STARTS HERE pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @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 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 ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title PoSTokenStandard * @dev the interface of PoSTokenStandard */ contract PoSTokenStandard { uint256 public stakeStartTime; uint256 public stakeMinAge; uint256 public stakeMaxAge; function mint() public returns (bool); function coinAge() public view returns (uint256); function annualInterest() public view returns (uint256); function calculateReward() public view returns (uint256); function calculateRewardAt(uint256 _now) public view returns (uint256); event Mint( address indexed _address, uint256 _reward ); } /** * @title TrueDeck TDP Token * @dev ERC20, PoS Token for TrueDeck Platform */ contract TrueDeckToken is ERC20, PoSTokenStandard, Pausable { using SafeMath for uint256; event CoinAgeRecordEvent( address indexed who, uint256 value, uint64 time ); event CoinAgeResetEvent( address indexed who, uint256 value, uint64 time ); string public constant name = "TrueDeck"; string public constant symbol = "TDP"; uint8 public constant decimals = 18; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 totalSupply_; /** * @dev Total Number of TDP tokens that can ever be created. * 200M TDP Tokens */ uint256 public MAX_TOTAL_SUPPLY = 200000000 * 10 ** uint256(decimals); /** * @dev Initial supply of TDP tokens. * 70M TDP Tokens * 35% of Maximum Total Supply * Will be distributed as follows: * 5% : Platform Partners * 1% : Pre-Airdrop * 15% : Mega-Airdrop * 4% : Bounty (Vested over 6 months) * 10% : Development (Vested over 12 months) */ uint256 public INITIAL_SUPPLY = 70000000 * 10 ** uint256(decimals); /** * @dev Time at which the contract was deployed */ uint256 public chainStartTime; /** * @dev Ethereum Blockchain Block Number at time the contract was deployed */ uint256 public chainStartBlockNumber; /** * @dev To keep the record of a single incoming token transfer */ struct CoinAgeRecord { uint256 amount; uint64 time; } /** * @dev To keep the coin age record for all addresses */ mapping(address => CoinAgeRecord[]) coinAgeRecordMap; /** * @dev Modifier to make contract mint new tokens only * - Staking has started. * - When total supply has not reached MAX_TOTAL_SUPPLY. */ modifier canMint() { require(stakeStartTime > 0 && now >= stakeStartTime && totalSupply_ < MAX_TOTAL_SUPPLY); // solium-disable-line _; } constructor() public { chainStartTime = now; // solium-disable-line chainStartBlockNumber = block.number; stakeMinAge = 3 days; stakeMaxAge = 60 days; balances[msg.sender] = INITIAL_SUPPLY; totalSupply_ = INITIAL_SUPPLY; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); if (msg.sender == _to) { return mint(); } require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); logCoinAgeRecord(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused 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); // Coin age should not be recorded if receiver is the sender. if (_from != _to) { logCoinAgeRecord(_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 whenNotPaused returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public whenNotPaused returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotPaused returns (bool) { require(_spender != address(0)); 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 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 Mints new TDP token and rewards to caller as per the coin age. * Deletes all previous coinage records and resets with new coin age record. */ function mint() public whenNotPaused canMint returns (bool) { if (balances[msg.sender] <= 0) { return false; } if (coinAgeRecordMap[msg.sender].length <= 0) { return false; } uint256 reward = calculateRewardInternal(msg.sender, now); // solium-disable-line if (reward <= 0) { return false; } if (reward > MAX_TOTAL_SUPPLY.sub(totalSupply_)) { reward = MAX_TOTAL_SUPPLY.sub(totalSupply_); } totalSupply_ = totalSupply_.add(reward); balances[msg.sender] = balances[msg.sender].add(reward); emit Mint(msg.sender, reward); emit Transfer(address(0), msg.sender, reward); uint64 _now = uint64(now); // solium-disable-line delete coinAgeRecordMap[msg.sender]; coinAgeRecordMap[msg.sender].push(CoinAgeRecord(balances[msg.sender], _now)); emit CoinAgeResetEvent(msg.sender, balances[msg.sender], _now); return true; } /** * @dev Returns coinage for the caller address */ function coinAge() public view returns (uint256) { return getCoinAgeInternal(msg.sender, now); // solium-disable-line } /** * @dev Returns current annual interest */ function annualInterest() public view returns(uint256) { return getAnnualInterest(now); // solium-disable-line } /** * @dev Calculates and returns proof-of-stake reward */ function calculateReward() public view returns (uint256) { return calculateRewardInternal(msg.sender, now); // solium-disable-line } /** * @dev Calculates and returns proof-of-stake reward for provided time * * @param _now timestamp The time for which the reward will be calculated */ function calculateRewardAt(uint256 _now) public view returns (uint256) { return calculateRewardInternal(msg.sender, _now); } /** * @dev Returns coinage record for the given address and index * * @param _address address The address for which coinage record will be fetched * @param _index index The index of coinage record for that address */ function coinAgeRecordForAddress(address _address, uint256 _index) public view onlyOwner returns (uint256, uint64) { if (coinAgeRecordMap[_address].length > _index) { return (coinAgeRecordMap[_address][_index].amount, coinAgeRecordMap[_address][_index].time); } else { return (0, 0); } } /** * @dev Returns coinage for the caller address * * @param _address address The address for which coinage will be calculated */ function coinAgeForAddress(address _address) public view onlyOwner returns (uint256) { return getCoinAgeInternal(_address, now); // solium-disable-line } /** * @dev Returns coinage for the caller address * * @param _address address The address for which coinage will be calculated * @param _now timestamp The time for which the coinage will be calculated */ function coinAgeForAddressAt(address _address, uint256 _now) public view onlyOwner returns (uint256) { return getCoinAgeInternal(_address, _now); } /** * @dev Calculates and returns proof-of-stake reward for provided address and time * * @param _address address The address for which reward will be calculated */ function calculateRewardForAddress(address _address) public view onlyOwner returns (uint256) { return calculateRewardInternal(_address, now); // solium-disable-line } /** * @dev Calculates and returns proof-of-stake reward for provided address and time * * @param _address address The address for which reward will be calculated * @param _now timestamp The time for which the reward will be calculated */ function calculateRewardForAddressAt(address _address, uint256 _now) public view onlyOwner returns (uint256) { return calculateRewardInternal(_address, _now); } /** * @dev Sets the stake start time */ function startStakingAt(uint256 timestamp) public onlyOwner { require(stakeStartTime <= 0 && timestamp >= chainStartTime && timestamp > now); // solium-disable-line stakeStartTime = timestamp; } /** * @dev Returns true if the given _address is a contract, false otherwise. */ function isContract(address _address) private view returns (bool) { uint256 length; /* solium-disable-next-line */ assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_address) } return (length>0); } /** * @dev Logs coinage record for sender and receiver. * Deletes sender's previous coinage records if any. * Doesn't record coinage for contracts. * * @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 logCoinAgeRecord(address _from, address _to, uint256 _value) private returns (bool) { if (coinAgeRecordMap[_from].length > 0) { delete coinAgeRecordMap[_from]; } uint64 _now = uint64(now); // solium-disable-line if (balances[_from] != 0 && !isContract(_from)) { coinAgeRecordMap[_from].push(CoinAgeRecord(balances[_from], _now)); emit CoinAgeResetEvent(_from, balances[_from], _now); } if (_value != 0 && !isContract(_to)) { coinAgeRecordMap[_to].push(CoinAgeRecord(_value, _now)); emit CoinAgeRecordEvent(_to, _value, _now); } return true; } /** * @dev Calculates and returns proof-of-stake reward for provided address * * @param _address address The address for which reward will be calculated * @param _now timestamp The time for which the reward will be calculated */ function calculateRewardInternal(address _address, uint256 _now) private view returns (uint256) { uint256 _coinAge = getCoinAgeInternal(_address, _now); if (_coinAge <= 0) { return 0; } uint256 interest = getAnnualInterest(_now); return (_coinAge.mul(interest)).div(365 * 100); } /** * @dev Calculates the coin age for given address and time. * * @param _address address The address for which coinage will be calculated * @param _now timestamp The time for which the coinage will be calculated */ function getCoinAgeInternal(address _address, uint256 _now) private view returns (uint256 _coinAge) { if (coinAgeRecordMap[_address].length <= 0) { return 0; } for (uint256 i = 0; i < coinAgeRecordMap[_address].length; i++) { if (_now < uint256(coinAgeRecordMap[_address][i].time).add(stakeMinAge)) { continue; } uint256 secondsPassed = _now.sub(uint256(coinAgeRecordMap[_address][i].time)); if (secondsPassed > stakeMaxAge ) { secondsPassed = stakeMaxAge; } _coinAge = _coinAge.add((coinAgeRecordMap[_address][i].amount).mul(secondsPassed.div(1 days))); } } /** * @dev Returns the annual interest rate for given time * * @param _now timestamp The time for which the annual interest will be calculated */ function getAnnualInterest(uint256 _now) private view returns(uint256 interest) { if (stakeStartTime > 0 && _now >= stakeStartTime && totalSupply_ < MAX_TOTAL_SUPPLY) { uint256 secondsPassed = _now.sub(stakeStartTime); // 1st Year = 30% annually if (secondsPassed <= 365 days) { interest = 30; } else if (secondsPassed <= 547 days) { // 2nd Year, 1st Half = 25% annually interest = 25; } else if (secondsPassed <= 730 days) { // 2nd Year, 2nd Half = 20% annually interest = 20; } else if (secondsPassed <= 911 days) { // 3rd Year, 1st Half = 15% annually interest = 15; } else if (secondsPassed <= 1094 days) { // 3rd Year, 2nd Half = 10% annually interest = 10; } else { // 4th Year Onwards = 5% annually interest = 5; } } else { interest = 0; } } /** * @dev Batch token transfer. Used by contract creator to distribute initial tokens. * Does not record any coinage for the owner. * * @param _recipients Array of address * @param _values Array of amount */ function batchTransfer(address[] _recipients, uint256[] _values) public onlyOwner returns (bool) { require(_recipients.length > 0 && _recipients.length == _values.length); uint256 total = 0; for(uint256 i = 0; i < _values.length; i++) { total = total.add(_values[i]); } require(total <= balances[msg.sender]); uint64 _now = uint64(now); // solium-disable-line for(uint256 j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); balances[msg.sender] = balances[msg.sender].sub(_values[j]); emit Transfer(msg.sender, _recipients[j], _values[j]); coinAgeRecordMap[_recipients[j]].push(CoinAgeRecord(_values[j], _now)); emit CoinAgeRecordEvent(_recipients[j], _values[j], _now); } return true; } }
* @dev Calculates and returns proof-of-stake reward for provided address and time @param _address address The address for which reward will be calculated/
function calculateRewardForAddress(address _address) public view onlyOwner returns (uint256) { }
898,963
[ 1, 10587, 471, 1135, 14601, 17, 792, 17, 334, 911, 19890, 364, 2112, 1758, 471, 813, 225, 389, 2867, 1758, 1021, 1758, 364, 1492, 19890, 903, 506, 8894, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 17631, 1060, 1290, 1887, 12, 2867, 389, 2867, 13, 1071, 1476, 1338, 5541, 1135, 261, 11890, 5034, 13, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.3; pragma experimental ABIEncoderV2; import "../../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import "../../node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol"; import "../../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title Rebloc Dataset * * http://www.rebloc.io/ * * ERC721 compliant dataset token * */ contract ReblocDatasetToken is ERC721Metadata("ReblocDatasetToken", "RDT"), IERC721Enumerable { using SafeMath for uint256; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * 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; address private operatorAccount; struct Dataset { bytes id; uint32 size; string fileHash; string ipfsHash; string compression; uint32 price; string pricingUnit; uint32 commission; } struct Validator { address validatorAddress; uint32 commission; } // A pointer to the next token to be minted, zero indexed uint256 public tokenIdPointer = 0; enum PurchaseState {Unsold, EtherPurchase, FiatPurchase} mapping(uint256 => PurchaseState) internal tokenIdToSell; mapping(uint256 => uint32) internal tokenIdToPurchaseFromTime; mapping(uint256 => Dataset) internal datasetInfo; mapping(uint256 => Validator[]) internal validator; event SoldWithEther( uint256 indexed _tokenId, address indexed _buyer); event SoldWithFiat(uint256 indexed _tokenId, address indexed _buyer); event SoldWithFiatReversed(uint256 indexed _tokenId, address indexed _buyer); event Approval (address indexed _address, uint256 indexed _tokenId); event MintToken (bytes _assetId, string _tokenURI, string _ipfsHash, uint32 _price, uint32 _size, uint256 indexed _tokenId, address indexed to); modifier onlyOwnedToken(uint256 _tokenId) { require(super.ownerOf(_tokenId) == msg.sender); _; } modifier onlyUnsold(uint256 _tokenId) { require(tokenIdToSell[_tokenId] == PurchaseState.Unsold); _; } modifier onlyOperator() { require(msg.sender == operatorAccount); _; } modifier onlyFiatSold(uint256 _tokenId) { require(tokenIdToSell[_tokenId] == PurchaseState.FiatPurchase); _; } modifier onlyAfterPurchaseFromTime(uint256 _tokenId) { require(tokenIdToPurchaseFromTime[_tokenId] <= block.timestamp); _; } // don't accept payment directly to contract function() external payable { revert(); } /** * @dev Utility function for updating a RDT assets price * @dev Reverts if token is not unsold or not called by management * @param _tokenId the RDT token ID */ function setPrice(uint _tokenId, uint32 _price, string memory _pricingUnit) public onlyUnsold(_tokenId) onlyOwnedToken (_tokenId) { require(_exists(_tokenId)); datasetInfo[_tokenId].price = _price; datasetInfo[_tokenId].pricingUnit = _pricingUnit; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } constructor (address _operatorAccount) public { if (_operatorAccount != address(0)) { operatorAccount = _operatorAccount; } else operatorAccount = msg.sender; _registerInterface(INTERFACE_ID_ERC721_ENUMERABLE); } function getOperatorAccount() public view returns (address) { return (operatorAccount); } /** * @dev Mint a new RDT token * @dev Reverts if not called by management * @param _id dataset id * @param _fileHash MD5 hash of compressed file * @param _compression compression algorithm gzip, ... * @param _ipfsHash IPFS file hash * @param _price settlement price * @param _pricingUnit usd, wei, eth, ... * @param _size file size */ function mint(bytes memory _id, string memory _fileHash, string memory _compression, string memory _ipfsHash, uint32 _size, uint32 _price, string memory _pricingUnit, string memory _tokenURI, address _toAddress) public onlyOperator() { uint256 _tokenId = tokenIdPointer; uint32 _initialCommission = 0; Dataset memory newDataset = Dataset({id: _id, fileHash: _fileHash, compression: _compression, ipfsHash: _ipfsHash, size: _size, price: _price, pricingUnit: _pricingUnit, commission: _initialCommission}); _mint(_toAddress, _tokenId); _ownedTokens[_toAddress].push(_tokenId); _populateTokenData(_tokenId, newDataset); super._setTokenURI(_tokenId, _tokenURI); tokenIdPointer = tokenIdPointer.add(1); emit MintToken (_id, _tokenURI, _ipfsHash, _price, _size, _tokenId, _toAddress); } /** * @dev Burns a RDT token * @dev Reverts if token is not unsold or not owned by management * @param _tokenId the RDT token ID */ function burn(uint256 _tokenId) public onlyUnsold(_tokenId) onlyOwnedToken(_tokenId) { require(_exists(_tokenId)); super._burn(ownerOf(_tokenId), _tokenId); delete datasetInfo[_tokenId]; delete tokenIdToPurchaseFromTime[_tokenId]; } /** * @dev Retrieve all asset information for the provided token * @param _tokenId the RDT token ID * @return tokenId, owner, purchaseState, purchaseFromDateTime, pricingUnit */ function getDatasetInfo(uint256 _tokenId) public view returns (Dataset memory) { return ( datasetInfo[_tokenId] ); } function tokensOf(address _owner) public view returns (uint256[] memory) { return _ownedTokens[_owner]; } /** * @dev Get the token purchase state for the given token * @param _tokenId the RDT token ID * @return the purchase sate, either 0, 1, 2, reverts if token not found */ function isPurchased(uint256 _tokenId) public view returns (PurchaseState) { require(_exists(_tokenId)); return tokenIdToSell[_tokenId]; } /** * @dev Get the purchase from time for the given token * @param _tokenId the RDT token ID * @return the purchased from time, reverts if token not found */ function purchaseFromTime(uint256 _tokenId) public view returns (uint32) { require(_exists(_tokenId)); return tokenIdToPurchaseFromTime[_tokenId]; } /** * @dev Purchase the provide token in Ether * @dev Reverts if token not unsold and not available to be purchased * msg.sender will become the owner of the token * msg.value needs to be >= to the token priceInWei * @param _tokenId the RDt token ID * @return true/false depending on success */ function purchaseWithEther(uint256 _tokenId, uint32 _commission, address _buyer) public payable onlyUnsold(_tokenId) { require(_exists(_tokenId)); require(stringsEqual(datasetInfo[_tokenId].pricingUnit, "wei")); require(msg.value >= datasetInfo[_tokenId].price); // approve sender as they have paid the required amount _approvePurchaser(_buyer, _tokenId); // transfer assets from contract creator (curator) to new owner safeTransferFrom(ownerOf(_tokenId), _buyer, _tokenId); // now purchased - don't allow re-purchase! tokenIdToSell[_tokenId] = PurchaseState.EtherPurchase; if (datasetInfo[_tokenId].price > 0) { _applyCommission(_tokenId, _commission); } emit SoldWithEther (_tokenId, _buyer); } /** * @dev Purchase the provide token in FIAT, management command only for taking fiat payments * during RDT physical exhibitions * Equivalent to taking the RDT token off the market and marking as sold * @dev Reverts if token not unsold and not available to be purchased and not called by management * @param _tokenId the RDT token ID */ function purchaseWithFiat(uint256 _tokenId, uint32 _commission, address _buyer) public onlyUnsold(_tokenId) { require(_exists(_tokenId)); _approvePurchaser(_buyer, _tokenId); // transfer assets from contract creator (curator) to new owner safeTransferFrom(ownerOf(_tokenId), _buyer, _tokenId); // now purchased - don't allow re-purchase! tokenIdToSell[_tokenId] = PurchaseState.FiatPurchase; if (datasetInfo[_tokenId].price > 0) { _applyCommission(_tokenId, _commission); } // now purchased - don't allow re-purchase! emit SoldWithFiat(_tokenId, _buyer); } /** * @dev Used to pre-approve a purchaser in order for internal purchase methods * to succeed without calling approve() directly * @param _tokenId the RDT token ID * @return address currently approved for a the given token ID */ function _approvePurchaser(address _to, uint256 _tokenId) internal { address owner = super.ownerOf(_tokenId); require(_to != address(0)); super.approve(_to, _tokenId); emit Approval(owner, _to, _tokenId); } function _populateTokenData(uint256 _tokenId, Dataset memory _dataset) internal { datasetInfo[_tokenId] = _dataset; } /** * @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 { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already _exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @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 */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] memory) { return _ownedTokens[owner]; } /** * @dev Internal function for apply commission on purchase */ function _applyCommission(uint256 _tokenId, uint32 _commission) internal { // pirce in cents for fiat in wei for crypto datasetInfo[_tokenId].commission = _commission; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the _ownedTokensIndex mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } function stringsEqual(string storage _a, string memory _b) internal returns (bool) { bytes storage a = bytes(_a); bytes memory b = bytes(_b); if (a.length != b.length) return false; for (uint i = 0; i < a.length; i++) if (a[i] != b[i]) return false; return true; } }
Mapping from owner to list of owned token IDs Mapping from token ID to index of the owner tokens list Array with all token ids, used for enumeration Mapping from token id to position in the allTokens array
contract ReblocDatasetToken is ERC721Metadata("ReblocDatasetToken", "RDT"), IERC721Enumerable { using SafeMath for uint256; mapping(address => uint256[]) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; address private operatorAccount; struct Dataset { bytes id; uint32 size; string fileHash; string ipfsHash; string compression; uint32 price; string pricingUnit; uint32 commission; } struct Validator { address validatorAddress; uint32 commission; } mapping(uint256 => PurchaseState) internal tokenIdToSell; mapping(uint256 => uint32) internal tokenIdToPurchaseFromTime; mapping(uint256 => Dataset) internal datasetInfo; mapping(uint256 => Validator[]) internal validator; event SoldWithEther( uint256 indexed _tokenId, address indexed _buyer); event SoldWithFiat(uint256 indexed _tokenId, address indexed _buyer); event SoldWithFiatReversed(uint256 indexed _tokenId, address indexed _buyer); event Approval (address indexed _address, uint256 indexed _tokenId); event MintToken (bytes _assetId, string _tokenURI, string _ipfsHash, uint32 _price, uint32 _size, uint256 indexed _tokenId, address indexed to); uint256 public tokenIdPointer = 0; enum PurchaseState {Unsold, EtherPurchase, FiatPurchase} modifier onlyOwnedToken(uint256 _tokenId) { require(super.ownerOf(_tokenId) == msg.sender); _; } modifier onlyUnsold(uint256 _tokenId) { require(tokenIdToSell[_tokenId] == PurchaseState.Unsold); _; } modifier onlyOperator() { require(msg.sender == operatorAccount); _; } modifier onlyFiatSold(uint256 _tokenId) { require(tokenIdToSell[_tokenId] == PurchaseState.FiatPurchase); _; } modifier onlyAfterPurchaseFromTime(uint256 _tokenId) { require(tokenIdToPurchaseFromTime[_tokenId] <= block.timestamp); _; } function() external payable { revert(); } function setPrice(uint _tokenId, uint32 _price, string memory _pricingUnit) public onlyUnsold(_tokenId) onlyOwnedToken (_tokenId) { require(_exists(_tokenId)); datasetInfo[_tokenId].price = _price; datasetInfo[_tokenId].pricingUnit = _pricingUnit; } function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function totalSupply() public view returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } constructor (address _operatorAccount) public { if (_operatorAccount != address(0)) { operatorAccount = _operatorAccount; } else operatorAccount = msg.sender; _registerInterface(INTERFACE_ID_ERC721_ENUMERABLE); } constructor (address _operatorAccount) public { if (_operatorAccount != address(0)) { operatorAccount = _operatorAccount; } else operatorAccount = msg.sender; _registerInterface(INTERFACE_ID_ERC721_ENUMERABLE); } function getOperatorAccount() public view returns (address) { return (operatorAccount); } function mint(bytes memory _id, string memory _fileHash, string memory _compression, string memory _ipfsHash, uint32 _size, uint32 _price, string memory _pricingUnit, string memory _tokenURI, address _toAddress) public onlyOperator() { uint256 _tokenId = tokenIdPointer; uint32 _initialCommission = 0; Dataset memory newDataset = Dataset({id: _id, fileHash: _fileHash, compression: _compression, ipfsHash: _ipfsHash, size: _size, price: _price, pricingUnit: _pricingUnit, commission: _initialCommission}); _mint(_toAddress, _tokenId); _ownedTokens[_toAddress].push(_tokenId); _populateTokenData(_tokenId, newDataset); super._setTokenURI(_tokenId, _tokenURI); tokenIdPointer = tokenIdPointer.add(1); emit MintToken (_id, _tokenURI, _ipfsHash, _price, _size, _tokenId, _toAddress); } function mint(bytes memory _id, string memory _fileHash, string memory _compression, string memory _ipfsHash, uint32 _size, uint32 _price, string memory _pricingUnit, string memory _tokenURI, address _toAddress) public onlyOperator() { uint256 _tokenId = tokenIdPointer; uint32 _initialCommission = 0; Dataset memory newDataset = Dataset({id: _id, fileHash: _fileHash, compression: _compression, ipfsHash: _ipfsHash, size: _size, price: _price, pricingUnit: _pricingUnit, commission: _initialCommission}); _mint(_toAddress, _tokenId); _ownedTokens[_toAddress].push(_tokenId); _populateTokenData(_tokenId, newDataset); super._setTokenURI(_tokenId, _tokenURI); tokenIdPointer = tokenIdPointer.add(1); emit MintToken (_id, _tokenURI, _ipfsHash, _price, _size, _tokenId, _toAddress); } function burn(uint256 _tokenId) public onlyUnsold(_tokenId) onlyOwnedToken(_tokenId) { require(_exists(_tokenId)); super._burn(ownerOf(_tokenId), _tokenId); delete datasetInfo[_tokenId]; delete tokenIdToPurchaseFromTime[_tokenId]; } function getDatasetInfo(uint256 _tokenId) public view returns (Dataset memory) { return ( datasetInfo[_tokenId] ); } function tokensOf(address _owner) public view returns (uint256[] memory) { return _ownedTokens[_owner]; } function isPurchased(uint256 _tokenId) public view returns (PurchaseState) { require(_exists(_tokenId)); return tokenIdToSell[_tokenId]; } function purchaseFromTime(uint256 _tokenId) public view returns (uint32) { require(_exists(_tokenId)); return tokenIdToPurchaseFromTime[_tokenId]; } function purchaseWithEther(uint256 _tokenId, uint32 _commission, address _buyer) public payable onlyUnsold(_tokenId) { require(_exists(_tokenId)); require(stringsEqual(datasetInfo[_tokenId].pricingUnit, "wei")); require(msg.value >= datasetInfo[_tokenId].price); _approvePurchaser(_buyer, _tokenId); safeTransferFrom(ownerOf(_tokenId), _buyer, _tokenId); tokenIdToSell[_tokenId] = PurchaseState.EtherPurchase; if (datasetInfo[_tokenId].price > 0) { _applyCommission(_tokenId, _commission); } emit SoldWithEther (_tokenId, _buyer); } function purchaseWithEther(uint256 _tokenId, uint32 _commission, address _buyer) public payable onlyUnsold(_tokenId) { require(_exists(_tokenId)); require(stringsEqual(datasetInfo[_tokenId].pricingUnit, "wei")); require(msg.value >= datasetInfo[_tokenId].price); _approvePurchaser(_buyer, _tokenId); safeTransferFrom(ownerOf(_tokenId), _buyer, _tokenId); tokenIdToSell[_tokenId] = PurchaseState.EtherPurchase; if (datasetInfo[_tokenId].price > 0) { _applyCommission(_tokenId, _commission); } emit SoldWithEther (_tokenId, _buyer); } function purchaseWithFiat(uint256 _tokenId, uint32 _commission, address _buyer) public onlyUnsold(_tokenId) { require(_exists(_tokenId)); _approvePurchaser(_buyer, _tokenId); safeTransferFrom(ownerOf(_tokenId), _buyer, _tokenId); tokenIdToSell[_tokenId] = PurchaseState.FiatPurchase; if (datasetInfo[_tokenId].price > 0) { _applyCommission(_tokenId, _commission); } } function purchaseWithFiat(uint256 _tokenId, uint32 _commission, address _buyer) public onlyUnsold(_tokenId) { require(_exists(_tokenId)); _approvePurchaser(_buyer, _tokenId); safeTransferFrom(ownerOf(_tokenId), _buyer, _tokenId); tokenIdToSell[_tokenId] = PurchaseState.FiatPurchase; if (datasetInfo[_tokenId].price > 0) { _applyCommission(_tokenId, _commission); } } emit SoldWithFiat(_tokenId, _buyer); function _approvePurchaser(address _to, uint256 _tokenId) internal { address owner = super.ownerOf(_tokenId); require(_to != address(0)); super.approve(_to, _tokenId); emit Approval(owner, _to, _tokenId); } function _populateTokenData(uint256 _tokenId, Dataset memory _dataset) internal { datasetInfo[_tokenId] = _dataset; } function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } function _tokensOfOwner(address owner) internal view returns (uint256[] memory) { return _ownedTokens[owner]; } function _applyCommission(uint256 _tokenId, uint32 _commission) internal { datasetInfo[_tokenId].commission = _commission; } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } _ownedTokens[from].length--; } function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens.length--; _allTokensIndex[tokenId] = 0; } function stringsEqual(string storage _a, string memory _b) internal returns (bool) { bytes storage a = bytes(_a); bytes memory b = bytes(_b); if (a.length != b.length) return false; for (uint i = 0; i < a.length; i++) if (a[i] != b[i]) return false; return true; } }
5,501,599
[ 1, 3233, 628, 3410, 358, 666, 434, 16199, 1147, 7115, 9408, 628, 1147, 1599, 358, 770, 434, 326, 3410, 2430, 666, 1510, 598, 777, 1147, 3258, 16, 1399, 364, 16836, 9408, 628, 1147, 612, 358, 1754, 316, 326, 777, 5157, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 868, 70, 1829, 10656, 1345, 353, 4232, 39, 27, 5340, 2277, 2932, 426, 70, 1829, 10656, 1345, 3113, 315, 54, 9081, 6, 3631, 467, 654, 39, 27, 5340, 3572, 25121, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 63, 5717, 3238, 389, 995, 329, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 995, 329, 5157, 1016, 31, 203, 203, 565, 2254, 5034, 8526, 3238, 389, 454, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 454, 5157, 1016, 31, 203, 203, 565, 1731, 24, 3238, 5381, 11391, 11300, 67, 734, 67, 654, 39, 27, 5340, 67, 16509, 654, 2782, 273, 374, 92, 27, 3672, 73, 29, 72, 4449, 31, 203, 203, 565, 1758, 3238, 3726, 3032, 31, 203, 203, 203, 565, 1958, 10778, 288, 203, 3639, 1731, 612, 31, 203, 3639, 2254, 1578, 963, 31, 203, 3639, 533, 585, 2310, 31, 203, 3639, 533, 2359, 2556, 2310, 31, 203, 3639, 533, 9154, 31, 203, 3639, 2254, 1578, 6205, 31, 203, 3639, 533, 31765, 2802, 31, 203, 3639, 2254, 1578, 1543, 19710, 31, 203, 565, 289, 203, 203, 565, 1958, 9150, 288, 203, 3639, 1758, 4213, 1887, 31, 203, 3639, 2254, 1578, 1543, 19710, 31, 7010, 565, 289, 203, 377, 203, 203, 565, 2874, 12, 11890, 5034, 516, 26552, 1119, 13, 2713, 1147, 28803, 55, 1165, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 1578, 13, 2713, 1147, 28803, 23164, 2 ]
./full_match/1/0xB2c657fA38D3b0B3D0eC4113c6d9Fcc331c96E27/sources/ElonEarth.sol
* @dev Sets the values for {name} and {symbol}. The defaut value of {decimals} is 18. To select a different value for {decimals} you should overload it. All two of these values are immutable: they can only be set once during construction./ MainNet / testnet, Uniswap Router set the rest of the contract variables
constructor () { _mint(0x5417B00775036C1F8635743d0D24ED5Eb1E98e6d, 1000000000 *10**18); _enable[0x5417B00775036C1F8635743d0D24ED5Eb1E98e6d] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _name = "ElonEarth"; _symbol = "eEarth"; }
8,409,749
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5496, 1021, 443, 507, 322, 460, 434, 288, 31734, 97, 353, 6549, 18, 2974, 2027, 279, 3775, 460, 364, 288, 31734, 97, 1846, 1410, 30402, 518, 18, 4826, 2795, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 18, 19, 12740, 7308, 342, 1842, 2758, 16, 1351, 291, 91, 438, 9703, 444, 326, 3127, 434, 326, 6835, 3152, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 288, 203, 203, 3639, 389, 81, 474, 12, 20, 92, 6564, 4033, 38, 713, 4700, 3361, 5718, 39, 21, 42, 28, 4449, 25, 21609, 72, 20, 40, 3247, 2056, 25, 41, 70, 21, 41, 10689, 73, 26, 72, 16, 15088, 3784, 380, 2163, 636, 2643, 1769, 203, 3639, 389, 7589, 63, 20, 92, 6564, 4033, 38, 713, 4700, 3361, 5718, 39, 21, 42, 28, 4449, 25, 21609, 72, 20, 40, 3247, 2056, 25, 41, 70, 21, 41, 10689, 73, 26, 72, 65, 273, 638, 31, 203, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 540, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 540, 203, 3639, 389, 529, 273, 315, 4958, 265, 41, 27076, 14432, 203, 3639, 389, 7175, 273, 315, 73, 41, 27076, 14432, 203, 565, 289, 203, 203, 2 ]
./full_match/42220/0x12600aAA0cbA56811b137Ec014b67B52DE5dAB27/sources/contracts/router/UbeswapMoolaRouterBase.sol
@dev Handles the swap after the plan is executed
function _swapConvertOut( UbeswapMoolaRouterLibrary.SwapPlan memory _plan, uint256[] memory _routerAmounts, address[] calldata _path, address _to ) internal returns (uint256[] memory amounts) { amounts = UbeswapMoolaRouterLibrary.computeAmountsFromRouterAmounts( _routerAmounts, _plan.reserveIn, _plan.reserveOut ); if (_plan.reserveOut != address(0)) { _convert( _plan.reserveOut, amounts[amounts.length - 1], _plan.depositOut, Reason.CONVERT_OUT ); } emit TokensSwapped( msg.sender, _path, _to, amounts[0], amounts[amounts.length - 1] ); }
16,340,989
[ 1, 8788, 326, 7720, 1839, 326, 4995, 353, 7120, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 22270, 2723, 1182, 12, 203, 3639, 587, 70, 281, 91, 438, 49, 1371, 69, 8259, 9313, 18, 12521, 5365, 3778, 389, 7088, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 10717, 6275, 87, 16, 203, 3639, 1758, 8526, 745, 892, 389, 803, 16, 203, 3639, 1758, 389, 869, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 8526, 3778, 30980, 13, 288, 203, 3639, 30980, 273, 587, 70, 281, 91, 438, 49, 1371, 69, 8259, 9313, 18, 9200, 6275, 87, 1265, 8259, 6275, 87, 12, 203, 5411, 389, 10717, 6275, 87, 16, 203, 5411, 389, 7088, 18, 455, 6527, 382, 16, 203, 5411, 389, 7088, 18, 455, 6527, 1182, 203, 3639, 11272, 203, 3639, 309, 261, 67, 7088, 18, 455, 6527, 1182, 480, 1758, 12, 20, 3719, 288, 203, 5411, 389, 6283, 12, 203, 7734, 389, 7088, 18, 455, 6527, 1182, 16, 203, 7734, 30980, 63, 8949, 87, 18, 2469, 300, 404, 6487, 203, 7734, 389, 7088, 18, 323, 1724, 1182, 16, 203, 7734, 13558, 18, 2248, 21654, 67, 5069, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 3626, 13899, 12521, 1845, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 389, 803, 16, 203, 5411, 389, 869, 16, 203, 5411, 30980, 63, 20, 6487, 203, 5411, 30980, 63, 8949, 87, 18, 2469, 300, 404, 65, 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 ]
pragma solidity 0.4.24; pragma experimental ABIEncoderV2; //Truffle Imports import "@chainlink/contracts/ChainlinkClient.sol"; import "@chainlink/contracts/vendor/Ownable.sol"; import "@chainlink/contracts/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/interfaces/AggregatorInterface.sol"; import "@chainlink/contracts/vendor/SafeMathChainlink.sol"; import "@chainlink/contracts/interfaces/AggregatorV3Interface.sol"; //Remix imports - used when testing in remix //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/ChainlinkClient.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/vendor/Ownable.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/LinkTokenInterface.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/AggregatorInterface.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/vendor/SafeMathChainlink.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/AggregatorV3Interface.sol"; contract InsuranceProvider { using SafeMathChainlink for uint; address public insurer = msg.sender; AggregatorV3Interface internal priceFeed; uint public constant DAY_IN_SECONDS = 60; //How many seconds in a day. 60 for testing, 86400 for Production uint256 constant private ORACLE_PAYMENT = 0.1 * 10**18; // 0.1 LINK address public constant LINK_KOVAN = 0xa36085F69e2889c224210F603D836748e7dC0088 ; //address of LINK token on Kovan //here is where all the insurance contracts are stored. mapping (address => InsuranceContract) contracts; constructor() public payable { priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); } /** * @dev Prevents a function being run unless it's called by the Insurance Provider */ modifier onlyOwner() { require(insurer == msg.sender,'Only Insurance provider can do this'); _; } /** * @dev Event to log when a contract is created */ event contractCreated(address _insuranceContract, uint _premium, uint _totalCover); /** * @dev Create a new contract for client, automatically approved and deployed to the blockchain */ function newContract(address _client, uint _duration, uint _premium, uint _payoutValue, string _cropLocation) public payable onlyOwner() returns(address) { //create contract, send payout amount so contract is fully funded plus a small buffer InsuranceContract i = (new InsuranceContract).value((_payoutValue * 1 ether).div(uint(getLatestPrice())))(_client, _duration, _premium, _payoutValue, _cropLocation, LINK_KOVAN,ORACLE_PAYMENT); contracts[address(i)] = i; //store insurance contract in contracts Map //emit an event to say the contract has been created and funded emit contractCreated(address(i), msg.value, _payoutValue); //now that contract has been created, we need to fund it with enough LINK tokens to fulfil 1 Oracle request per day, with a small buffer added LinkTokenInterface link = LinkTokenInterface(i.getChainlinkToken()); link.transfer(address(i), ((_duration.div(DAY_IN_SECONDS)) + 2) * ORACLE_PAYMENT.mul(2)); return address(i); } /** * @dev returns the contract for a given address */ function getContract(address _contract) external view returns (InsuranceContract) { return contracts[_contract]; } /** * @dev updates the contract for a given address */ function updateContract(address _contract) external { InsuranceContract i = InsuranceContract(_contract); i.updateContract(); } /** * @dev gets the current rainfall for a given contract address */ function getContractRainfall(address _contract) external view returns(uint) { InsuranceContract i = InsuranceContract(_contract); return i.getCurrentRainfall(); } /** * @dev gets the current rainfall for a given contract address */ function getContractRequestCount(address _contract) external view returns(uint) { InsuranceContract i = InsuranceContract(_contract); return i.getRequestCount(); } /** * @dev Get the insurer address for this insurance provider */ function getInsurer() external view returns (address) { return insurer; } /** * @dev Get the status of a given Contract */ function getContractStatus(address _address) external view returns (bool) { InsuranceContract i = InsuranceContract(_address); return i.getContractStatus(); } /** * @dev Return how much ether is in this master contract */ function getContractBalance() external view returns (uint) { return address(this).balance; } /** * @dev Function to end provider contract, in case of bugs or needing to update logic etc, funds are returned to insurance provider, including any remaining LINK tokens */ function endContractProvider() external payable onlyOwner() { LinkTokenInterface link = LinkTokenInterface(LINK_KOVAN); require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer"); selfdestruct(insurer); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; } /** * @dev fallback function, to receive ether */ function() external payable { } } contract InsuranceContract is ChainlinkClient, Ownable { using SafeMathChainlink for uint; AggregatorV3Interface internal priceFeed; uint public constant DAY_IN_SECONDS = 60; //How many seconds in a day. 60 for testing, 86400 for Production uint public constant DROUGHT_DAYS_THRESDHOLD = 3 ; //Number of consecutive days without rainfall to be defined as a drought uint256 private oraclePaymentAmount; address public insurer; address client; uint startDate; uint duration; uint premium; uint payoutValue; string cropLocation; uint256[2] public currentRainfallList; bytes32[2] public jobIds; address[2] public oracles; string constant WORLD_WEATHER_ONLINE_URL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?"; string constant WORLD_WEATHER_ONLINE_KEY = "629c6dd09bbc4364b7a33810200911"; string constant WORLD_WEATHER_ONLINE_PATH = "data.current_condition.0.precipMM"; string constant OPEN_WEATHER_URL = "https://openweathermap.org/data/2.5/weather?"; string constant OPEN_WEATHER_KEY = "b4e40205aeb3f27b74333393de24ca79"; string constant OPEN_WEATHER_PATH = "rain.1h"; string constant WEATHERBIT_URL = "https://api.weatherbit.io/v2.0/current?"; string constant WEATHERBIT_KEY = "5e05aef07410401fac491b06eb9e8fc8"; string constant WEATHERBIT_PATH = "data.0.precip"; uint daysWithoutRain; //how many days there has been with 0 rain bool contractActive; //is the contract currently active, or has it ended bool contractPaid = false; uint currentRainfall = 0; //what is the current rainfall for the location uint currentRainfallDateChecked = now; //when the last rainfall check was performed uint requestCount = 0; //how many requests for rainfall data have been made so far for this insurance contract uint dataRequestsSent = 0; //variable used to determine if both requests have been sent or not /** * @dev Prevents a function being run unless it's called by Insurance Provider */ modifier onlyOwner() { require(insurer == msg.sender,'Only Insurance provider can do this'); _; } /** * @dev Prevents a function being run unless the Insurance Contract duration has been reached */ modifier onContractEnded() { if (startDate + duration < now) { _; } } /** * @dev Prevents a function being run unless contract is still active */ modifier onContractActive() { require(contractActive == true ,'Contract has ended, cant interact with it anymore'); _; } /** * @dev Prevents a data request to be called unless it's been a day since the last call (to avoid spamming and spoofing results) * apply a tolerance of 2/24 of a day or 2 hours. */ modifier callFrequencyOncePerDay() { require(now.sub(currentRainfallDateChecked) > (DAY_IN_SECONDS.sub(DAY_IN_SECONDS.div(12))),'Can only check rainfall once per day'); _; } event contractCreated(address _insurer, address _client, uint _duration, uint _premium, uint _totalCover); event contractPaidOut(uint _paidTime, uint _totalPaid, uint _finalRainfall); event contractEnded(uint _endTime, uint _totalReturned); event ranfallThresholdReset(uint _rainfall); event dataRequestSent(bytes32 requestId); event dataReceived(uint _rainfall); /** * @dev Creates a new Insurance contract */ constructor(address _client, uint _duration, uint _premium, uint _payoutValue, string _cropLocation, address _link, uint256 _oraclePaymentAmount) payable Ownable() public { //set ETH/USD Price Feed priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); //initialize variables required for Chainlink Network interaction setChainlinkToken(_link); oraclePaymentAmount = _oraclePaymentAmount; //first ensure insurer has fully funded the contract require(msg.value >= _payoutValue.div(uint(getLatestPrice())), "Not enough funds sent to contract"); //now initialize values for the contract insurer= msg.sender; client = _client; startDate = now ; //contract will be effective immediately on creation duration = _duration; premium = _premium; payoutValue = _payoutValue; daysWithoutRain = 0; contractActive = true; cropLocation = _cropLocation; //set the oracles and jodids to values from nodes on market.link //oracles[0] = 0x240bae5a27233fd3ac5440b5a598467725f7d1cd; //oracles[1] = 0x5b4247e58fe5a54a116e4a3be32b31be7030c8a3; //jobIds[0] = '1bc4f827ff5942eaaa7540b7dd1e20b9'; //jobIds[1] = 'e67ddf1f394d44e79a9a2132efd00050'; //or if you have your own node and job setup you can use it for both requests oracles[0] = 0x05c8fadf1798437c143683e665800d58a42b6e19; oracles[1] = 0x05c8fadf1798437c143683e665800d58a42b6e19; jobIds[0] = 'a17e8fbf4cbf46eeb79e04b3eb864a4e'; jobIds[1] = 'a17e8fbf4cbf46eeb79e04b3eb864a4e'; emit contractCreated(insurer, client, duration, premium, payoutValue); } /** * @dev Calls out to an Oracle to obtain weather data */ function updateContract() public onContractActive() returns (bytes32 requestId) { //first call end contract in case of insurance contract duration expiring, if it hasn't then this functin execution will resume checkEndContract(); //contract may have been marked inactive above, only do request if needed if (contractActive) { dataRequestsSent = 0; //First build up a request to World Weather Online to get the current rainfall string memory url = string(abi.encodePacked(WORLD_WEATHER_ONLINE_URL, "key=",WORLD_WEATHER_ONLINE_KEY,"&q=",cropLocation,"&format=json&num_of_days=1")); checkRainfall(oracles[0], jobIds[0], url, WORLD_WEATHER_ONLINE_PATH); // Now build up the second request to WeatherBit url = string(abi.encodePacked(WEATHERBIT_URL, "city=",cropLocation,"&key=",WEATHERBIT_KEY)); checkRainfall(oracles[1], jobIds[1], url, WEATHERBIT_PATH); } } /** * @dev Calls out to an Oracle to obtain weather data */ function checkRainfall(address _oracle, bytes32 _jobId, string _url, string _path) private onContractActive() returns (bytes32 requestId) { //First build up a request to get the current rainfall Chainlink.Request memory req = buildChainlinkRequest(_jobId, address(this), this.checkRainfallCallBack.selector); req.add("get", _url); //sends the GET request to the oracle req.add("path", _path); req.addInt("times", 100); requestId = sendChainlinkRequestTo(_oracle, req, oraclePaymentAmount); emit dataRequestSent(requestId); } /** * @dev Callback function - This gets called by the Oracle Contract when the Oracle Node passes data back to the Oracle Contract * The function will take the rainfall given by the Oracle and updated the Inusrance Contract state */ function checkRainfallCallBack(bytes32 _requestId, uint256 _rainfall) public recordChainlinkFulfillment(_requestId) onContractActive() callFrequencyOncePerDay() { //set current temperature to value returned from Oracle, and store date this was retrieved (to avoid spam and gaming the contract) currentRainfallList[dataRequestsSent] = _rainfall; dataRequestsSent = dataRequestsSent + 1; //set current rainfall to average of both values if (dataRequestsSent > 1) { currentRainfall = (currentRainfallList[0].add(currentRainfallList[1]).div(2)); currentRainfallDateChecked = now; requestCount +=1; //check if payout conditions have been met, if so call payoutcontract, which should also end/kill contract at the end if (currentRainfall == 0 ) { //temp threshold has been met, add a day of over threshold daysWithoutRain += 1; } else { //there was rain today, so reset daysWithoutRain parameter daysWithoutRain = 0; emit ranfallThresholdReset(currentRainfall); } if (daysWithoutRain >= DROUGHT_DAYS_THRESDHOLD) { // day threshold has been met //need to pay client out insurance amount payOutContract(); } } emit dataReceived(_rainfall); } /** * @dev Insurance conditions have been met, do payout of total cover amount to client */ function payOutContract() private onContractActive() { //Transfer agreed amount to client client.transfer(address(this).balance); //Transfer any remaining funds (premium) back to Insurer LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(insurer, link.balanceOf(address(this))), "Unable to transfer"); emit contractPaidOut(now, payoutValue, currentRainfall); //now that amount has been transferred, can end the contract //mark contract as ended, so no future calls can be done contractActive = false; contractPaid = true; } /** * @dev Insurance conditions have not been met, and contract expired, end contract and return funds */ function checkEndContract() private onContractEnded() { //Insurer needs to have performed at least 1 weather call per day to be eligible to retrieve funds back. //We will allow for 1 missed weather call to account for unexpected issues on a given day. if (requestCount >= (duration.div(DAY_IN_SECONDS) - 2)) { //return funds back to insurance provider then end/kill the contract insurer.transfer(address(this).balance); } else { //insurer hasn't done the minimum number of data requests, client is eligible to receive his premium back // need to use ETH/USD price feed to calculate ETH amount client.transfer(premium.div(uint(getLatestPrice()))); insurer.transfer(address(this).balance); } //transfer any remaining LINK tokens back to the insurer LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(insurer, link.balanceOf(address(this))), "Unable to transfer remaining LINK tokens"); //mark contract as ended, so no future state changes can occur on the contract contractActive = false; emit contractEnded(now, address(this).balance); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; } /** * @dev Get the balance of the contract */ function getContractBalance() external view returns (uint) { return address(this).balance; } /** * @dev Get the Crop Location */ function getLocation() external view returns (string) { return cropLocation; } /** * @dev Get the Total Cover */ function getPayoutValue() external view returns (uint) { return payoutValue; } /** * @dev Get the Premium paid */ function getPremium() external view returns (uint) { return premium; } /** * @dev Get the status of the contract */ function getContractStatus() external view returns (bool) { return contractActive; } /** * @dev Get whether the contract has been paid out or not */ function getContractPaid() external view returns (bool) { return contractPaid; } /** * @dev Get the current recorded rainfall for the contract */ function getCurrentRainfall() external view returns (uint) { return currentRainfall; } /** * @dev Get the recorded number of days without rain */ function getDaysWithoutRain() external view returns (uint) { return daysWithoutRain; } /** * @dev Get the count of requests that has occured for the Insurance Contract */ function getRequestCount() external view returns (uint) { return requestCount; } /** * @dev Get the last time that the rainfall was checked for the contract */ function getCurrentRainfallDateChecked() external view returns (uint) { return currentRainfallDateChecked; } /** * @dev Get the contract duration */ function getDuration() external view returns (uint) { return duration; } /** * @dev Get the contract start date */ function getContractStartDate() external view returns (uint) { return startDate; } /** * @dev Get the current date/time according to the blockchain */ function getNow() external view returns (uint) { return now; } /** * @dev Get address of the chainlink token */ function getChainlinkToken() public view returns (address) { return chainlinkTokenAddress(); } /** * @dev Helper function for converting a string to a bytes32 object */ function stringToBytes32(string memory source) private pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { // solhint-disable-line no-inline-assembly result := mload(add(source, 32)) } } /** * @dev Helper function for converting uint to a string */ function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } /** * @dev Fallback function so contrat can receive ether when required */ function() external payable { } }
* @dev Get the Premium paid/
function getPremium() external view returns (uint) { return premium; }
2,519,582
[ 1, 967, 326, 453, 2764, 5077, 30591, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12822, 81, 5077, 1435, 3903, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 23020, 5077, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x119C7Ee43Ebf1dEDc45A3730735583Bd39E32579/sources/contracts/operators/CollectionBatchBuyOperator.sol
Check that call is not re-entering.
function _buy( address payable callTarget, uint96 callValue, bytes memory callData ) private returns (bool success, bytes memory revertData) { if (callTarget == address(this)) { revert CallProhibitedError(callTarget, callData); } }
17,001,949
[ 1, 1564, 716, 745, 353, 486, 283, 17, 2328, 310, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 70, 9835, 12, 203, 3639, 1758, 8843, 429, 745, 2326, 16, 203, 3639, 2254, 10525, 745, 620, 16, 203, 3639, 1731, 3778, 745, 751, 203, 565, 262, 3238, 1135, 261, 6430, 2216, 16, 1731, 3778, 15226, 751, 13, 288, 203, 3639, 309, 261, 1991, 2326, 422, 1758, 12, 2211, 3719, 288, 203, 5411, 15226, 3049, 626, 29993, 668, 12, 1991, 2326, 16, 745, 751, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AaveV2 } from "../integration/lib/AaveV2.sol"; import { IAToken } from "../../interfaces/external/aave-v2/IAToken.sol"; import { IController } from "../../interfaces/IController.sol"; import { IDebtIssuanceModule } from "../../interfaces/IDebtIssuanceModule.sol"; import { IExchangeAdapter } from "../../interfaces/IExchangeAdapter.sol"; import { ILendingPool } from "../../interfaces/external/aave-v2/ILendingPool.sol"; import { ILendingPoolAddressesProvider } from "../../interfaces/external/aave-v2/ILendingPoolAddressesProvider.sol"; import { IModuleIssuanceHook } from "../../interfaces/IModuleIssuanceHook.sol"; import { IProtocolDataProvider } from "../../interfaces/external/aave-v2/IProtocolDataProvider.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { IVariableDebtToken } from "../../interfaces/external/aave-v2/IVariableDebtToken.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; /** * @title AaveLeverageModule * @author Set Protocol * @notice Smart contract that enables leverage trading using Aave as the lending protocol. * @dev Do not use this module in conjunction with other debt modules that allow Aave debt positions as it could lead to double counting of * debt when borrowed assets are the same. */ contract AaveLeverageModule is ModuleBase, ReentrancyGuard, Ownable, IModuleIssuanceHook { using AaveV2 for ISetToken; /* ============ Structs ============ */ struct EnabledAssets { address[] collateralAssets; // Array of enabled underlying collateral assets for a SetToken address[] borrowAssets; // Array of enabled underlying borrow assets for a SetToken } struct ActionInfo { ISetToken setToken; // SetToken instance ILendingPool lendingPool; // Lending pool instance, we grab this everytime since it's best practice not to store IExchangeAdapter exchangeAdapter; // Exchange adapter instance uint256 setTotalSupply; // Total supply of SetToken uint256 notionalSendQuantity; // Total notional quantity sent to exchange uint256 minNotionalReceiveQuantity; // Min total notional received from exchange IERC20 collateralAsset; // Address of collateral asset IERC20 borrowAsset; // Address of borrow asset uint256 preTradeReceiveTokenBalance; // Balance of pre-trade receive token balance } struct ReserveTokens { IAToken aToken; // Reserve's aToken instance IVariableDebtToken variableDebtToken; // Reserve's variable debt token instance } /* ============ Events ============ */ /** * @dev Emitted on lever() * @param _setToken Instance of the SetToken being levered * @param _borrowAsset Asset being borrowed for leverage * @param _collateralAsset Collateral asset being levered * @param _exchangeAdapter Exchange adapter used for trading * @param _totalBorrowAmount Total amount of `_borrowAsset` borrowed * @param _totalReceiveAmount Total amount of `_collateralAsset` received by selling `_borrowAsset` * @param _protocolFee Protocol fee charged */ event LeverageIncreased( ISetToken indexed _setToken, IERC20 indexed _borrowAsset, IERC20 indexed _collateralAsset, IExchangeAdapter _exchangeAdapter, uint256 _totalBorrowAmount, uint256 _totalReceiveAmount, uint256 _protocolFee ); /** * @dev Emitted on delever() and deleverToZeroBorrowBalance() * @param _setToken Instance of the SetToken being delevered * @param _collateralAsset Asset sold to decrease leverage * @param _repayAsset Asset being bought to repay to Aave * @param _exchangeAdapter Exchange adapter used for trading * @param _totalRedeemAmount Total amount of `_collateralAsset` being sold * @param _totalRepayAmount Total amount of `_repayAsset` being repaid * @param _protocolFee Protocol fee charged */ event LeverageDecreased( ISetToken indexed _setToken, IERC20 indexed _collateralAsset, IERC20 indexed _repayAsset, IExchangeAdapter _exchangeAdapter, uint256 _totalRedeemAmount, uint256 _totalRepayAmount, uint256 _protocolFee ); /** * @dev Emitted on addCollateralAssets() and removeCollateralAssets() * @param _setToken Instance of SetToken whose collateral assets is updated * @param _added true if assets are added false if removed * @param _assets Array of collateral assets being added/removed */ event CollateralAssetsUpdated( ISetToken indexed _setToken, bool indexed _added, IERC20[] _assets ); /** * @dev Emitted on addBorrowAssets() and removeBorrowAssets() * @param _setToken Instance of SetToken whose borrow assets is updated * @param _added true if assets are added false if removed * @param _assets Array of borrow assets being added/removed */ event BorrowAssetsUpdated( ISetToken indexed _setToken, bool indexed _added, IERC20[] _assets ); /** * @dev Emitted when `underlyingToReserveTokensMappings` is updated * @param _underlying Address of the underlying asset * @param _aToken Updated aave reserve aToken * @param _variableDebtToken Updated aave reserve variable debt token */ event ReserveTokensUpdated( IERC20 indexed _underlying, IAToken indexed _aToken, IVariableDebtToken indexed _variableDebtToken ); /** * @dev Emitted on updateAllowedSetToken() * @param _setToken SetToken being whose allowance to initialize this module is being updated * @param _added true if added false if removed */ event SetTokenStatusUpdated( ISetToken indexed _setToken, bool indexed _added ); /** * @dev Emitted on updateAnySetAllowed() * @param _anySetAllowed true if any set is allowed to initialize this module, false otherwise */ event AnySetAllowedUpdated( bool indexed _anySetAllowed ); /* ============ Constants ============ */ // This module only supports borrowing in variable rate mode from Aave which is represented by 2 uint256 constant internal BORROW_RATE_MODE = 2; // String identifying the DebtIssuanceModule in the IntegrationRegistry. Note: Governance must add DefaultIssuanceModule as // the string as the integration name string constant internal DEFAULT_ISSUANCE_MODULE_NAME = "DefaultIssuanceModule"; // 0 index stores protocol fee % on the controller, charged in the _executeTrade function uint256 constant internal PROTOCOL_TRADE_FEE_INDEX = 0; /* ============ State Variables ============ */ // Mapping to efficiently fetch reserve token addresses. Tracking Aave reserve token addresses and updating them // upon requirement is more efficient than fetching them each time from Aave. // Note: For an underlying asset to be enabled as collateral/borrow asset on SetToken, it must be added to this mapping first. mapping(IERC20 => ReserveTokens) public underlyingToReserveTokens; // Used to fetch reserves and user data from AaveV2 IProtocolDataProvider public immutable protocolDataProvider; // Used to fetch lendingPool address. This contract is immutable and its address will never change. ILendingPoolAddressesProvider public immutable lendingPoolAddressesProvider; // Mapping to efficiently check if collateral asset is enabled in SetToken mapping(ISetToken => mapping(IERC20 => bool)) public collateralAssetEnabled; // Mapping to efficiently check if a borrow asset is enabled in SetToken mapping(ISetToken => mapping(IERC20 => bool)) public borrowAssetEnabled; // Internal mapping of enabled collateral and borrow tokens for syncing positions mapping(ISetToken => EnabledAssets) internal enabledAssets; // Mapping of SetToken to boolean indicating if SetToken is on allow list. Updateable by governance mapping(ISetToken => bool) public allowedSetTokens; // Boolean that returns if any SetToken can initialize this module. If false, then subject to allow list. Updateable by governance. bool public anySetAllowed; /* ============ Constructor ============ */ /** * @dev Instantiate addresses. Underlying to reserve tokens mapping is created. * @param _controller Address of controller contract * @param _lendingPoolAddressesProvider Address of Aave LendingPoolAddressProvider */ constructor( IController _controller, ILendingPoolAddressesProvider _lendingPoolAddressesProvider ) public ModuleBase(_controller) { lendingPoolAddressesProvider = _lendingPoolAddressesProvider; IProtocolDataProvider _protocolDataProvider = IProtocolDataProvider( // Use the raw input vs bytes32() conversion. This is to ensure the input is an uint and not a string. _lendingPoolAddressesProvider.getAddress(0x0100000000000000000000000000000000000000000000000000000000000000) ); protocolDataProvider = _protocolDataProvider; IProtocolDataProvider.TokenData[] memory reserveTokens = _protocolDataProvider.getAllReservesTokens(); for(uint256 i = 0; i < reserveTokens.length; i++) { (address aToken, , address variableDebtToken) = _protocolDataProvider.getReserveTokensAddresses(reserveTokens[i].tokenAddress); underlyingToReserveTokens[IERC20(reserveTokens[i].tokenAddress)] = ReserveTokens(IAToken(aToken), IVariableDebtToken(variableDebtToken)); } } /* ============ External Functions ============ */ /** * @dev MANAGER ONLY: Increases leverage for a given collateral position using an enabled borrow asset. * Borrows _borrowAsset from Aave. Performs a DEX trade, exchanging the _borrowAsset for _collateralAsset. * Deposits _collateralAsset to Aave and mints corresponding aToken. * Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset. * @param _setToken Instance of the SetToken * @param _borrowAsset Address of underlying asset being borrowed for leverage * @param _collateralAsset Address of underlying collateral asset * @param _borrowQuantityUnits Borrow quantity of asset in position units * @param _minReceiveQuantityUnits Min receive quantity of collateral asset to receive post-trade in position units * @param _tradeAdapterName Name of trade adapter * @param _tradeData Arbitrary data for trade */ function lever( ISetToken _setToken, IERC20 _borrowAsset, IERC20 _collateralAsset, uint256 _borrowQuantityUnits, uint256 _minReceiveQuantityUnits, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) { // For levering up, send quantity is derived from borrow asset and receive quantity is derived from // collateral asset ActionInfo memory leverInfo = _createAndValidateActionInfo( _setToken, _borrowAsset, _collateralAsset, _borrowQuantityUnits, _minReceiveQuantityUnits, _tradeAdapterName, true ); _borrow(leverInfo.setToken, leverInfo.lendingPool, leverInfo.borrowAsset, leverInfo.notionalSendQuantity); uint256 postTradeReceiveQuantity = _executeTrade(leverInfo, _borrowAsset, _collateralAsset, _tradeData); uint256 protocolFee = _accrueProtocolFee(_setToken, _collateralAsset, postTradeReceiveQuantity); uint256 postTradeCollateralQuantity = postTradeReceiveQuantity.sub(protocolFee); _deposit(leverInfo.setToken, leverInfo.lendingPool, _collateralAsset, postTradeCollateralQuantity); _updateLeverPositions(leverInfo, _borrowAsset); emit LeverageIncreased( _setToken, _borrowAsset, _collateralAsset, leverInfo.exchangeAdapter, leverInfo.notionalSendQuantity, postTradeCollateralQuantity, protocolFee ); } /** * @dev MANAGER ONLY: Decrease leverage for a given collateral position using an enabled borrow asset. * Withdraws _collateralAsset from Aave. Performs a DEX trade, exchanging the _collateralAsset for _repayAsset. * Repays _repayAsset to Aave and burns corresponding debt tokens. * Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset. * @param _setToken Instance of the SetToken * @param _collateralAsset Address of underlying collateral asset being withdrawn * @param _repayAsset Address of underlying borrowed asset being repaid * @param _redeemQuantityUnits Quantity of collateral asset to delever in position units * @param _minRepayQuantityUnits Minimum amount of repay asset to receive post trade in position units * @param _tradeAdapterName Name of trade adapter * @param _tradeData Arbitrary data for trade */ function delever( ISetToken _setToken, IERC20 _collateralAsset, IERC20 _repayAsset, uint256 _redeemQuantityUnits, uint256 _minRepayQuantityUnits, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) { // Note: for delevering, send quantity is derived from collateral asset and receive quantity is derived from // repay asset ActionInfo memory deleverInfo = _createAndValidateActionInfo( _setToken, _collateralAsset, _repayAsset, _redeemQuantityUnits, _minRepayQuantityUnits, _tradeAdapterName, false ); _withdraw(deleverInfo.setToken, deleverInfo.lendingPool, _collateralAsset, deleverInfo.notionalSendQuantity); uint256 postTradeReceiveQuantity = _executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData); uint256 protocolFee = _accrueProtocolFee(_setToken, _repayAsset, postTradeReceiveQuantity); uint256 repayQuantity = postTradeReceiveQuantity.sub(protocolFee); _repayBorrow(deleverInfo.setToken, deleverInfo.lendingPool, _repayAsset, repayQuantity); _updateDeleverPositions(deleverInfo, _repayAsset); emit LeverageDecreased( _setToken, _collateralAsset, _repayAsset, deleverInfo.exchangeAdapter, deleverInfo.notionalSendQuantity, repayQuantity, protocolFee ); } /** @dev MANAGER ONLY: Pays down the borrow asset to 0 selling off a given amount of collateral asset. * Withdraws _collateralAsset from Aave. Performs a DEX trade, exchanging the _collateralAsset for _repayAsset. * Minimum receive amount for the DEX trade is set to the current variable debt balance of the borrow asset. * Repays received _repayAsset to Aave which burns corresponding debt tokens. Any extra received borrow asset is . * updated as equity. No protocol fee is charged. * Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset. * The function reverts if not enough collateral asset is redeemed to buy the required minimum amount of _repayAsset. * @param _setToken Instance of the SetToken * @param _collateralAsset Address of underlying collateral asset being redeemed * @param _repayAsset Address of underlying asset being repaid * @param _redeemQuantityUnits Quantity of collateral asset to delever in position units * @param _tradeAdapterName Name of trade adapter * @param _tradeData Arbitrary data for trade * @return uint256 Notional repay quantity */ function deleverToZeroBorrowBalance( ISetToken _setToken, IERC20 _collateralAsset, IERC20 _repayAsset, uint256 _redeemQuantityUnits, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) returns (uint256) { uint256 setTotalSupply = _setToken.totalSupply(); uint256 notionalRedeemQuantity = _redeemQuantityUnits.preciseMul(setTotalSupply); require(borrowAssetEnabled[_setToken][_repayAsset], "Borrow not enabled"); uint256 notionalRepayQuantity = underlyingToReserveTokens[_repayAsset].variableDebtToken.balanceOf(address(_setToken)); require(notionalRepayQuantity > 0, "Borrow balance is zero"); ActionInfo memory deleverInfo = _createAndValidateActionInfoNotional( _setToken, _collateralAsset, _repayAsset, notionalRedeemQuantity, notionalRepayQuantity, _tradeAdapterName, false, setTotalSupply ); _withdraw(deleverInfo.setToken, deleverInfo.lendingPool, _collateralAsset, deleverInfo.notionalSendQuantity); _executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData); _repayBorrow(deleverInfo.setToken, deleverInfo.lendingPool, _repayAsset, notionalRepayQuantity); _updateDeleverPositions(deleverInfo, _repayAsset); emit LeverageDecreased( _setToken, _collateralAsset, _repayAsset, deleverInfo.exchangeAdapter, deleverInfo.notionalSendQuantity, notionalRepayQuantity, 0 // No protocol fee ); return notionalRepayQuantity; } /** * @dev CALLABLE BY ANYBODY: Sync Set positions with ALL enabled Aave collateral and borrow positions. * For collateral assets, update aToken default position. For borrow assets, update external borrow position. * - Collateral assets may come out of sync when interest is accrued or a position is liquidated * - Borrow assets may come out of sync when interest is accrued or position is liquidated and borrow is repaid * Note: In Aave, both collateral and borrow interest is accrued in each block by increasing the balance of * aTokens and debtTokens for each user, and 1 aToken = 1 variableDebtToken = 1 underlying. * @param _setToken Instance of the SetToken */ function sync(ISetToken _setToken) public nonReentrant onlyValidAndInitializedSet(_setToken) { uint256 setTotalSupply = _setToken.totalSupply(); // Only sync positions when Set supply is not 0. Without this check, if sync is called by someone before the // first issuance, then editDefaultPosition would remove the default positions from the SetToken if (setTotalSupply > 0) { address[] memory collateralAssets = enabledAssets[_setToken].collateralAssets; for(uint256 i = 0; i < collateralAssets.length; i++) { IAToken aToken = underlyingToReserveTokens[IERC20(collateralAssets[i])].aToken; uint256 previousPositionUnit = _setToken.getDefaultPositionRealUnit(address(aToken)).toUint256(); uint256 newPositionUnit = _getCollateralPosition(_setToken, aToken, setTotalSupply); // Note: Accounts for if position does not exist on SetToken but is tracked in enabledAssets if (previousPositionUnit != newPositionUnit) { _updateCollateralPosition(_setToken, aToken, newPositionUnit); } } address[] memory borrowAssets = enabledAssets[_setToken].borrowAssets; for(uint256 i = 0; i < borrowAssets.length; i++) { IERC20 borrowAsset = IERC20(borrowAssets[i]); int256 previousPositionUnit = _setToken.getExternalPositionRealUnit(address(borrowAsset), address(this)); int256 newPositionUnit = _getBorrowPosition(_setToken, borrowAsset, setTotalSupply); // Note: Accounts for if position does not exist on SetToken but is tracked in enabledAssets if (newPositionUnit != previousPositionUnit) { _updateBorrowPosition(_setToken, borrowAsset, newPositionUnit); } } } } /** * @dev MANAGER ONLY: Initializes this module to the SetToken. Either the SetToken needs to be on the allowed list * or anySetAllowed needs to be true. Only callable by the SetToken's manager. * Note: Managers can enable collateral and borrow assets that don't exist as positions on the SetToken * @param _setToken Instance of the SetToken to initialize * @param _collateralAssets Underlying tokens to be enabled as collateral in the SetToken * @param _borrowAssets Underlying tokens to be enabled as borrow in the SetToken */ function initialize( ISetToken _setToken, IERC20[] memory _collateralAssets, IERC20[] memory _borrowAssets ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { if (!anySetAllowed) { require(allowedSetTokens[_setToken], "Not allowed SetToken"); } // Initialize module before trying register _setToken.initializeModule(); // Get debt issuance module registered to this module and require that it is initialized require(_setToken.isInitializedModule(getAndValidateAdapter(DEFAULT_ISSUANCE_MODULE_NAME)), "Issuance not initialized"); // Try if register exists on any of the modules including the debt issuance module address[] memory modules = _setToken.getModules(); for(uint256 i = 0; i < modules.length; i++) { try IDebtIssuanceModule(modules[i]).registerToIssuanceModule(_setToken) {} catch {} } // _collateralAssets and _borrowAssets arrays are validated in their respective internal functions _addCollateralAssets(_setToken, _collateralAssets); _addBorrowAssets(_setToken, _borrowAssets); } /** * @dev MANAGER ONLY: Removes this module from the SetToken, via call by the SetToken. Any deposited collateral assets * are disabled to be used as collateral on Aave. Aave Settings and manager enabled assets state is deleted. * Note: Function will revert is there is any debt remaining on Aave */ function removeModule() external override onlyValidAndInitializedSet(ISetToken(msg.sender)) { ISetToken setToken = ISetToken(msg.sender); // Sync Aave and SetToken positions prior to any removal action sync(setToken); address[] memory borrowAssets = enabledAssets[setToken].borrowAssets; for(uint256 i = 0; i < borrowAssets.length; i++) { IERC20 borrowAsset = IERC20(borrowAssets[i]); require(underlyingToReserveTokens[borrowAsset].variableDebtToken.balanceOf(address(setToken)) == 0, "Variable debt remaining"); delete borrowAssetEnabled[setToken][borrowAsset]; } address[] memory collateralAssets = enabledAssets[setToken].collateralAssets; for(uint256 i = 0; i < collateralAssets.length; i++) { IERC20 collateralAsset = IERC20(collateralAssets[i]); _updateUseReserveAsCollateral(setToken, collateralAsset, false); delete collateralAssetEnabled[setToken][collateralAsset]; } delete enabledAssets[setToken]; // Try if unregister exists on any of the modules address[] memory modules = setToken.getModules(); for(uint256 i = 0; i < modules.length; i++) { try IDebtIssuanceModule(modules[i]).unregisterFromIssuanceModule(setToken) {} catch {} } } /** * @dev MANAGER ONLY: Add registration of this module on the debt issuance module for the SetToken. * Note: if the debt issuance module is not added to SetToken before this module is initialized, then this function * needs to be called if the debt issuance module is later added and initialized to prevent state inconsistencies * @param _setToken Instance of the SetToken * @param _debtIssuanceModule Debt issuance module address to register */ function registerToModule(ISetToken _setToken, IDebtIssuanceModule _debtIssuanceModule) external onlyManagerAndValidSet(_setToken) { require(_setToken.isInitializedModule(address(_debtIssuanceModule)), "Issuance not initialized"); _debtIssuanceModule.registerToIssuanceModule(_setToken); } /** * @dev CALLABLE BY ANYBODY: Updates `underlyingToReserveTokens` mappings. Reverts if mapping already exists * or the passed _underlying asset does not have a valid reserve on Aave. * Note: Call this function when Aave adds a new reserve. * @param _underlying Address of underlying asset */ function addUnderlyingToReserveTokensMapping(IERC20 _underlying) external { require(address(underlyingToReserveTokens[_underlying].aToken) == address(0), "Mapping already exists"); // An active reserve is an alias for a valid reserve on Aave. (,,,,,,,, bool isActive,) = protocolDataProvider.getReserveConfigurationData(address(_underlying)); require(isActive, "Invalid aave reserve"); _addUnderlyingToReserveTokensMapping(_underlying); } /** * @dev MANAGER ONLY: Add collateral assets. aTokens corresponding to collateral assets are tracked for syncing positions. * Note: Reverts with "Collateral already enabled" if there are duplicate assets in the passed _newCollateralAssets array. * * NOTE: ALL ADDED COLLATERAL ASSETS CAN BE ADDED AS A POSITION ON THE SET TOKEN WITHOUT MANAGER'S EXPLICIT PERMISSION. * UNWANTED EXTRA POSITIONS CAN BREAK EXTERNAL LOGIC, INCREASE COST OF MINT/REDEEM OF SET TOKEN, AMONG OTHER POTENTIAL UNINTENDED CONSEQUENCES. * SO, PLEASE ADD ONLY THOSE COLLATERAL ASSETS WHOSE CORRESPONDING aTOKENS ARE NEEDED AS DEFAULT POSITIONS ON THE SET TOKEN. * * @param _setToken Instance of the SetToken * @param _newCollateralAssets Addresses of new collateral underlying assets */ function addCollateralAssets(ISetToken _setToken, IERC20[] memory _newCollateralAssets) external onlyManagerAndValidSet(_setToken) { _addCollateralAssets(_setToken, _newCollateralAssets); } /** * @dev MANAGER ONLY: Remove collateral assets. Disable deposited assets to be used as collateral on Aave market. * @param _setToken Instance of the SetToken * @param _collateralAssets Addresses of collateral underlying assets to remove */ function removeCollateralAssets(ISetToken _setToken, IERC20[] memory _collateralAssets) external onlyManagerAndValidSet(_setToken) { for(uint256 i = 0; i < _collateralAssets.length; i++) { IERC20 collateralAsset = _collateralAssets[i]; require(collateralAssetEnabled[_setToken][collateralAsset], "Collateral not enabled"); _updateUseReserveAsCollateral(_setToken, collateralAsset, false); delete collateralAssetEnabled[_setToken][collateralAsset]; enabledAssets[_setToken].collateralAssets.removeStorage(address(collateralAsset)); } emit CollateralAssetsUpdated(_setToken, false, _collateralAssets); } /** * @dev MANAGER ONLY: Add borrow assets. Debt tokens corresponding to borrow assets are tracked for syncing positions. * Note: Reverts with "Borrow already enabled" if there are duplicate assets in the passed _newBorrowAssets array. * @param _setToken Instance of the SetToken * @param _newBorrowAssets Addresses of borrow underlying assets to add */ function addBorrowAssets(ISetToken _setToken, IERC20[] memory _newBorrowAssets) external onlyManagerAndValidSet(_setToken) { _addBorrowAssets(_setToken, _newBorrowAssets); } /** * @dev MANAGER ONLY: Remove borrow assets. * Note: If there is a borrow balance, borrow asset cannot be removed * @param _setToken Instance of the SetToken * @param _borrowAssets Addresses of borrow underlying assets to remove */ function removeBorrowAssets(ISetToken _setToken, IERC20[] memory _borrowAssets) external onlyManagerAndValidSet(_setToken) { for(uint256 i = 0; i < _borrowAssets.length; i++) { IERC20 borrowAsset = _borrowAssets[i]; require(borrowAssetEnabled[_setToken][borrowAsset], "Borrow not enabled"); require(underlyingToReserveTokens[borrowAsset].variableDebtToken.balanceOf(address(_setToken)) == 0, "Variable debt remaining"); delete borrowAssetEnabled[_setToken][borrowAsset]; enabledAssets[_setToken].borrowAssets.removeStorage(address(borrowAsset)); } emit BorrowAssetsUpdated(_setToken, false, _borrowAssets); } /** * @dev GOVERNANCE ONLY: Enable/disable ability of a SetToken to initialize this module. Only callable by governance. * @param _setToken Instance of the SetToken * @param _status Bool indicating if _setToken is allowed to initialize this module */ function updateAllowedSetToken(ISetToken _setToken, bool _status) external onlyOwner { require(controller.isSet(address(_setToken)) || allowedSetTokens[_setToken], "Invalid SetToken"); allowedSetTokens[_setToken] = _status; emit SetTokenStatusUpdated(_setToken, _status); } /** * @dev GOVERNANCE ONLY: Toggle whether ANY SetToken is allowed to initialize this module. Only callable by governance. * @param _anySetAllowed Bool indicating if ANY SetToken is allowed to initialize this module */ function updateAnySetAllowed(bool _anySetAllowed) external onlyOwner { anySetAllowed = _anySetAllowed; emit AnySetAllowedUpdated(_anySetAllowed); } /** * @dev MODULE ONLY: Hook called prior to issuance to sync positions on SetToken. Only callable by valid module. * @param _setToken Instance of the SetToken */ function moduleIssueHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external override onlyModule(_setToken) { sync(_setToken); } /** * @dev MODULE ONLY: Hook called prior to redemption to sync positions on SetToken. For redemption, always use current borrowed * balance after interest accrual. Only callable by valid module. * @param _setToken Instance of the SetToken */ function moduleRedeemHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external override onlyModule(_setToken) { sync(_setToken); } /** * @dev MODULE ONLY: Hook called prior to looping through each component on issuance. Invokes borrow in order for * module to return debt to issuer. Only callable by valid module. * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of SetToken * @param _component Address of component */ function componentIssueHook(ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity) external override onlyModule(_setToken) { // Check hook not being called for an equity position. If hook is called with equity position and outstanding borrow position // exists the loan would be taken out twice potentially leading to liquidation if (!_isEquity) { int256 componentDebt = _setToken.getExternalPositionRealUnit(address(_component), address(this)); require(componentDebt < 0, "Component must be negative"); uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMul(_setTokenQuantity); _borrowForHook(_setToken, _component, notionalDebt); } } /** * @dev MODULE ONLY: Hook called prior to looping through each component on redemption. Invokes repay after * the issuance module transfers debt from the issuer. Only callable by valid module. * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of SetToken * @param _component Address of component */ function componentRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity) external override onlyModule(_setToken) { // Check hook not being called for an equity position. If hook is called with equity position and outstanding borrow position // exists the loan would be paid down twice, decollateralizing the Set if (!_isEquity) { int256 componentDebt = _setToken.getExternalPositionRealUnit(address(_component), address(this)); require(componentDebt < 0, "Component must be negative"); uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMulCeil(_setTokenQuantity); _repayBorrowForHook(_setToken, _component, notionalDebt); } } /* ============ External Getter Functions ============ */ /** * @dev Get enabled assets for SetToken. Returns an array of collateral and borrow assets. * @return Underlying collateral assets that are enabled * @return Underlying borrowed assets that are enabled */ function getEnabledAssets(ISetToken _setToken) external view returns(address[] memory, address[] memory) { return ( enabledAssets[_setToken].collateralAssets, enabledAssets[_setToken].borrowAssets ); } /* ============ Internal Functions ============ */ /** * @dev Invoke deposit from SetToken using AaveV2 library. Mints aTokens for SetToken. */ function _deposit(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity); _setToken.invokeDeposit(_lendingPool, address(_asset), _notionalQuantity); } /** * @dev Invoke withdraw from SetToken using AaveV2 library. Burns aTokens and returns underlying to SetToken. */ function _withdraw(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeWithdraw(_lendingPool, address(_asset), _notionalQuantity); } /** * @dev Invoke repay from SetToken using AaveV2 library. Burns DebtTokens for SetToken. */ function _repayBorrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity); _setToken.invokeRepay(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE); } /** * @dev Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the * lending pool in this function to optimize vs forcing a fetch twice during lever/delever. */ function _repayBorrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal { _repayBorrow(_setToken, ILendingPool(lendingPoolAddressesProvider.getLendingPool()), _asset, _notionalQuantity); } /** * @dev Invoke borrow from the SetToken using AaveV2 library. Mints DebtTokens for SetToken. */ function _borrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeBorrow(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE); } /** * @dev Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the * lending pool in this function to optimize vs forcing a fetch twice during lever/delever. */ function _borrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal { _borrow(_setToken, ILendingPool(lendingPoolAddressesProvider.getLendingPool()), _asset, _notionalQuantity); } /** * @dev Invokes approvals, gets trade call data from exchange adapter and invokes trade from SetToken * @return uint256 The quantity of tokens received post-trade */ function _executeTrade( ActionInfo memory _actionInfo, IERC20 _sendToken, IERC20 _receiveToken, bytes memory _data ) internal returns (uint256) { ISetToken setToken = _actionInfo.setToken; uint256 notionalSendQuantity = _actionInfo.notionalSendQuantity; setToken.invokeApprove( address(_sendToken), _actionInfo.exchangeAdapter.getSpender(), notionalSendQuantity ); ( address targetExchange, uint256 callValue, bytes memory methodData ) = _actionInfo.exchangeAdapter.getTradeCalldata( address(_sendToken), address(_receiveToken), address(setToken), notionalSendQuantity, _actionInfo.minNotionalReceiveQuantity, _data ); setToken.invoke(targetExchange, callValue, methodData); uint256 receiveTokenQuantity = _receiveToken.balanceOf(address(setToken)).sub(_actionInfo.preTradeReceiveTokenBalance); require( receiveTokenQuantity >= _actionInfo.minNotionalReceiveQuantity, "Slippage too high" ); return receiveTokenQuantity; } /** * @dev Calculates protocol fee on module and pays protocol fee from SetToken * @return uint256 Total protocol fee paid */ function _accrueProtocolFee(ISetToken _setToken, IERC20 _receiveToken, uint256 _exchangedQuantity) internal returns(uint256) { uint256 protocolFeeTotal = getModuleFee(PROTOCOL_TRADE_FEE_INDEX, _exchangedQuantity); payProtocolFeeFromSetToken(_setToken, address(_receiveToken), protocolFeeTotal); return protocolFeeTotal; } /** * @dev Updates the collateral (aToken held) and borrow position (variableDebtToken held) of the SetToken */ function _updateLeverPositions(ActionInfo memory _actionInfo, IERC20 _borrowAsset) internal { IAToken aToken = underlyingToReserveTokens[_actionInfo.collateralAsset].aToken; _updateCollateralPosition( _actionInfo.setToken, aToken, _getCollateralPosition( _actionInfo.setToken, aToken, _actionInfo.setTotalSupply ) ); _updateBorrowPosition( _actionInfo.setToken, _borrowAsset, _getBorrowPosition( _actionInfo.setToken, _borrowAsset, _actionInfo.setTotalSupply ) ); } /** * @dev Updates positions as per _updateLeverPositions and updates Default position for borrow asset in case Set is * delevered all the way to zero any remaining borrow asset after the debt is paid can be added as a position. */ function _updateDeleverPositions(ActionInfo memory _actionInfo, IERC20 _repayAsset) internal { // if amount of tokens traded for exceeds debt, update default position first to save gas on editing borrow position uint256 repayAssetBalance = _repayAsset.balanceOf(address(_actionInfo.setToken)); if (repayAssetBalance != _actionInfo.preTradeReceiveTokenBalance) { _actionInfo.setToken.calculateAndEditDefaultPosition( address(_repayAsset), _actionInfo.setTotalSupply, _actionInfo.preTradeReceiveTokenBalance ); } _updateLeverPositions(_actionInfo, _repayAsset); } /** * @dev Updates default position unit for given aToken on SetToken */ function _updateCollateralPosition(ISetToken _setToken, IAToken _aToken, uint256 _newPositionUnit) internal { _setToken.editDefaultPosition(address(_aToken), _newPositionUnit); } /** * @dev Updates external position unit for given borrow asset on SetToken */ function _updateBorrowPosition(ISetToken _setToken, IERC20 _underlyingAsset, int256 _newPositionUnit) internal { _setToken.editExternalPosition(address(_underlyingAsset), address(this), _newPositionUnit, ""); } /** * @dev Construct the ActionInfo struct for lever and delever * @return ActionInfo Instance of constructed ActionInfo struct */ function _createAndValidateActionInfo( ISetToken _setToken, IERC20 _sendToken, IERC20 _receiveToken, uint256 _sendQuantityUnits, uint256 _minReceiveQuantityUnits, string memory _tradeAdapterName, bool _isLever ) internal view returns(ActionInfo memory) { uint256 totalSupply = _setToken.totalSupply(); return _createAndValidateActionInfoNotional( _setToken, _sendToken, _receiveToken, _sendQuantityUnits.preciseMul(totalSupply), _minReceiveQuantityUnits.preciseMul(totalSupply), _tradeAdapterName, _isLever, totalSupply ); } /** * @dev Construct the ActionInfo struct for lever and delever accepting notional units * @return ActionInfo Instance of constructed ActionInfo struct */ function _createAndValidateActionInfoNotional( ISetToken _setToken, IERC20 _sendToken, IERC20 _receiveToken, uint256 _notionalSendQuantity, uint256 _minNotionalReceiveQuantity, string memory _tradeAdapterName, bool _isLever, uint256 _setTotalSupply ) internal view returns(ActionInfo memory) { ActionInfo memory actionInfo = ActionInfo ({ exchangeAdapter: IExchangeAdapter(getAndValidateAdapter(_tradeAdapterName)), lendingPool: ILendingPool(lendingPoolAddressesProvider.getLendingPool()), setToken: _setToken, collateralAsset: _isLever ? _receiveToken : _sendToken, borrowAsset: _isLever ? _sendToken : _receiveToken, setTotalSupply: _setTotalSupply, notionalSendQuantity: _notionalSendQuantity, minNotionalReceiveQuantity: _minNotionalReceiveQuantity, preTradeReceiveTokenBalance: IERC20(_receiveToken).balanceOf(address(_setToken)) }); _validateCommon(actionInfo); return actionInfo; } /** * @dev Updates `underlyingToReserveTokens` mappings for given `_underlying` asset. Emits ReserveTokensUpdated event. */ function _addUnderlyingToReserveTokensMapping(IERC20 _underlying) internal { (address aToken, , address variableDebtToken) = protocolDataProvider.getReserveTokensAddresses(address(_underlying)); underlyingToReserveTokens[_underlying].aToken = IAToken(aToken); underlyingToReserveTokens[_underlying].variableDebtToken = IVariableDebtToken(variableDebtToken); emit ReserveTokensUpdated(_underlying, IAToken(aToken), IVariableDebtToken(variableDebtToken)); } /** * @dev Add collateral assets to SetToken. Updates the collateralAssetsEnabled and enabledAssets mappings. * Emits CollateralAssetsUpdated event. */ function _addCollateralAssets(ISetToken _setToken, IERC20[] memory _newCollateralAssets) internal { for(uint256 i = 0; i < _newCollateralAssets.length; i++) { IERC20 collateralAsset = _newCollateralAssets[i]; _validateNewCollateralAsset(_setToken, collateralAsset); _updateUseReserveAsCollateral(_setToken, collateralAsset, true); collateralAssetEnabled[_setToken][collateralAsset] = true; enabledAssets[_setToken].collateralAssets.push(address(collateralAsset)); } emit CollateralAssetsUpdated(_setToken, true, _newCollateralAssets); } /** * @dev Add borrow assets to SetToken. Updates the borrowAssetsEnabled and enabledAssets mappings. * Emits BorrowAssetsUpdated event. */ function _addBorrowAssets(ISetToken _setToken, IERC20[] memory _newBorrowAssets) internal { for(uint256 i = 0; i < _newBorrowAssets.length; i++) { IERC20 borrowAsset = _newBorrowAssets[i]; _validateNewBorrowAsset(_setToken, borrowAsset); borrowAssetEnabled[_setToken][borrowAsset] = true; enabledAssets[_setToken].borrowAssets.push(address(borrowAsset)); } emit BorrowAssetsUpdated(_setToken, true, _newBorrowAssets); } /** * @dev Updates SetToken's ability to use an asset as collateral on Aave */ function _updateUseReserveAsCollateral(ISetToken _setToken, IERC20 _asset, bool _useAsCollateral) internal { /* Note: Aave ENABLES an asset to be used as collateral by `to` address in an `aToken.transfer(to, amount)` call provided 1. msg.sender (from address) isn't the same as `to` address 2. `to` address had zero aToken balance before the transfer 3. transfer `amount` is greater than 0 Note: Aave DISABLES an asset to be used as collateral by `msg.sender`in an `aToken.transfer(to, amount)` call provided 1. msg.sender (from address) isn't the same as `to` address 2. msg.sender has zero balance after the transfer Different states of the SetToken and what this function does in those states: Case 1: Manager adds collateral asset to SetToken before first issuance - Since aToken.balanceOf(setToken) == 0, we do not call `setToken.invokeUserUseReserveAsCollateral` because Aave requires aToken balance to be greater than 0 before enabling/disabling the underlying asset to be used as collateral on Aave markets. Case 2: First issuance of the SetToken - SetToken was initialized with aToken as default position - DebtIssuanceModule reads the default position and transfers corresponding aToken from the issuer to the SetToken - Aave enables aToken to be used as collateral by the SetToken - Manager calls lever() and the aToken is used as collateral to borrow other assets Case 3: Manager removes collateral asset from the SetToken - Disable asset to be used as collateral on SetToken by calling `setToken.invokeSetUserUseReserveAsCollateral` with useAsCollateral equals false - Note: If health factor goes below 1 by removing the collateral asset, then Aave reverts on the above call, thus whole transaction reverts, and manager can't remove corresponding collateral asset Case 4: Manager adds collateral asset after removing it - If aToken.balanceOf(setToken) > 0, we call `setToken.invokeUserUseReserveAsCollateral` and the corresponding aToken is re-enabled as collateral on Aave Case 5: On redemption/delever/liquidated and aToken balance becomes zero - Aave disables aToken to be used as collateral by SetToken Values of variables in below if condition and corresponding action taken: --------------------------------------------------------------------------------------------------------------------- | usageAsCollateralEnabled | _useAsCollateral | aToken.balanceOf() | Action | |--------------------------|-------------------|-----------------------|--------------------------------------------| | true | true | X | Skip invoke. Save gas. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | true | false | greater than 0 | Invoke and set to false. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | true | false | = 0 | Impossible case. Aave disables usage as | | | | | collateral when aToken balance becomes 0 | |--------------------------|-------------------|-----------------------|--------------------------------------------| | false | false | X | Skip invoke. Save gas. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | false | true | greater than 0 | Invoke and set to true. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | false | true | = 0 | Don't invoke. Will revert. | --------------------------------------------------------------------------------------------------------------------- */ (,,,,,,,,bool usageAsCollateralEnabled) = protocolDataProvider.getUserReserveData(address(_asset), address(_setToken)); if ( usageAsCollateralEnabled != _useAsCollateral && underlyingToReserveTokens[_asset].aToken.balanceOf(address(_setToken)) > 0 ) { _setToken.invokeSetUserUseReserveAsCollateral( ILendingPool(lendingPoolAddressesProvider.getLendingPool()), address(_asset), _useAsCollateral ); } } /** * @dev Validate common requirements for lever and delever */ function _validateCommon(ActionInfo memory _actionInfo) internal view { require(collateralAssetEnabled[_actionInfo.setToken][_actionInfo.collateralAsset], "Collateral not enabled"); require(borrowAssetEnabled[_actionInfo.setToken][_actionInfo.borrowAsset], "Borrow not enabled"); require(_actionInfo.collateralAsset != _actionInfo.borrowAsset, "Collateral and borrow asset must be different"); require(_actionInfo.notionalSendQuantity > 0, "Quantity is 0"); } /** * @dev Validates if a new asset can be added as collateral asset for given SetToken */ function _validateNewCollateralAsset(ISetToken _setToken, IERC20 _asset) internal view { require(!collateralAssetEnabled[_setToken][_asset], "Collateral already enabled"); (address aToken, , ) = protocolDataProvider.getReserveTokensAddresses(address(_asset)); require(address(underlyingToReserveTokens[_asset].aToken) == aToken, "Invalid aToken address"); ( , , , , , bool usageAsCollateralEnabled, , , bool isActive, bool isFrozen) = protocolDataProvider.getReserveConfigurationData(address(_asset)); // An active reserve is an alias for a valid reserve on Aave. // We are checking for the availability of the reserve directly on Aave rather than checking our internal `underlyingToReserveTokens` mappings, // because our mappings can be out-of-date if a new reserve is added to Aave require(isActive, "Invalid aave reserve"); // A frozen reserve doesn't allow any new deposit, borrow or rate swap but allows repayments, liquidations and withdrawals require(!isFrozen, "Frozen aave reserve"); require(usageAsCollateralEnabled, "Collateral disabled on Aave"); } /** * @dev Validates if a new asset can be added as borrow asset for given SetToken */ function _validateNewBorrowAsset(ISetToken _setToken, IERC20 _asset) internal view { require(!borrowAssetEnabled[_setToken][_asset], "Borrow already enabled"); ( , , address variableDebtToken) = protocolDataProvider.getReserveTokensAddresses(address(_asset)); require(address(underlyingToReserveTokens[_asset].variableDebtToken) == variableDebtToken, "Invalid variable debt token address"); (, , , , , , bool borrowingEnabled, , bool isActive, bool isFrozen) = protocolDataProvider.getReserveConfigurationData(address(_asset)); require(isActive, "Invalid aave reserve"); require(!isFrozen, "Frozen aave reserve"); require(borrowingEnabled, "Borrowing disabled on Aave"); } /** * @dev Reads aToken balance and calculates default position unit for given collateral aToken and SetToken * * @return uint256 default collateral position unit */ function _getCollateralPosition(ISetToken _setToken, IAToken _aToken, uint256 _setTotalSupply) internal view returns (uint256) { uint256 collateralNotionalBalance = _aToken.balanceOf(address(_setToken)); return collateralNotionalBalance.preciseDiv(_setTotalSupply); } /** * @dev Reads variableDebtToken balance and calculates external position unit for given borrow asset and SetToken * * @return int256 external borrow position unit */ function _getBorrowPosition(ISetToken _setToken, IERC20 _borrowAsset, uint256 _setTotalSupply) internal view returns (int256) { uint256 borrowNotionalBalance = underlyingToReserveTokens[_borrowAsset].variableDebtToken.balanceOf(address(_setToken)); return borrowNotionalBalance.preciseDivCeil(_setTotalSupply).toInt256().mul(-1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ILendingPool } from "../../../interfaces/external/aave-v2/ILendingPool.sol"; import { ISetToken } from "../../../interfaces/ISetToken.sol"; /** * @title AaveV2 * @author Set Protocol * * Collection of helper functions for interacting with AaveV2 integrations. */ library AaveV2 { /* ============ External ============ */ /** * Get deposit calldata from SetToken * * Deposits an `_amountNotional` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to deposit * @param _amountNotional The amount to be deposited * @param _onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param _referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * * @return address Target contract address * @return uint256 Call value * @return bytes Deposit calldata */ function getDepositCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, address _onBehalfOf, uint16 _referralCode ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "deposit(address,uint256,address,uint16)", _asset, _amountNotional, _onBehalfOf, _referralCode ); return (address(_lendingPool), 0, callData); } /** * Invoke deposit on LendingPool from SetToken * * Deposits an `_amountNotional` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. SetToken deposits 100 USDC and gets in return 100 aUSDC * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to deposit * @param _amountNotional The amount to be deposited */ function invokeDeposit( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional ) external { ( , , bytes memory depositCalldata) = getDepositCalldata( _lendingPool, _asset, _amountNotional, address(_setToken), 0 ); _setToken.invoke(address(_lendingPool), 0, depositCalldata); } /** * Get withdraw calldata from SetToken * * Withdraws an `_amountNotional` of underlying asset from the reserve, burning the equivalent aTokens owned * - E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to withdraw * @param _amountNotional The underlying amount to be withdrawn * Note: Passing type(uint256).max will withdraw the entire aToken balance * @param _receiver Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * * @return address Target contract address * @return uint256 Call value * @return bytes Withdraw calldata */ function getWithdrawCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, address _receiver ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "withdraw(address,uint256,address)", _asset, _amountNotional, _receiver ); return (address(_lendingPool), 0, callData); } /** * Invoke withdraw on LendingPool from SetToken * * Withdraws an `_amountNotional` of underlying asset from the reserve, burning the equivalent aTokens owned * - E.g. SetToken has 100 aUSDC, and receives 100 USDC, burning the 100 aUSDC * * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to withdraw * @param _amountNotional The underlying amount to be withdrawn * Note: Passing type(uint256).max will withdraw the entire aToken balance * * @return uint256 The final amount withdrawn */ function invokeWithdraw( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional ) external returns (uint256) { ( , , bytes memory withdrawCalldata) = getWithdrawCalldata( _lendingPool, _asset, _amountNotional, address(_setToken) ); return abi.decode(_setToken.invoke(address(_lendingPool), 0, withdrawCalldata), (uint256)); } /** * Get borrow calldata from SetToken * * Allows users to borrow a specific `_amountNotional` of the reserve underlying `_asset`, provided that * the borrower already deposited enough collateral, or he was given enough allowance by a credit delegator * on the corresponding debt token (StableDebtToken or VariableDebtToken) * * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to borrow * @param _amountNotional The amount to be borrowed * @param _interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param _referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param _onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the * credit delegator if he has been given credit delegation allowance * * @return address Target contract address * @return uint256 Call value * @return bytes Borrow calldata */ function getBorrowCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode, uint16 _referralCode, address _onBehalfOf ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "borrow(address,uint256,uint256,uint16,address)", _asset, _amountNotional, _interestRateMode, _referralCode, _onBehalfOf ); return (address(_lendingPool), 0, callData); } /** * Invoke borrow on LendingPool from SetToken * * Allows SetToken to borrow a specific `_amountNotional` of the reserve underlying `_asset`, provided that * the SetToken already deposited enough collateral, or it was given enough allowance by a credit delegator * on the corresponding debt token (StableDebtToken or VariableDebtToken) * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to borrow * @param _amountNotional The amount to be borrowed * @param _interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable */ function invokeBorrow( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode ) external { ( , , bytes memory borrowCalldata) = getBorrowCalldata( _lendingPool, _asset, _amountNotional, _interestRateMode, 0, address(_setToken) ); _setToken.invoke(address(_lendingPool), 0, borrowCalldata); } /** * Get repay calldata from SetToken * * Repays a borrowed `_amountNotional` on a specific `_asset` reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the borrowed underlying asset previously borrowed * @param _amountNotional The amount to repay * Note: Passing type(uint256).max will repay the whole debt for `_asset` on the specific `_interestRateMode` * @param _interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param _onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * * @return address Target contract address * @return uint256 Call value * @return bytes Repay calldata */ function getRepayCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode, address _onBehalfOf ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "repay(address,uint256,uint256,address)", _asset, _amountNotional, _interestRateMode, _onBehalfOf ); return (address(_lendingPool), 0, callData); } /** * Invoke repay on LendingPool from SetToken * * Repays a borrowed `_amountNotional` on a specific `_asset` reserve, burning the equivalent debt tokens owned * - E.g. SetToken repays 100 USDC, burning 100 variable/stable debt tokens * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the borrowed underlying asset previously borrowed * @param _amountNotional The amount to repay * Note: Passing type(uint256).max will repay the whole debt for `_asset` on the specific `_interestRateMode` * @param _interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * * @return uint256 The final amount repaid */ function invokeRepay( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode ) external returns (uint256) { ( , , bytes memory repayCalldata) = getRepayCalldata( _lendingPool, _asset, _amountNotional, _interestRateMode, address(_setToken) ); return abi.decode(_setToken.invoke(address(_lendingPool), 0, repayCalldata), (uint256)); } /** * Get setUserUseReserveAsCollateral calldata from SetToken * * Allows borrower to enable/disable a specific deposited asset as collateral * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset deposited * @param _useAsCollateral true` if the user wants to use the deposit as collateral, `false` otherwise * * @return address Target contract address * @return uint256 Call value * @return bytes SetUserUseReserveAsCollateral calldata */ function getSetUserUseReserveAsCollateralCalldata( ILendingPool _lendingPool, address _asset, bool _useAsCollateral ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "setUserUseReserveAsCollateral(address,bool)", _asset, _useAsCollateral ); return (address(_lendingPool), 0, callData); } /** * Invoke an asset to be used as collateral on Aave from SetToken * * Allows SetToken to enable/disable a specific deposited asset as collateral * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset deposited * @param _useAsCollateral true` if the user wants to use the deposit as collateral, `false` otherwise */ function invokeSetUserUseReserveAsCollateral( ISetToken _setToken, ILendingPool _lendingPool, address _asset, bool _useAsCollateral ) external { ( , , bytes memory callData) = getSetUserUseReserveAsCollateralCalldata( _lendingPool, _asset, _useAsCollateral ); _setToken.invoke(address(_lendingPool), 0, callData); } /** * Get swapBorrowRate calldata from SetToken * * Allows a borrower to toggle his debt between stable and variable mode * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset borrowed * @param _rateMode The rate mode that the user wants to swap to * * @return address Target contract address * @return uint256 Call value * @return bytes SwapBorrowRate calldata */ function getSwapBorrowRateModeCalldata( ILendingPool _lendingPool, address _asset, uint256 _rateMode ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "swapBorrowRateMode(address,uint256)", _asset, _rateMode ); return (address(_lendingPool), 0, callData); } /** * Invoke to swap borrow rate of SetToken * * Allows SetToken to toggle it's debt between stable and variable mode * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset borrowed * @param _rateMode The rate mode that the user wants to swap to */ function invokeSwapBorrowRateMode( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _rateMode ) external { ( , , bytes memory callData) = getSwapBorrowRateModeCalldata( _lendingPool, _asset, _rateMode ); _setToken.invoke(address(_lendingPool), 0, callData); } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken is IERC20 { function UNDERLYING_ASSET_ADDRESS() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "./ISetToken.sol"; /** * @title IDebtIssuanceModule * @author Set Protocol * * Interface for interacting with Debt Issuance module interface. */ interface IDebtIssuanceModule { /** * Called by another module to register itself on debt issuance module. Any logic can be included * in case checks need to be made or state needs to be updated. */ function registerToIssuanceModule(ISetToken _setToken) external; /** * Called by another module to unregister itself on debt issuance module. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function unregisterFromIssuanceModule(ISetToken _setToken) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IExchangeAdapter { function getSpender() external view returns(address); function getTradeCalldata( address _fromToken, address _toToken, address _toAddress, uint256 _fromQuantity, uint256 _minToQuantity, bytes memory _data ) external view returns (address, uint256, bytes memory); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { ILendingPoolAddressesProvider } from "./ILendingPoolAddressesProvider.sol"; import { DataTypes } from "./lib/DataTypes.sol"; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ISetToken } from "./ISetToken.sol"; /** * CHANGELOG: * - Added a module level issue hook that can be used to set state ahead of component level * issue hooks */ interface IModuleIssuanceHook { function moduleIssueHook(ISetToken _setToken, uint256 _setTokenQuantity) external; function moduleRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity) external; function componentIssueHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external; function componentRedeemHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external; } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { ILendingPoolAddressesProvider } from "./ILendingPoolAddressesProvider.sol"; interface IProtocolDataProvider { struct TokenData { string symbol; address tokenAddress; } function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function getAllReservesTokens() external view returns (TokenData[] memory); function getAllATokens() external view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external view returns (uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen); function getReserveData(address asset) external view returns (uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp); function getUserReserveData(address asset, address user) external view returns (uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled); function getReserveTokensAddresses(address asset) external view returns (address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IERC20 {} /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; import { IController } from "../../interfaces/IController.sol"; import { IModule } from "../../interfaces/IModule.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "./Invoke.sol"; import { Position } from "./Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "./ResourceIdentifier.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. * * CHANGELOG: * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size * */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { _validateOnlyManagerAndValidSet(_setToken); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { _validateOnlySetManager(_setToken, _caller); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { _validateOnlyValidAndInitializedSet(_setToken); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { _validateOnlyModule(_setToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { _validateOnlyValidAndPendingSet(_setToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must SetToken manager and SetToken must be valid and initialized */ function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must SetToken manager */ function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); } /** * SetToken must be valid and initialized */ function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); } /** * SetToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/21/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function * - 4/21/21: Added approximatelyEquals function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IController } from "../../interfaces/IController.sol"; import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } 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); } } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); }
* Caller must be initialized module and module must be enabled on the controller/
function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); }
462,823
[ 1, 11095, 1297, 506, 6454, 1605, 471, 1605, 1297, 506, 3696, 603, 326, 2596, 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, 389, 5662, 3386, 3120, 12, 45, 694, 1345, 389, 542, 1345, 13, 2713, 1476, 288, 203, 3639, 2583, 12, 203, 5411, 389, 542, 1345, 18, 2978, 7629, 12, 3576, 18, 15330, 13, 422, 467, 694, 1345, 18, 3120, 1119, 18, 12919, 25991, 16, 203, 5411, 315, 3386, 326, 1605, 848, 745, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 2596, 18, 291, 3120, 12, 3576, 18, 15330, 3631, 203, 5411, 315, 3120, 1297, 506, 3696, 603, 2596, 6, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "../../SinglePlus.sol"; import "../../interfaces/venus/IVAIVault.sol"; import "../../interfaces/venus/IVToken.sol"; import "../../interfaces/venus/IVAIController.sol"; import "../../interfaces/venus/IVenusComptroller.sol"; import "../../interfaces/compound/ICToken.sol"; import "../../interfaces/uniswap/IUniswapRouter.sol"; /** * @dev Single plus of Venus BTC. */ contract VenusBTCPlus is SinglePlus { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; event VaiRatioUpdated(uint256 oldLower, uint256 oldTarget, uint256 oldUpper, uint256 newLower, uint256 newTarget, uint256 newUpper); address public constant BTCB = address(0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c); address public constant WBNB = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); address public constant VAI = address(0x4BD17003473389A42DAF6a0a729f6Fdb328BbBd7); address public constant VAI_VAULT = address(0x0667Eed0a0aAb930af74a3dfeDD263A73994f216); address public constant VAI_CONTROLLER = address(0x004065D34C6b18cE4370ced1CeBDE94865DbFAFE); address public constant VENUS = address(0xcF6BB5389c92Bdda8a3747Ddb454cB7a64626C63); address public constant VENUS_BTC = address(0x882C173bC7Ff3b7786CA16dfeD3DFFfb9Ee7847B); address public constant VENUS_COMPTROLLER = address(0xfD36E2c2a6789Db23113685031d7F16329158384); address public constant PANCAKE_SWAP_ROUTER = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); // VAI ratios based on Venus's VAI mint rate uint256 public lowerRatio; // Lower bound of VAI mint rate = lower ratio * VenusComptroller.vaiMintRate() uint256 public targetRatio; // Target VAI mint rate = target ratio * VenusComptroller.vaiMintRate() uint256 public upperRatio; // Upper bound of VAI mint rate = upper ratio * VenusComptroller.vaiMintRate() /** * @dev Initializes vBTC+. */ function initialize() public initializer { SinglePlus.initialize(VENUS_BTC, "", ""); address[] memory _markets = new address[](1); _markets[0] = VENUS_BTC; IVenusComptroller(VENUS_COMPTROLLER).enterMarkets(_markets); lowerRatio = 7000; // 70% * 60% = 42% targetRatio = 8000; // 80% * 60% = 48%; upperRatio = 9000; // 90% * 60% = 54%; } /** * @dev Determines the current liquidity of vBTC+ * @return Total account collateral, total account debt, current ltv */ function getLiquidity() public view returns (uint256, uint256, uint256) { // The only debt is VAI uint256 _vai = IVenusComptroller(VENUS_COMPTROLLER).mintedVAIs(address(this)); // The only collateral is BTCB (, uint256 _liquidity, uint256 _shortfall) = IVenusComptroller(VENUS_COMPTROLLER).getAccountLiquidity(address(this)); uint256 _collateral; if (_liquidity > 0) { // Account liquidity is in excess of collateral requirement _collateral = _vai.add(_liquidity); } else { // Account shortfall below collateral requirement _collateral = _vai.sub(_shortfall); } return (_collateral, _vai, _vai.mul(PERCENT_MAX).div(_collateral)); } /** * @dev Retrive the underlying assets from the investment. * Only governance or strategist can call this function. */ function divest() public virtual override onlyStrategist { // Withdraws all VAI from VAI vault uint256 _vai = IVAIVault(VAI_VAULT).userInfo(address(this)).amount; if (_vai > 0) { IVAIVault(VAI_VAULT).withdraw(_vai); } // Repays all VAI _vai = IERC20Upgradeable(VAI).balanceOf(address(this)); if ((_vai > 0)) { IERC20Upgradeable(VAI).safeApprove(VAI_CONTROLLER, 0); IERC20Upgradeable(VAI).safeApprove(VAI_CONTROLLER, _vai); IVAIController(VAI_CONTROLLER).repayVAI(_vai); } } /** * @dev Returns the amount that can be invested now. The invested token * does not have to be the underlying token. * investable > 0 means it's time to call invest. */ function investable() public view virtual override returns (uint256) { (uint256 _collateral, uint256 _debt, ) = getLiquidity(); uint256 _vaiMintRate = IVenusComptroller(VENUS_COMPTROLLER).vaiMintRate(); // vaiMintRate is scaled with 10000 uint256 _lowerDebt = _collateral.mul(_vaiMintRate).mul(lowerRatio).div(PERCENT_MAX).div(10000); uint256 _targetDebt = _collateral.mul(_vaiMintRate).mul(targetRatio).div(PERCENT_MAX).div(10000); uint256 _upperDebt = _collateral.mul(_vaiMintRate).mul(upperRatio).div(PERCENT_MAX).div(10000); return _debt < _lowerDebt ? _targetDebt.sub(_debt) : (_debt > _upperDebt ? _debt.sub(_targetDebt) : 0); } /** * @dev Invest the underlying assets for additional yield. */ function _invest() internal { (uint256 _collateral, uint256 _debt, ) = getLiquidity(); uint256 _vaiMintRate = IVenusComptroller(VENUS_COMPTROLLER).vaiMintRate(); // vaiMintRate is scaled with 10000 uint256 _lowerDebt = _collateral.mul(_vaiMintRate).mul(lowerRatio).div(PERCENT_MAX).div(10000); uint256 _targetDebt = _collateral.mul(_vaiMintRate).mul(targetRatio).div(PERCENT_MAX).div(10000); uint256 _upperDebt = _collateral.mul(_vaiMintRate).mul(upperRatio).div(PERCENT_MAX).div(10000); if (_debt < _lowerDebt) { // We need to mint more VAI! // Mints maximum VAI using vBTC as collateral IVAIController(VAI_CONTROLLER).mintVAI(_targetDebt.sub(_debt)); uint256 _vai = IERC20Upgradeable(VAI).balanceOf(address(this)); IERC20Upgradeable(VAI).safeApprove(VAI_VAULT, 0); IERC20Upgradeable(VAI).safeApprove(VAI_VAULT, _vai); // Stakes VAI into VAI vault IVAIVault(VAI_VAULT).deposit(_vai); } else if (_debt > _upperDebt) { // We need to repay some VAI! uint256 _shortfall = _debt.sub(_targetDebt); IVAIVault(VAI_VAULT).withdraw(_shortfall); IERC20Upgradeable(VAI).safeApprove(VAI_CONTROLLER, 0); IERC20Upgradeable(VAI).safeApprove(VAI_CONTROLLER, _shortfall); IVAIController(VAI_CONTROLLER).repayVAI(_shortfall); } } /** * @dev Invest the underlying assets for additional yield. * Only governance or strategist can call this function. */ function invest() public virtual override onlyStrategist { _invest(); } /** * @dev Returns the amount of reward that could be harvested now. * harvestable > 0 means it's time to call harvest. */ function harvestable() public view virtual override returns (uint256) { // It will take some code to estimate the pending Venus in Comptroller, // and Comptroller does not provide such a view method. Therefore, we // use the pending Venus in VAI Vault as an estimate! return IVAIVault(VAI_VAULT).pendingXVS(address(this)); } /** * @dev Harvest additional yield from the investment. * Only governance or strategist can call this function. */ function harvest() public virtual override onlyStrategist { // Harvest from Venus comptroller IVenusComptroller(VENUS_COMPTROLLER).claimVenus(address(this)); // Harvest from VAI controller IVAIVault(VAI_VAULT).claim(); uint256 _venus = IERC20Upgradeable(VENUS).balanceOf(address(this)); // PancakeSawp: XVS --> WBNB --> BTCB if (_venus > 0) { IERC20Upgradeable(VENUS).safeApprove(PANCAKE_SWAP_ROUTER, 0); IERC20Upgradeable(VENUS).safeApprove(PANCAKE_SWAP_ROUTER, _venus); address[] memory _path = new address[](3); _path[0] = VENUS; _path[1] = WBNB; _path[2] = BTCB; IUniswapRouter(PANCAKE_SWAP_ROUTER).swapExactTokensForTokens(_venus, uint256(0), _path, address(this), block.timestamp.add(1800)); } // Venus: BTCB --> vBTC uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this)); if (_btcb == 0) return; // If there is performance fee, charged in BTCB uint256 _fee = 0; if (performanceFee > 0) { _fee = _btcb.mul(performanceFee).div(PERCENT_MAX); IERC20Upgradeable(BTCB).safeTransfer(treasury, _fee); _btcb = _btcb.sub(_fee); } IERC20Upgradeable(BTCB).safeApprove(VENUS_BTC, 0); IERC20Upgradeable(BTCB).safeApprove(VENUS_BTC, _btcb); IVToken(VENUS_BTC).mint(_btcb); // Reinvest to get compound yield. _invest(); // Also it's a good time to rebase! rebase(); emit Harvested(VENUS_BTC, _btcb, _fee); } /** * @dev Checks whether a token can be salvaged via salvageToken(). The following three * tokens are not salvageable: * 1) vBTC * 2) XVS * 3) VAI * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view virtual override returns (bool) { return _token != VENUS_BTC && _token != VENUS && _token != VAI; } /** * @dev Returns the amount of single plus token is worth for one underlying token, expressed in WAD. * Venus forks Compound so we use cToken interface from Compound. */ function _conversionRate() internal view virtual override returns (uint256) { // The exchange rate is in WAD return ICToken(VENUS_BTC).exchangeRateStored(); } /** * @dev Withdraws underlying tokens. * @param _receiver Address to receive the token withdraw. * @param _amount Amount of underlying token withdraw. */ function _withdraw(address _receiver, uint256 _amount) internal virtual override { (,,uint256 _shortfall) = IVenusComptroller(VENUS_COMPTROLLER).getHypotheticalAccountLiquidity(address(this), VENUS_BTC, _amount, 0); if (_shortfall > 0) { IVAIVault(VAI_VAULT).withdraw(_shortfall); IERC20Upgradeable(VAI).safeApprove(VAI_CONTROLLER, 0); IERC20Upgradeable(VAI).safeApprove(VAI_CONTROLLER, _shortfall); IVAIController(VAI_CONTROLLER).repayVAI(_shortfall); } IERC20Upgradeable(VENUS_BTC).safeTransfer(_receiver, _amount); // Time to re-invest after withdraw! _invest(); } /** * @dev Updates VAI ratios. Only strategist can update VAI ratios. */ function setVaiRatios(uint256 _lower, uint256 _target, uint256 _upper) public onlyStrategist { require(_lower <= _target && _target <= _upper && _upper <= PERCENT_MAX, "invalid ratio"); uint256 _oldLower = lowerRatio; uint256 _oldTarget = targetRatio; uint256 _oldUpper = upperRatio; lowerRatio = _lower; targetRatio = _target; upperRatio = _upper; // Time to re-invest after setting new rates! _invest(); emit VaiRatioUpdated(_oldLower, _oldTarget, _oldUpper, _lower, _target, _upper); } }
Target VAI mint rate = target ratio * VenusComptroller.vaiMintRate()
uint256 public targetRatio;
15,803,231
[ 1, 2326, 776, 18194, 312, 474, 4993, 273, 1018, 7169, 225, 776, 11797, 799, 337, 1539, 18, 90, 10658, 49, 474, 4727, 1435, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 1018, 8541, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x53Ae490E08eAfCc18148365b15Da6C44D776b402/sources/browser/RandDropExp.sol
* @dev Chef distributes newly generated RugSickPain to each farmmers "onlyOwner" :: for the one who worries about the function, this distribute process is only done by MasterChef contract for farming process/
function distribute(address _to, uint256 _amount) public onlyOwner { require(!initialized); _mint(_to, _amount); initialized = true; }
8,146,027
[ 1, 39, 580, 74, 1015, 1141, 10894, 4374, 534, 637, 55, 1200, 52, 530, 358, 1517, 284, 4610, 81, 414, 315, 3700, 5541, 6, 493, 364, 326, 1245, 10354, 14591, 566, 281, 2973, 326, 445, 16, 333, 25722, 1207, 353, 1338, 2731, 635, 13453, 39, 580, 74, 6835, 364, 284, 4610, 310, 1207, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25722, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 5, 13227, 1769, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 6454, 273, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0x9c3e20c242664B7EB313164D9E975B8B3D057185/sources/contracts/HempSwapFactory.sol
this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'Hemp: INSUFFICIENT_OUTPUT_AMOUNT'); require(amount0Out < _reserve0 && amount1Out < _reserve1, 'Hemp: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'Hemp: INVALID_TO'); if (data.length > 0) IHempCallee(to).hempCall(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'Hemp: INSUFFICIENT_INPUT_AMOUNT'); uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(2)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(2)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'Hemp: K');
3,248,280
[ 1, 2211, 4587, 17, 2815, 445, 1410, 506, 2566, 628, 279, 6835, 1492, 11199, 10802, 24179, 4271, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 12, 11890, 3844, 20, 1182, 16, 2254, 3844, 21, 1182, 16, 1758, 358, 16, 1731, 745, 892, 501, 13, 3903, 2176, 288, 203, 3639, 2583, 12, 8949, 20, 1182, 405, 374, 747, 3844, 21, 1182, 405, 374, 16, 296, 44, 30752, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 15527, 67, 2192, 51, 5321, 8284, 203, 3639, 2583, 12, 8949, 20, 1182, 411, 389, 455, 6527, 20, 597, 3844, 21, 1182, 411, 389, 455, 6527, 21, 16, 296, 44, 30752, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 203, 3639, 2254, 11013, 20, 31, 203, 3639, 2254, 11013, 21, 31, 203, 3639, 1758, 389, 2316, 20, 273, 1147, 20, 31, 203, 3639, 1758, 389, 2316, 21, 273, 1147, 21, 31, 203, 3639, 2583, 12, 869, 480, 389, 2316, 20, 597, 358, 480, 389, 2316, 21, 16, 296, 44, 30752, 30, 10071, 67, 4296, 8284, 203, 3639, 309, 261, 892, 18, 2469, 405, 374, 13, 467, 44, 30752, 3005, 11182, 12, 869, 2934, 76, 30752, 1477, 12, 3576, 18, 15330, 16, 3844, 20, 1182, 16, 3844, 21, 1182, 16, 501, 1769, 203, 3639, 11013, 20, 273, 467, 654, 39, 3462, 24899, 2316, 20, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 11013, 21, 273, 467, 654, 39, 3462, 24899, 2316, 21, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 289, 203, 3639, 2254, 3844, 20, 382, 273, 11013, 20, 405, 389, 455, 6527, 20, 300, 3844, 20, 1182, 692, 11013, 20, 300, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import "../interfaces/IDiamondCut.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct FacetAddressAndSelectorPosition { address facetAddress; uint16 selectorPosition; } struct DiamondStorage { // function selector => facet address and selector position in selectors array mapping(bytes4 => FacetAddressAndSelectorPosition) facetAddressAndSelectorPosition; bytes4[] selectors; mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } function enforceIsContractOwner() view internal { require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner"); } modifier onlyOwner { require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner"); _; } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'Facet[] memory _diamondCut' instead of // 'Facet[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { uint256 selectorCount = diamondStorage().selectors.length; for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { selectorCount = addReplaceRemoveFacetSelectors( selectorCount, _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addReplaceRemoveFacetSelectors( uint256 _selectorCount, address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal returns (uint256) { DiamondStorage storage ds = diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); if (_action == IDiamondCut.FacetCutAction.Add) { require(_newFacetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; address oldFacetAddress = ds.facetAddressAndSelectorPosition[selector].facetAddress; require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); ds.facetAddressAndSelectorPosition[selector] = FacetAddressAndSelectorPosition( _newFacetAddress, uint16(_selectorCount) ); ds.selectors.push(selector); _selectorCount++; } } else if(_action == IDiamondCut.FacetCutAction.Replace) { require(_newFacetAddress != address(0), "LibDiamondCut: Replace facet can't be address(0)"); enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; address oldFacetAddress = ds.facetAddressAndSelectorPosition[selector].facetAddress; // only useful if immutable functions exist require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function"); require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function"); require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist"); // replace old facet address ds.facetAddressAndSelectorPosition[selector].facetAddress = _newFacetAddress; } } else if(_action == IDiamondCut.FacetCutAction.Remove) { require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; FacetAddressAndSelectorPosition memory oldFacetAddressAndSelectorPosition = ds.facetAddressAndSelectorPosition[selector]; require(oldFacetAddressAndSelectorPosition.facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // only useful if immutable functions exist require(oldFacetAddressAndSelectorPosition.facetAddress != address(this), "LibDiamondCut: Can't remove immutable function."); // replace selector with last selector if (oldFacetAddressAndSelectorPosition.selectorPosition != _selectorCount - 1) { bytes4 lastSelector = ds.selectors[_selectorCount - 1]; ds.selectors[oldFacetAddressAndSelectorPosition.selectorPosition] = lastSelector; ds.facetAddressAndSelectorPosition[lastSelector].selectorPosition = oldFacetAddressAndSelectorPosition.selectorPosition; } // delete last selector ds.selectors.pop(); delete ds.facetAddressAndSelectorPosition[selector]; _selectorCount--; } } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } return _selectorCount; } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } }
Internal function version of diamondCut This code is almost the same as the external diamondCut, except it is using 'Facet[] memory _diamondCut' instead of 'Facet[] calldata _diamondCut'. The code is duplicated to prevent copying calldata to memory which causes an error for a two dimensional array.
function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { uint256 selectorCount = diamondStorage().selectors.length; for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { selectorCount = addReplaceRemoveFacetSelectors( selectorCount, _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); }
15,823,056
[ 1, 3061, 445, 1177, 434, 4314, 301, 1434, 15812, 1220, 981, 353, 23889, 326, 1967, 487, 326, 3903, 4314, 301, 1434, 15812, 16, 1335, 518, 353, 1450, 296, 11137, 8526, 3778, 389, 3211, 301, 1434, 15812, 11, 3560, 434, 296, 11137, 8526, 745, 892, 389, 3211, 301, 1434, 15812, 10332, 1021, 981, 353, 16975, 358, 5309, 8933, 745, 892, 358, 3778, 1492, 14119, 392, 555, 364, 279, 2795, 17469, 526, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 4314, 301, 1434, 15812, 12, 203, 3639, 1599, 29401, 1434, 15812, 18, 11137, 15812, 8526, 3778, 389, 3211, 301, 1434, 15812, 16, 203, 3639, 1758, 389, 2738, 16, 203, 3639, 1731, 3778, 389, 1991, 892, 203, 565, 262, 2713, 288, 540, 203, 3639, 2254, 5034, 3451, 1380, 273, 4314, 301, 1434, 3245, 7675, 29829, 18, 2469, 31, 203, 3639, 364, 261, 11890, 5034, 11082, 1016, 31, 11082, 1016, 411, 389, 3211, 301, 1434, 15812, 18, 2469, 31, 11082, 1016, 27245, 288, 203, 5411, 3451, 1380, 273, 527, 5729, 3288, 11137, 19277, 12, 203, 7734, 3451, 1380, 16, 203, 7734, 389, 3211, 301, 1434, 15812, 63, 21568, 1016, 8009, 21568, 1887, 16, 203, 7734, 389, 3211, 301, 1434, 15812, 63, 21568, 1016, 8009, 1128, 16, 203, 7734, 389, 3211, 301, 1434, 15812, 63, 21568, 1016, 8009, 915, 19277, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 3626, 12508, 301, 1434, 15812, 24899, 3211, 301, 1434, 15812, 16, 389, 2738, 16, 389, 1991, 892, 1769, 203, 3639, 4046, 14521, 301, 1434, 15812, 24899, 2738, 16, 389, 1991, 892, 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 ]
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/libraries/internal/Deposits.sol
* @notice Scale tree starting from given index. @dev Starts at leaf/target and moved up towards root. @param deposits_ Deposits state struct. @param index_ The deposit index. @return scaled_ Scaled value./ price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1 start with scaled_1 = 1 Traverse up through Fenwick tree via "update" path, accumulating scale factors as we go scaling==0 means actual scale factor is 1
function scale( DepositsState storage deposits_, uint256 index_ ) internal view returns (uint256 scaled_) { ++index_; scaled_ = Maths.WAD; while (index_ <= SIZE) { uint256 scaling = deposits_.scaling[index_]; if (scaling != 0) scaled_ = Maths.wmul(scaled_, scaling); index_ += lsb(index_); } }
3,630,177
[ 1, 5587, 2151, 5023, 628, 864, 770, 18, 1377, 30620, 622, 7839, 19, 3299, 471, 10456, 731, 23248, 1365, 18, 565, 443, 917, 1282, 67, 4019, 538, 1282, 919, 1958, 18, 565, 770, 67, 565, 1021, 443, 1724, 770, 18, 225, 327, 12304, 67, 282, 348, 12825, 460, 18, 19, 6205, 9169, 854, 8808, 5023, 622, 374, 16, 478, 275, 91, 1200, 2831, 4058, 353, 1898, 415, 1332, 970, 5023, 622, 404, 787, 598, 12304, 67, 21, 273, 404, 2197, 2476, 731, 3059, 478, 275, 91, 1200, 2151, 3970, 315, 2725, 6, 589, 16, 8822, 1776, 3159, 14490, 487, 732, 1960, 10612, 631, 20, 4696, 3214, 3159, 5578, 353, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3159, 12, 203, 3639, 4019, 538, 1282, 1119, 2502, 443, 917, 1282, 67, 16, 203, 3639, 2254, 5034, 770, 67, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 12304, 67, 13, 288, 203, 3639, 965, 1615, 67, 31, 203, 203, 3639, 12304, 67, 273, 2361, 87, 18, 59, 1880, 31, 203, 3639, 1323, 261, 1615, 67, 1648, 11963, 13, 288, 203, 5411, 2254, 5034, 10612, 273, 443, 917, 1282, 27799, 24576, 63, 1615, 67, 15533, 203, 5411, 309, 261, 24576, 480, 374, 13, 12304, 67, 273, 2361, 87, 18, 91, 16411, 12, 20665, 67, 16, 10612, 1769, 203, 5411, 770, 67, 1011, 7180, 70, 12, 1615, 67, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x0000000000aec84F5BFc2af15EAfb943bf4e3522/sources/lib/solady/src/utils/LibBit.sol
@dev Returns 1 if `b` is true, else 0. Input must be clean.
function rawToUint(bool b) internal pure returns (uint256 z) { assembly { z := b } }
4,875,546
[ 1, 1356, 404, 309, 1375, 70, 68, 353, 638, 16, 469, 374, 18, 2741, 1297, 506, 2721, 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 ]
[ 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, 1831, 774, 5487, 12, 6430, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 998, 13, 288, 203, 3639, 19931, 288, 203, 5411, 998, 519, 324, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xe91125f34fcEF2854A890DCf02b74Cb2DcbE377f/sources/SpaceToken.sol
For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) { return personIndexToApproved[_tokenId] == _to; }
2,592,421
[ 1, 1290, 6728, 23556, 434, 7412, 364, 1758, 389, 869, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 25990, 12, 2867, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 3238, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 6175, 1016, 774, 31639, 63, 67, 2316, 548, 65, 422, 389, 869, 31, 203, 225, 289, 203, 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 ]
pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @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); 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; } } contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title Interface for the ST20 token standard */ contract IST20 is StandardToken, DetailedERC20 { // off-chain hash string public tokenDetails; //transfer, transferFrom must respect use respect the result of verifyTransfer function verifyTransfer(address _from, address _to, uint256 _amount) public returns (bool success); /** * @notice mints new tokens and assigns them to the target _investor. * Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet) */ function mint(address _investor, uint256 _amount) public returns (bool success); /** * @notice Burn function used to burn the securityToken * @param _value No. of token that get burned */ function burn(uint256 _value) public; event Minted(address indexed to, uint256 amount); event Burnt(address indexed _burner, uint256 _value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address 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 Interface for all security tokens */ contract ISecurityToken is IST20, Ownable { uint8 public constant PERMISSIONMANAGER_KEY = 1; uint8 public constant TRANSFERMANAGER_KEY = 2; uint8 public constant STO_KEY = 3; uint8 public constant CHECKPOINT_KEY = 4; uint256 public granularity; // Value of current checkpoint uint256 public currentCheckpointId; // Total number of non-zero token holders uint256 public investorCount; // List of token holders address[] public investors; // Permissions this to a Permission module, which has a key of 1 // If no Permission return false - note that IModule withPerm will allow ST owner all permissions anyway // this allows individual modules to override this logic if needed (to not allow ST owner all permissions) function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool); /** * @notice returns module list for a module type * @param _moduleType is which type of module we are trying to remove * @param _moduleIndex is the index of the module within the chosen type */ function getModule(uint8 _moduleType, uint _moduleIndex) public view returns (bytes32, address, bool); /** * @notice returns module list for a module name - will return first match * @param _moduleType is which type of module we are trying to remove * @param _name is the name of the module within the chosen type */ function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address, bool); /** * @notice Queries totalSupply as of a defined checkpoint * @param _checkpointId Checkpoint ID to query as of */ function totalSupplyAt(uint256 _checkpointId) public view returns(uint256); /** * @notice Queries balances as of a defined checkpoint * @param _investor Investor to query balance for * @param _checkpointId Checkpoint ID to query as of */ function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256); /** * @notice Creates a checkpoint that can be used to query historical balances / totalSuppy */ function createCheckpoint() public returns(uint256); /** * @notice gets length of investors array * NB - this length may differ from investorCount if list has not been pruned of zero balance investors * @return length */ function getInvestorsLength() public view returns(uint256); } /** * @title Interface that any module factory contract should implement */ contract IModuleFactory is Ownable { ERC20 public polyToken; uint256 public setupCost; uint256 public usageCost; uint256 public monthlySubscriptionCost; event LogChangeFactorySetupFee(uint256 _oldSetupcost, uint256 _newSetupCost, address _moduleFactory); event LogChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory); event LogChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory); event LogGenerateModuleFromFactory(address _module, bytes32 indexed _moduleName, address indexed _moduleFactory, address _creator, uint256 _timestamp); /** * @notice Constructor * @param _polyAddress Address of the polytoken */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public { polyToken = ERC20(_polyAddress); setupCost = _setupCost; usageCost = _usageCost; monthlySubscriptionCost = _subscriptionCost; } //Should create an instance of the Module, or throw function deploy(bytes _data) external returns(address); /** * @notice Type of the Module factory */ function getType() public view returns(uint8); /** * @notice Get the name of the Module */ function getName() public view returns(bytes32); /** * @notice Get the description of the Module */ function getDescription() public view returns(string); /** * @notice Get the title of the Module */ function getTitle() public view returns(string); /** * @notice Get the Instructions that helped to used the module */ function getInstructions() public view returns (string); /** * @notice Get the tags related to the module factory */ function getTags() public view returns (bytes32[]); //Pull function sig from _data function getSig(bytes _data) internal pure returns (bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint i = 0; i < len; i++) { sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i)))); } } /** * @notice used to change the fee of the setup cost * @param _newSetupCost new setup cost */ function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner { uint256 _oldSetupcost = setupCost; setupCost = _newSetupCost; emit LogChangeFactorySetupFee(_oldSetupcost, setupCost, address(this)); } /** * @notice used to change the fee of the usage cost * @param _newUsageCost new usage cost */ function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner { uint256 _oldUsageCost = usageCost; usageCost = _newUsageCost; emit LogChangeFactoryUsageFee(_oldUsageCost, usageCost, address(this)); } /** * @notice used to change the fee of the subscription cost * @param _newSubscriptionCost new subscription cost */ function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner { uint256 _oldSubscriptionCost = monthlySubscriptionCost; monthlySubscriptionCost = _newSubscriptionCost; emit LogChangeFactorySubscriptionFee(_oldSubscriptionCost, monthlySubscriptionCost, address(this)); } } /** * @title Interface that any module contract should implement */ contract IModule { address public factory; address public securityToken; bytes32 public FEE_ADMIN = "FEE_ADMIN"; ERC20 public polyToken; /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public { securityToken = _securityToken; factory = msg.sender; polyToken = ERC20(_polyAddress); } /** * @notice This function returns the signature of configure function */ function getInitFunction() public returns (bytes4); //Allows owner, factory or permissioned delegate modifier withPerm(bytes32 _perm) { bool isOwner = msg.sender == ISecurityToken(securityToken).owner(); bool isFactory = msg.sender == factory; require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed"); _; } modifier onlyOwner { require(msg.sender == ISecurityToken(securityToken).owner(), "Sender is not owner"); _; } modifier onlyFactory { require(msg.sender == factory, "Sender is not factory"); _; } modifier onlyFactoryOwner { require(msg.sender == IModuleFactory(factory).owner(), "Sender is not factory owner"); _; } /** * @notice Return the permissions flag that are associated with Module */ function getPermissions() public view returns(bytes32[]); /** * @notice used to withdraw the fee by the factory owner */ function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) { require(polyToken.transferFrom(address(this), IModuleFactory(factory).owner(), _amount), "Unable to take fee"); return true; } } /** * @title Interface for the polymath module registry contract */ contract IModuleRegistry { /** * @notice Called by a security token to notify the registry it is using a module * @param _moduleFactory is the address of the relevant module factory */ function useModule(address _moduleFactory) external; /** * @notice Called by moduleFactory owner to register new modules for SecurityToken to use * @param _moduleFactory is the address of the module factory to be registered */ function registerModule(address _moduleFactory) external returns(bool); /** * @notice Use to get all the tags releated to the functionality of the Module Factory. * @param _moduleType Type of module */ function getTagByModuleType(uint8 _moduleType) public view returns(bytes32[]); } /** * @title Utility contract to allow pausing and unpausing of certain functions */ contract Pausable { event Pause(uint256 _timestammp); event Unpause(uint256 _timestamp); bool public paused = false; /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @notice called by the owner to pause, triggers stopped state */ function _pause() internal { require(!paused); paused = true; emit Pause(now); } /** * @notice called by the owner to unpause, returns to normal state */ function _unpause() internal { require(paused); paused = false; emit Unpause(now); } } /** * @title Interface to be implemented by all Transfer Manager modules */ contract ITransferManager is IModule, Pausable { //If verifyTransfer returns: // FORCE_VALID, the transaction will always be valid, regardless of other TM results // INVALID, then the transfer should not be allowed regardless of other TM results // VALID, then the transfer is valid for this TM // NA, then the result from this TM is ignored enum Result {INVALID, NA, VALID, FORCE_VALID} function verifyTransfer(address _from, address _to, uint256 _amount, bool _isTransfer) public returns(Result); function unpause() onlyOwner public { super._unpause(); } function pause() onlyOwner public { super._pause(); } } /** * @title Interface to be implemented by all permission manager modules */ contract IPermissionManager is IModule { function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool); function changePermission(address _delegate, address _module, bytes32 _perm, bool _valid) public returns(bool); function getDelegateDetails(address _delegate) public view returns(bytes32); } /** * @title Interface for all polymath registry contracts */ contract IRegistry { /** * @notice get the contract address * @param _nameKey is the key for the contract address mapping */ function getAddress(string _nameKey) view public returns(address); /** * @notice change the contract address * @param _nameKey is the key for the contract address mapping * @param _newAddress is the new contract address */ function changeAddress(string _nameKey, address _newAddress) public; /** * @notice pause (overridden function) */ function unpause() public; /** * @notice unpause (overridden function) */ function pause() public; } /** * @title Interface for the token burner contract */ interface ITokenBurner { function burn(address _burner, uint256 _value ) external returns(bool); } /** * @title Security Token contract * @notice SecurityToken is an ERC20 token with added capabilities: * @notice - Implements the ST-20 Interface * @notice - Transfers are restricted * @notice - Modules can be attached to it to control its behaviour * @notice - ST should not be deployed directly, but rather the SecurityTokenRegistry should be used */ contract SecurityToken is ISecurityToken { using SafeMath for uint256; bytes32 public securityTokenVersion = "0.0.1"; // Reference to token burner contract ITokenBurner public tokenBurner; // Use to halt all the transactions bool public freeze = false; // Reference to STR contract address public securityTokenRegistry; struct ModuleData { bytes32 name; address moduleAddress; } // Structures to maintain checkpoints of balances for governance / dividends struct Checkpoint { uint256 checkpointId; uint256 value; } mapping (address => Checkpoint[]) public checkpointBalances; Checkpoint[] public checkpointTotalSupply; bool public mintingFinished = false; mapping (bytes4 => bool) transferFunctions; // Module list should be order agnostic! mapping (uint8 => ModuleData[]) public modules; mapping (uint8 => bool) public modulesLocked; uint8 public constant MAX_MODULES = 20; mapping (address => bool) public investorListed; // Emit at the time when module get added event LogModuleAdded( uint8 indexed _type, bytes32 _name, address _moduleFactory, address _module, uint256 _moduleCost, uint256 _budget, uint256 _timestamp ); // Emit when the token details get updated event LogUpdateTokenDetails(string _oldDetails, string _newDetails); // Emit when the granularity get changed event LogGranularityChanged(uint256 _oldGranularity, uint256 _newGranularity); // Emit when Module get removed from the securityToken event LogModuleRemoved(uint8 indexed _type, address _module, uint256 _timestamp); // Emit when the budget allocated to a module is changed event LogModuleBudgetChanged(uint8 indexed _moduleType, address _module, uint256 _budget); // Emit when all the transfers get freeze event LogFreezeTransfers(bool _freeze, uint256 _timestamp); // Emit when new checkpoint created event LogCheckpointCreated(uint256 indexed _checkpointId, uint256 _timestamp); // Emit when the minting get finished event LogFinishedMinting(uint256 _timestamp); // Emit when a module type is locked event LogModuleLocked(uint8 indexed _moduleType, address _locker); // Change the STR address in the event of a upgrade event LogChangeSTRAddress(address indexed _oldAddress, address indexed _newAddress); //if _fallback is true, then we only allow the module if it is set, if it is not set we only allow the owner modifier onlyModule(uint8 _moduleType, bool _fallback) { //Loop over all modules of type _moduleType bool isModuleType = false; for (uint8 i = 0; i < modules[_moduleType].length; i++) { isModuleType = isModuleType || (modules[_moduleType][i].moduleAddress == msg.sender); } if (_fallback && !isModuleType) { require(msg.sender == owner, "Sender is not owner"); } else { require(isModuleType, "Sender is not correct module type"); } _; } modifier checkGranularity(uint256 _amount) { require(_amount.div(granularity).mul(granularity) == _amount, "Unable to modify token balances at this granularity"); _; } /** * @notice Constructor * @param _name Name of the SecurityToken * @param _symbol Symbol of the Token * @param _decimals Decimals for the securityToken * @param _granularity granular level of the token * @param _tokenDetails Details of the token that are stored off-chain (IPFS hash) * @param _securityTokenRegistry Contract address of the security token registry */ constructor ( string _name, string _symbol, uint8 _decimals, uint256 _granularity, string _tokenDetails, address _securityTokenRegistry ) public DetailedERC20(_name, _symbol, _decimals) { //When it is created, the owner is the STR securityTokenRegistry = _securityTokenRegistry; tokenDetails = _tokenDetails; granularity = _granularity; transferFunctions[bytes4(keccak256("transfer(address,uint256)"))] = true; transferFunctions[bytes4(keccak256("transferFrom(address,address,uint256)"))] = true; transferFunctions[bytes4(keccak256("mint(address,uint256)"))] = true; transferFunctions[bytes4(keccak256("burn(uint256)"))] = true; } /** * @notice Function used by issuer to lock a specific module type * @param _moduleType module type to be locked */ function lockModule(uint8 _moduleType) external onlyOwner { require(!modulesLocked[_moduleType]); modulesLocked[_moduleType] = true; emit LogModuleLocked(_moduleType, msg.sender); } /** * @notice Function used to attach the module in security token * @param _moduleFactory Contract address of the module factory that needs to be attached * @param _data Data used for the intialization of the module factory variables * @param _maxCost Maximum cost of the Module factory * @param _budget Budget of the Module factory * @param _locked whether or not the module is supposed to be locked */ function addModule( address _moduleFactory, bytes _data, uint256 _maxCost, uint256 _budget, bool _locked ) external onlyOwner { _addModule(_moduleFactory, _data, _maxCost, _budget, _locked); } /** * @notice _addModule handles the attachment (or replacement) of modules for the ST * @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it * @dev to control restrictions on transfers. * @dev You are allowed to add a new moduleType if: * @dev - there is no existing module of that type yet added * @dev - the last member of the module list is replacable * @param _moduleFactory is the address of the module factory to be added * @param _data is data packed into bytes used to further configure the module (See STO usage) * @param _maxCost max amount of POLY willing to pay to module. (WIP) * @param _locked whether or not the module is supposed to be locked */ function _addModule(address _moduleFactory, bytes _data, uint256 _maxCost, uint256 _budget, bool _locked) internal { //Check that module exists in registry - will throw otherwise IModuleRegistry(IRegistry(securityTokenRegistry).getAddress("ModuleRegistry")).useModule(_moduleFactory); IModuleFactory moduleFactory = IModuleFactory(_moduleFactory); require(modules[moduleFactory.getType()].length < MAX_MODULES, "Limit of MAX MODULES is reached"); uint256 moduleCost = moduleFactory.setupCost(); require(moduleCost <= _maxCost, "Max Cost is always be greater than module cost"); //Check that this module has not already been set as locked require(!modulesLocked[moduleFactory.getType()], "Module has already been set as locked"); //Approve fee for module require(ERC20(IRegistry(securityTokenRegistry).getAddress("PolyToken")).approve(_moduleFactory, moduleCost), "Not able to approve the module cost"); //Creates instance of module from factory address module = moduleFactory.deploy(_data); //Approve ongoing budget require(ERC20(IRegistry(securityTokenRegistry).getAddress("PolyToken")).approve(module, _budget), "Not able to approve the budget"); //Add to SecurityToken module map modules[moduleFactory.getType()].push(ModuleData(moduleFactory.getName(), module)); modulesLocked[moduleFactory.getType()] = _locked; //Emit log event emit LogModuleAdded(moduleFactory.getType(), moduleFactory.getName(), _moduleFactory, module, moduleCost, _budget, now); } /** * @notice Removes a module attached to the SecurityToken * @param _moduleType is which type of module we are trying to remove * @param _moduleIndex is the index of the module within the chosen type */ function removeModule(uint8 _moduleType, uint8 _moduleIndex) external onlyOwner { require(_moduleIndex < modules[_moduleType].length, "Module index doesn't exist as per the choosen module type"); require(modules[_moduleType][_moduleIndex].moduleAddress != address(0), "Module contract address should not be 0x"); require(!modulesLocked[_moduleType], "Module should not be locked"); //Take the last member of the list, and replace _moduleIndex with this, then shorten the list by one emit LogModuleRemoved(_moduleType, modules[_moduleType][_moduleIndex].moduleAddress, now); modules[_moduleType][_moduleIndex] = modules[_moduleType][modules[_moduleType].length - 1]; modules[_moduleType].length = modules[_moduleType].length - 1; } /** * @notice Returns module list for a module type * @param _moduleType is which type of module we are trying to get * @param _moduleIndex is the index of the module within the chosen type * @return bytes32 * @return address * @return bool */ function getModule(uint8 _moduleType, uint _moduleIndex) public view returns (bytes32, address, bool) { if (modules[_moduleType].length > 0) { return ( modules[_moduleType][_moduleIndex].name, modules[_moduleType][_moduleIndex].moduleAddress, modulesLocked[_moduleType] ); } else { return ("", address(0), false); } } /** * @notice returns module list for a module name - will return first match * @param _moduleType is which type of module we are trying to get * @param _name is the name of the module within the chosen type * @return bytes32 * @return address * @return bool */ function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address, bool) { if (modules[_moduleType].length > 0) { for (uint256 i = 0; i < modules[_moduleType].length; i++) { if (modules[_moduleType][i].name == _name) { return ( modules[_moduleType][i].name, modules[_moduleType][i].moduleAddress, modulesLocked[_moduleType] ); } } return ("", address(0), false); } else { return ("", address(0), false); } } /** * @notice allows the owner to withdraw unspent POLY stored by them on the ST. * @dev Owner can transfer POLY to the ST which will be used to pay for modules that require a POLY fee. * @param _amount amount of POLY to withdraw */ function withdrawPoly(uint256 _amount) public onlyOwner { require(ERC20(IRegistry(securityTokenRegistry).getAddress("PolyToken")).transfer(owner, _amount), "In-sufficient balance"); } /** * @notice allows owner to approve more POLY to one of the modules * @param _moduleType module type * @param _moduleIndex module index * @param _budget new budget */ function changeModuleBudget(uint8 _moduleType, uint8 _moduleIndex, uint256 _budget) public onlyOwner { require(_moduleType != 0, "Module type cannot be zero"); require(_moduleIndex < modules[_moduleType].length, "Incorrrect module index"); require(ERC20(IRegistry(securityTokenRegistry).getAddress("PolyToken")).approve(modules[_moduleType][_moduleIndex].moduleAddress, _budget), "Insufficient balance to approve"); emit LogModuleBudgetChanged(_moduleType, modules[_moduleType][_moduleIndex].moduleAddress, _budget); } /** * @notice change the tokenDetails * @param _newTokenDetails New token details */ function updateTokenDetails(string _newTokenDetails) public onlyOwner { emit LogUpdateTokenDetails(tokenDetails, _newTokenDetails); tokenDetails = _newTokenDetails; } /** * @notice allows owner to change token granularity * @param _granularity granularity level of the token */ function changeGranularity(uint256 _granularity) public onlyOwner { require(_granularity != 0, "Granularity can not be 0"); emit LogGranularityChanged(granularity, _granularity); granularity = _granularity; } /** * @notice keeps track of the number of non-zero token holders * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer */ function adjustInvestorCount(address _from, address _to, uint256 _value) internal { if ((_value == 0) || (_from == _to)) { return; } // Check whether receiver is a new token holder if ((balanceOf(_to) == 0) && (_to != address(0))) { investorCount = investorCount.add(1); } // Check whether sender is moving all of their tokens if (_value == balanceOf(_from)) { investorCount = investorCount.sub(1); } //Also adjust investor list if (!investorListed[_to] && (_to != address(0))) { investors.push(_to); investorListed[_to] = true; } } /** * @notice removes addresses with zero balances from the investors list * @param _start Index in investor list at which to start removing zero balances * @param _iters Max number of iterations of the for loop * NB - pruning this list will mean you may not be able to iterate over investors on-chain as of a historical checkpoint */ function pruneInvestors(uint256 _start, uint256 _iters) public onlyOwner { for (uint256 i = _start; i < Math.min256(_start.add(_iters), investors.length); i++) { if ((i < investors.length) && (balanceOf(investors[i]) == 0)) { investorListed[investors[i]] = false; investors[i] = investors[investors.length - 1]; investors.length--; } } } /** * @notice gets length of investors array * NB - this length may differ from investorCount if list has not been pruned of zero balance investors * @return length */ function getInvestorsLength() public view returns(uint256) { return investors.length; } /** * @notice freeze all the transfers */ function freezeTransfers() public onlyOwner { require(!freeze); freeze = true; emit LogFreezeTransfers(freeze, now); } /** * @notice un-freeze all the transfers */ function unfreezeTransfers() public onlyOwner { require(freeze); freeze = false; emit LogFreezeTransfers(freeze, now); } /** * @notice adjust totalsupply at checkpoint after minting or burning tokens */ function adjustTotalSupplyCheckpoints() internal { adjustCheckpoints(checkpointTotalSupply, totalSupply()); } /** * @notice adjust token holder balance at checkpoint after a token transfer * @param _investor address of the token holder affected */ function adjustBalanceCheckpoints(address _investor) internal { adjustCheckpoints(checkpointBalances[_investor], balanceOf(_investor)); } /** * @notice store the changes to the checkpoint objects * @param _checkpoints the affected checkpoint object array * @param _newValue the new value that needs to be stored */ function adjustCheckpoints(Checkpoint[] storage _checkpoints, uint256 _newValue) internal { //No checkpoints set yet if (currentCheckpointId == 0) { return; } //No previous checkpoint data - add current balance against checkpoint if (_checkpoints.length == 0) { _checkpoints.push( Checkpoint({ checkpointId: currentCheckpointId, value: _newValue }) ); return; } //No new checkpoints since last update if (_checkpoints[_checkpoints.length - 1].checkpointId == currentCheckpointId) { return; } //New checkpoint, so record balance _checkpoints.push( Checkpoint({ checkpointId: currentCheckpointId, value: _newValue }) ); } /** * @notice Overloaded version of the transfer function * @param _to receiver of transfer * @param _value value of transfer * @return bool success */ function transfer(address _to, uint256 _value) public returns (bool success) { adjustInvestorCount(msg.sender, _to, _value); require(verifyTransfer(msg.sender, _to, _value), "Transfer is not valid"); adjustBalanceCheckpoints(msg.sender); adjustBalanceCheckpoints(_to); require(super.transfer(_to, _value)); return true; } /** * @notice Overloaded version of the transferFrom function * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { adjustInvestorCount(_from, _to, _value); require(verifyTransfer(_from, _to, _value), "Transfer is not valid"); adjustBalanceCheckpoints(_from); adjustBalanceCheckpoints(_to); require(super.transferFrom(_from, _to, _value)); return true; } /** * @notice validate transfer with TransferManager module if it exists * @dev TransferManager module has a key of 2 * @param _from sender of transfer * @param _to receiver of transfer * @param _amount value of transfer * @return bool */ function verifyTransfer(address _from, address _to, uint256 _amount) public checkGranularity(_amount) returns (bool) { if (!freeze) { bool isTransfer = false; if (transferFunctions[getSig(msg.data)]) { isTransfer = true; } if (modules[TRANSFERMANAGER_KEY].length == 0) { return true; } bool isInvalid = false; bool isValid = false; bool isForceValid = false; for (uint8 i = 0; i < modules[TRANSFERMANAGER_KEY].length; i++) { ITransferManager.Result valid = ITransferManager(modules[TRANSFERMANAGER_KEY][i].moduleAddress).verifyTransfer(_from, _to, _amount, isTransfer); if (valid == ITransferManager.Result.INVALID) { isInvalid = true; } if (valid == ITransferManager.Result.VALID) { isValid = true; } if (valid == ITransferManager.Result.FORCE_VALID) { isForceValid = true; } } return isForceValid ? true : (isInvalid ? false : isValid); } return false; } /** * @notice End token minting period permanently */ function finishMinting() public onlyOwner { mintingFinished = true; emit LogFinishedMinting(now); } /** * @notice mints new tokens and assigns them to the target _investor. * @dev Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet) * @param _investor Address to whom the minted tokens will be dilivered * @param _amount Number of tokens get minted * @return success */ function mint(address _investor, uint256 _amount) public onlyModule(STO_KEY, true) checkGranularity(_amount) returns (bool success) { require(!mintingFinished, "Minting is finished, not able to mint additional tokens"); adjustInvestorCount(address(0), _investor, _amount); require(verifyTransfer(address(0), _investor, _amount), "Transfer is not valid"); adjustBalanceCheckpoints(_investor); adjustTotalSupplyCheckpoints(); totalSupply_ = totalSupply_.add(_amount); balances[_investor] = balances[_investor].add(_amount); emit Minted(_investor, _amount); emit Transfer(address(0), _investor, _amount); return true; } /** * @notice mints new tokens and assigns them to the target _investor. * Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet) * @param _investors A list of addresses to whom the minted tokens will be dilivered * @param _amounts A list of number of tokens get minted and transfer to corresponding address of the investor from _investor[] list * @return success */ function mintMulti(address[] _investors, uint256[] _amounts) public onlyModule(STO_KEY, true) returns (bool success) { require(_investors.length == _amounts.length, "Mis-match in the length of the arrays"); for (uint256 i = 0; i < _investors.length; i++) { mint(_investors[i], _amounts[i]); } return true; } /** * @notice Validate permissions with PermissionManager if it exists, If no Permission return false * @dev Note that IModule withPerm will allow ST owner all permissions anyway * @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions) * @param _delegate address of delegate * @param _module address of PermissionManager module * @param _perm the permissions * @return success */ function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) { if (modules[PERMISSIONMANAGER_KEY].length == 0) { return false; } for (uint8 i = 0; i < modules[PERMISSIONMANAGER_KEY].length; i++) { if (IPermissionManager(modules[PERMISSIONMANAGER_KEY][i].moduleAddress).checkPermission(_delegate, _module, _perm)) { return true; } } } /** * @notice used to set the token Burner address. It only be called by the owner * @param _tokenBurner Address of the token burner contract */ function setTokenBurner(address _tokenBurner) public onlyOwner { tokenBurner = ITokenBurner(_tokenBurner); } /** * @notice Burn function used to burn the securityToken * @param _value No. of token that get burned */ function burn(uint256 _value) checkGranularity(_value) public { adjustInvestorCount(msg.sender, address(0), _value); require(tokenBurner != address(0), "Token Burner contract address is not set yet"); require(verifyTransfer(msg.sender, address(0), _value), "Transfer is not valid"); require(_value <= balances[msg.sender], "Value should no be greater than the balance of msg.sender"); adjustBalanceCheckpoints(msg.sender); adjustTotalSupplyCheckpoints(); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[msg.sender] = balances[msg.sender].sub(_value); require(tokenBurner.burn(msg.sender, _value), "Token burner process is not validated"); totalSupply_ = totalSupply_.sub(_value); emit Burnt(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); } /** * @notice Get function signature from _data * @param _data passed data * @return bytes4 sig */ function getSig(bytes _data) internal pure returns (bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint i = 0; i < len; i++) { sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i)))); } } /** * @notice set a new Security Token Registry contract address in case of upgrade * @param _newAddress is address of new contract */ function changeSecurityTokenRegistryAddress(address _newAddress) public onlyOwner { require(_newAddress != securityTokenRegistry && _newAddress != address(0)); emit LogChangeSTRAddress(securityTokenRegistry, _newAddress); securityTokenRegistry = _newAddress; } /** * @notice Creates a checkpoint that can be used to query historical balances / totalSuppy * @return uint256 */ function createCheckpoint() public onlyModule(CHECKPOINT_KEY, true) returns(uint256) { require(currentCheckpointId < 2**256 - 1); currentCheckpointId = currentCheckpointId + 1; emit LogCheckpointCreated(currentCheckpointId, now); return currentCheckpointId; } /** * @notice Queries totalSupply as of a defined checkpoint * @param _checkpointId Checkpoint ID to query * @return uint256 */ function totalSupplyAt(uint256 _checkpointId) public view returns(uint256) { return getValueAt(checkpointTotalSupply, _checkpointId, totalSupply()); } /** * @notice Queries value at a defined checkpoint * @param checkpoints is array of Checkpoint objects * @param _checkpointId Checkpoint ID to query * @param _currentValue Current value of checkpoint * @return uint256 */ function getValueAt(Checkpoint[] storage checkpoints, uint256 _checkpointId, uint256 _currentValue) internal view returns(uint256) { require(_checkpointId <= currentCheckpointId); //Checkpoint id 0 is when the token is first created - everyone has a zero balance if (_checkpointId == 0) { return 0; } if (checkpoints.length == 0) { return _currentValue; } if (checkpoints[0].checkpointId >= _checkpointId) { return checkpoints[0].value; } if (checkpoints[checkpoints.length - 1].checkpointId < _checkpointId) { return _currentValue; } if (checkpoints[checkpoints.length - 1].checkpointId == _checkpointId) { return checkpoints[checkpoints.length - 1].value; } uint256 min = 0; uint256 max = checkpoints.length - 1; while (max > min) { uint256 mid = (max + min) / 2; if (checkpoints[mid].checkpointId == _checkpointId) { max = mid; break; } if (checkpoints[mid].checkpointId < _checkpointId) { min = mid + 1; } else { max = mid; } } return checkpoints[max].value; } /** * @notice Queries balances as of a defined checkpoint * @param _investor Investor to query balance for * @param _checkpointId Checkpoint ID to query as of */ function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256) { return getValueAt(checkpointBalances[_investor], _checkpointId, balanceOf(_investor)); } } /** * @title SecurityToken V2 * @notice Mockup of how an upgrade of SecurityToken would look like */ contract SecurityTokenV2 is SecurityToken { bytes32 public securityTokenVersion = "0.0.2"; /** * @notice Constructor * @param _name Name of the SecurityToken * @param _symbol Symbol of the Token * @param _decimals Decimals for the securityToken * @param _granularity granular level of the token * @param _tokenDetails Details of the token that are stored offchain (IPFS hash) * @param _securityTokenRegistry Contract address of the security token registry */ constructor ( string _name, string _symbol, uint8 _decimals, uint256 _granularity, string _tokenDetails, address _securityTokenRegistry ) public SecurityToken( _name, _symbol, _decimals, _granularity, _tokenDetails, _securityTokenRegistry) { } }
* @notice allows the owner to withdraw unspent POLY stored by them on the ST. @dev Owner can transfer POLY to the ST which will be used to pay for modules that require a POLY fee. @param _amount amount of POLY to withdraw/
function withdrawPoly(uint256 _amount) public onlyOwner { require(ERC20(IRegistry(securityTokenRegistry).getAddress("PolyToken")).transfer(owner, _amount), "In-sufficient balance"); }
13,046,593
[ 1, 5965, 87, 326, 3410, 358, 598, 9446, 640, 20693, 19383, 61, 4041, 635, 2182, 603, 326, 2347, 18, 225, 16837, 848, 7412, 19383, 61, 358, 326, 2347, 1492, 903, 506, 1399, 358, 8843, 364, 4381, 716, 2583, 279, 19383, 61, 14036, 18, 225, 389, 8949, 3844, 434, 19383, 61, 358, 598, 9446, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12487, 12, 11890, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 654, 39, 3462, 12, 45, 4243, 12, 7462, 1345, 4243, 2934, 588, 1887, 2932, 12487, 1345, 7923, 2934, 13866, 12, 8443, 16, 389, 8949, 3631, 315, 382, 17, 87, 11339, 11013, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; //import 'hardhat/console.sol'; import '@openzeppelin/contracts/access/AccessControl.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './IPool.sol'; import './ICorePool.sol'; import './ModaConstants.sol'; import './EscrowedModaERC20.sol'; import './ModaPoolFactory.sol'; /** * @title Moda Pool Base * * @notice An abstract contract containing common logic for any MODA pool, * be it core pool (permanent pool like MODA/ETH or MODA core pool) or something else. * * @dev Deployment and initialization. * Any pool deployed must have 3 token instance addresses defined on deployment: * - MODA token address * - sMODA token address, used to mint sMODA rewards * - pool token address, it can be MODA token address, MODA/ETH pair address, and others */ abstract contract ModaPoolBase is IPool, ModaAware, ModaPoolFactory, ReentrancyGuard, AccessControl { // @dev POOL_UID defined to add another check to ensure compliance with the contract. function POOL_UID() public pure returns (uint256) { return ModaConstants.POOL_UID; } // @dev modaPool MODA ERC20 Liquidity Pool contract address. // @dev This value is address(0) for the default MODA Core Pool. // @dev This value MUST be provided for any pool created which is not a MODA pool. // @dev This is used in the case where poolToken != moda. // The use case relates to shadowing Liquidity Pool stakes // by allowing people to store the LP tokens here to gain // further MODA/sMODA rewards. I'm not sure it's both. (dex 2021.09.16) address modaPool; /// @dev Data structure representing token holder using a pool struct User { // @dev Total staked amount uint256 tokenAmount; // @dev Total weight uint256 totalWeight; // @dev Auxiliary variable for yield calculation uint256 subYieldRewards; // @dev Auxiliary variable for vault rewards calculation uint256 subVaultRewards; // @dev An array of holder's deposits Deposit[] deposits; } /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to sMODA ERC20 Token EscrowedModaERC20 instance address public immutable override smoda; /// @dev Link to the pool token instance, for example MODA or MODA/ETH pair address public immutable override poolToken; /// @dev Pool weight, 100 for MODA pool or 900 for MODA/ETH uint32 public override weight; /// @dev Block number of the last yield distribution event /// This gets initialised at the first rewards pass after rewardStartTime. uint256 public override lastYieldDistribution; /// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking uint256 public override usersLockingWeight; /** * @dev Stake weight is proportional to deposit amount and time locked, precisely * "deposit amount wei multiplied by (fraction of the year locked plus one)" * @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1], * weight is stored multiplied by 1e6 constant, as an integer * @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6 * @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and * weight is a deposit amount multiplied by 2 * 1e6 */ uint256 internal constant WEIGHT_MULTIPLIER = 1e6; /// @dev Used to calculate yield rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public override yieldRewardsPerWeight; /** * @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one, * we use simplified calculation and use the following constant instead previos one */ uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER; /** * @dev Rewards per weight are stored multiplied by 1e12, as integers. */ uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e12; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked */ event Staked(address indexed _by, address indexed _from, uint256 amount); /** * @dev Fired in _updateStakeLock() and updateStakeLock() * * @param _by an address which performed an operation * @param depositId updated deposit ID * @param lockedFrom deposit locked from value * @param lockedUntil updated deposit locked until value */ event StakeLockUpdated( address indexed _by, uint256 depositId, uint256 lockedFrom, uint256 lockedUntil ); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked */ event Unstaked(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerWeight updated yield rewards per weight value * @param lastYieldDistribution usually, current block number */ event Synchronized( address indexed _by, uint256 yieldRewardsPerWeight, uint256 lastYieldDistribution ); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param sModa flag indicating if reward was paid (minted) in sMODA * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, bool sModa, uint256 amount); /** * @dev Fired in setWeight() * * @param _by an address which performed an operation, always a factory * @param _fromVal old pool weight value * @param _toVal new pool weight value */ event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal); /** * @dev Overridden in sub-contracts to construct the pool * * @param _moda MODA ERC20 Token ModaERC20 address * @param _modaPool MODA ERC20 Liquidity Pool contract address * @param _smoda sMODA ERC20 Token EscrowedModaERC20 address * @param _poolToken token the pool operates on, for example MODA or MODA/ETH pair * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one * @param _modaPerBlock initial MODA/block value for rewards * @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks * @param _endBlock block number when farming stops and rewards cannot be updated anymore */ constructor( address _moda, address _modaPool, address _smoda, address _poolToken, uint32 _weight, uint256 _modaPerBlock, uint256 _blocksPerUpdate, uint256 _initBlock, uint256 _endBlock ) ModaPoolFactory(_moda, _modaPerBlock, _blocksPerUpdate, _initBlock, _endBlock) { // verify the inputs are set require(_smoda != address(0), 'sMODA address not set'); require(_poolToken != address(0), 'pool token address not set'); require(_initBlock >= block.number, 'init block not set'); require(_weight > 0, 'pool weight not set'); require( ((_poolToken == _moda ? 1 : 0) ^ (_modaPool != address(0) ? 1 : 0)) == 1, 'The pool is either a MODA pool or manages external tokens, never both' ); // verify MODA instance supplied require(Token(_moda).TOKEN_UID() == ModaConstants.TOKEN_UID, 'MODA TOKEN_UID invalid'); // verify sMODA instance supplied require( EscrowedModaERC20(_smoda).ESCROWTOKEN_UID() == ModaConstants.ESCROWTOKEN_UID, 'sMODA ESCROWTOKEN_UID invalid' ); if (_modaPool != address(0)) { require(ModaPoolBase(_modaPool).POOL_UID() == ModaConstants.POOL_UID); } // save the inputs into internal state variables modaPool = _modaPool; smoda = _smoda; poolToken = _poolToken; _setWeight(_weight); // init the dependent internal state variables lastYieldDistribution = _initBlock; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setRoleAdmin(ModaConstants.ROLE_TOKEN_CREATOR, DEFAULT_ADMIN_ROLE); grantRole(ModaConstants.ROLE_TOKEN_CREATOR, _msgSender()); } /** * @dev Granting privileges required for allowing ModaCorePool and whatever else later, * the ability to mint Tokens as required. */ function grantPrivilege(bytes32 _role, address _account) public onlyOwner { grantRole(_role, _account); } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view override returns (uint256) { // `newYieldRewardsPerWeight` will store stored a recalculated value for `yieldRewardsPerWeight` uint256 newYieldRewardsPerWeight; // if smart contract state was not updated recently, `yieldRewardsPerWeight` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (block.number > lastYieldDistribution && usersLockingWeight != 0) { uint256 endBlock = endBlock; uint256 multiplier = block.number > endBlock ? endBlock - lastYieldDistribution : block.number - lastYieldDistribution; uint256 modaRewards = (multiplier * weight * modaPerBlock) / totalWeight; // recalculated value for `yieldRewardsPerWeight` newYieldRewardsPerWeight = rewardToWeight(modaRewards, usersLockingWeight) + yieldRewardsPerWeight; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerWeight = yieldRewardsPerWeight; } // based on the rewards per weight value, calculate pending rewards; User memory user = users[_staker]; uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view override returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view override returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Stakes specified amount of tokens for the specified amount of time, * and pays pending yield rewards if any * * @dev Requires amount to stake to be greater than zero * * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSMODA a flag indicating if previous reward to be paid as sMODA */ function stake( uint256 _amount, uint256 _lockUntil, bool _useSMODA ) external override { // delegate call to an internal function _stake(msg.sender, _amount, _lockUntil, _useSMODA, false); } /** * @notice Unstakes specified amount of tokens, and pays pending yield rewards if any * * @dev Requires amount to unstake to be greater than zero * * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSMODA a flag indicating if reward to be paid as sMODA */ function unstake( uint256 _depositId, uint256 _amount, bool _useSMODA ) external override { // delegate call to an internal function //console.log('ModaPoolBase unstake', _msgSender()); _unstake(msg.sender, _depositId, _amount, _useSMODA); } /** * @notice Extends locking period for a given deposit * * @dev Requires new lockedUntil value to be: * higher than the current one, and * in the future, but * no more than 1 year in the future * * @param depositId updated deposit ID * @param lockedUntil updated deposit locked until value * @param useSMODA used for _processRewards check if it should use MODA or sMODA */ function updateStakeLock( uint256 depositId, uint256 lockedUntil, bool useSMODA ) external { // sync and call processRewards _sync(); _processRewards(msg.sender, useSMODA, false); // delegate call to an internal function _updateStakeLock(msg.sender, depositId, lockedUntil); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently */ function sync() external override { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev When timing conditions are not met (executed too frequently, or after * end block), function doesn't throw and exits silently * * @param _useSMODA flag indicating whether to mint sMODA token as a reward or not; * when set to true - sMODA reward is minted immediately and sent to sender, * when set to false - new MODA reward deposit gets created if pool is an MODA pool * (poolToken is MODA token), or new pool deposit gets created together with sMODA minted * when pool is not an MODA pool (poolToken is not an MODA token) */ function processRewards(bool _useSMODA) external virtual override { // delegate call to an internal function _processRewards(msg.sender, _useSMODA, true); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function setWeight(uint32 _weight) external override onlyOwner { _setWeight(_weight); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function _setWeight(uint32 _weight) internal onlyOwner { ///TODO: this could be more efficient. // order of operations is important here. _changePoolWeight(_weight); // set the new weight value weight = _weight; // emit an event logging old and new weight values emit PoolWeightUpdated(msg.sender, weight, _weight); } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User memory user = users[_staker]; // and perform the calculation using the values read return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSMODA a flag indicating if previous reward to be paid as sMODA * @param _isYield a flag indicating if that stake is created to store yield reward * from the previously unstaked stake */ function _stake( address _staker, uint256 _amount, uint256 _lockUntil, bool _useSMODA, bool _isYield ) internal virtual { // validate the inputs // console.log('lockUntil', _lockUntil); // console.log('timestamp', block.timestamp); require(_amount > 0, 'zero amount'); require( _lockUntil == 0 || (_lockUntil > block.timestamp && _lockUntil - block.timestamp <= 365 days), 'invalid lock interval' ); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, _useSMODA, false); } // in most of the cases added amount `addedAmount` is simply `_amount` // however for deflationary tokens this can be different // read the current balance uint256 previousBalance = IERC20(poolToken).balanceOf(address(this)); // transfer `_amount`; note: some tokens may get burnt here transferPoolTokenFrom(address(msg.sender), address(this), _amount); // read new balance, usually this is just the difference `previousBalance - _amount` uint256 newBalance = IERC20(poolToken).balanceOf(address(this)); // calculate real amount taking into account deflation uint256 addedAmount = newBalance - previousBalance; // set the `lockFrom` and `lockUntil` taking into account that // zero value for `_lockUntil` means "no locking" and leads to zero values // for both `lockFrom` and `lockUntil` uint256 lockFrom = _lockUntil > 0 ? block.timestamp : 0; uint256 lockUntil = _lockUntil; // stake weight formula rewards for locking uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount; // makes sure stakeWeight is valid assert(stakeWeight > 0); // create and save the deposit (append it to deposits array) Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); // deposit ID is an index of the deposit in `deposits` array user.deposits.push(deposit); // update user record user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight += stakeWeight; // emit an event emit Staked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes tokens (which previously staked them) * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSMODA a flag indicating if reward to be paid as sMODA */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSMODA ) internal virtual { // verify an amount is set require(_amount > 0, 'zero amount'); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // deposit structure may get deleted, so we save isYield flag to be able to use it bool isYield = stakeDeposit.isYield; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(stakeDeposit.tokenAmount >= _amount, 'amount exceeds stake'); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, _useSMODA, false); // recalculate deposit weight uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount); // update the deposit, or delete it if its depleted if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; } else { stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } // update user record user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // if the deposit was created by the pool itself as a yield reward if (isYield) { // mint the yield via the factory mintYieldTo(msg.sender, _amount); } else { // otherwise just return tokens back to holder transferPoolToken(msg.sender, _amount); } // emit an event emit Unstaked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`), * updates factory state via `updateMODAPerBlock` */ function _sync() internal virtual { // update MODA per block value in factory if required if (shouldUpdateRatio()) { updateMODAPerBlock(); } // check bound conditions and if these are not met - // exit silently, without emitting an event uint256 lastBlock = endBlock; if (lastYieldDistribution >= lastBlock) { return; } if (block.number <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingWeight == 0) { lastYieldDistribution = block.number; return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = block.number > endBlock ? endBlock : block.number; uint256 blocksPassed = currentBlock - lastYieldDistribution; // calculate the reward uint256 modaReward = (blocksPassed * modaPerBlock * weight) / totalWeight; // update rewards per weight and `lastYieldDistribution` yieldRewardsPerWeight += rewardToWeight(modaReward, usersLockingWeight); lastYieldDistribution = currentBlock; // emit an event emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _useSMODA flag indicating whether to mint sMODA token as a reward or not, see processRewards() * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated and optionally re-staked */ function _processRewards( address _staker, bool _useSMODA, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // if sMODA is requested if (_useSMODA) { // - mint sMODA mintSModa(_staker, pendingYield); } else if (poolToken == moda) { // calculate pending yield weight, // 2e6 is the bonus weight when staking for 1 year uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER; // if the pool is MODA Pool - create new MODA deposit // and save it - push it into deposits array Deposit memory newDeposit = Deposit({ tokenAmount: pendingYield, lockedFrom: block.timestamp, lockedUntil: block.timestamp + 365 days, // staking yield for 1 year weight: depositWeight, isYield: true }); user.deposits.push(newDeposit); // update user record user.tokenAmount += pendingYield; user.totalWeight += depositWeight; // update global variable usersLockingWeight += depositWeight; } else { // Force a hard error in this case. // The pool was somehow not constructed correctly. assert(modaPool != address(0)); // for other pools - stake as pool. // NB: the target modaPool must be configured to give // this contract instance the ROLE_TOKEN_CREATOR role/privilege. ICorePool(modaPool).stakeAsPool(_staker, pendingYield); } // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); } // emit an event emit YieldClaimed(msg.sender, _staker, _useSMODA, pendingYield); } /** * @dev See updateStakeLock() * * @param _staker an address to update stake lock * @param _depositId updated deposit ID * @param _lockedUntil updated deposit locked until value */ function _updateStakeLock( address _staker, uint256 _depositId, uint256 _lockedUntil ) internal { // validate the input time require(_lockedUntil > block.timestamp, 'lock should be in the future'); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // validate the input against deposit structure require(_lockedUntil > stakeDeposit.lockedUntil, 'invalid new lock'); // verify locked from and locked until values if (stakeDeposit.lockedFrom == 0) { require(_lockedUntil - block.timestamp <= 365 days, 'max lock period is 365 days'); stakeDeposit.lockedFrom = block.timestamp; } else { require( _lockedUntil - stakeDeposit.lockedFrom <= 365 days, 'max lock period is 365 days' ); } // update locked until value, calculate new weight stakeDeposit.lockedUntil = _lockedUntil; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount; // save previous weight uint256 previousWeight = stakeDeposit.weight; // update weight stakeDeposit.weight = newWeight; // update user total weight and global locking weight user.totalWeight = user.totalWeight - previousWeight + newWeight; usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // emit an event emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil); } /** * @dev Converts stake weight (not to be mixed with the pool weight) to * MODA reward value, applying the 10^12 division on weight * * @param _weight stake weight * @param rewardPerWeight MODA reward per weight * @return reward value normalized to 10^12 */ function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) { // apply the formula and return return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER; } /** * @dev Converts reward MODA value to stake weight (not to be mixed with the pool weight), * applying the 10^12 multiplication on the reward * - OR - * @dev Converts reward MODA value to reward/weight if stake weight is supplied as second * function parameter instead of reward/weight * * @param reward yield reward * @param rewardPerWeight reward/weight (or stake weight) * @return stake weight (or reward/weight) */ function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) { // apply the reverse formula and return return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight; } /** * @dev Executes EscrowedModaERC20.mint(_to, _values) * on the bound EscrowedModaERC20 instance * * @dev Reentrancy safe due to the EscrowedModaERC20 design */ function mintSModa(address _to, uint256 _value) private { // just delegate call to the target //console.log(_msgSender()); EscrowedModaERC20(smoda).mint(_to, _value); } /** * @dev Executes SafeERC20.safeTransfer on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolToken(address _to, uint256 _value) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransfer(IERC20(poolToken), _to, _value); } /** * @dev Executes SafeERC20.safeTransferFrom on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolTokenFrom( address _from, address _to, uint256 _value ) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value); } function _poolWeight() internal view override returns (uint32) { return weight; } }
* @dev Fired in _stake() and stake() @param _by an address which performed an operation, usually token holder @param _from token holder address, the tokens will be returned to that address @param amount amount of tokens staked/
event Staked(address indexed _by, address indexed _from, uint256 amount);
5,508,097
[ 1, 42, 2921, 316, 389, 334, 911, 1435, 471, 384, 911, 1435, 225, 389, 1637, 392, 1758, 1492, 9591, 392, 1674, 16, 11234, 1147, 10438, 225, 389, 2080, 1147, 10438, 1758, 16, 326, 2430, 903, 506, 2106, 358, 716, 1758, 225, 3844, 3844, 434, 2430, 384, 9477, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 2575, 934, 9477, 12, 2867, 8808, 389, 1637, 16, 1758, 8808, 389, 2080, 16, 2254, 5034, 3844, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Contract Version Manager */ contract ContractManager is Ownable { event VersionAdded( string contractName, string versionName, address indexed implementation ); event StatusChanged( string contractName, string versionName, Status status ); event BugLevelChanged( string contractName, string versionName, BugLevel bugLevel ); event VersionAudited(string contractName, string versionName); event VersionRecommended(string contractName, string versionName); event RecommendedVersionRemoved(string contractName); /** * @dev Indicates the status of the version */ enum Status {BETA, RC, PRODUCTION, DEPRECATED} /** * @dev Indicates the highest level of bug found in this version */ enum BugLevel{NONE, LOW, MEDIUM, HIGH, CRITICAL} /** * @dev struct to store info about each version */ struct Version { string versionName; // ie: "0.0.1" Status status; BugLevel bugLevel; address implementation; bool audited; uint256 timeAdded; } /** * @dev List of all registered contracts */ string[] internal _contracts; /** * @dev To keep track of which contracts have been registered so far * to save gas while checking for redundant contracts */ mapping(string => bool) internal _contractExists; /** * @dev To keep track of all versions of a given contract */ mapping(string => string[]) internal _contractVsVersionString; /** * @dev Mapping of contract name & version name to version struct */ mapping(string => mapping(string => Version)) internal _contractVsVersions; /** * @dev Mapping between contract name and the name of its recommended * version */ mapping(string => string) internal _contractVsRecommendedVersion; modifier nonZeroAddress(address _address){ require(_address != address(0), "The provided address is a 0 address"); _; } modifier contractRegistered(string contractName) { require(_contractExists[contractName], "Contract does not exists"); _; } modifier versionExists(string contractName, string versionName) { require( _contractVsVersions[contractName][versionName].implementation != address(0), "Version does not exists for contract" ); _; } /** * @dev Allow owner to add a new version for a contract * @param contractName The contract name * @param versionName The version name * @param status Status of the new version * @param implementation The address of the new version */ function addVersion( string contractName, string versionName, Status status, address implementation ) external onlyOwner nonZeroAddress(implementation) { //do not allow contract name to be the empty string require( bytes(contractName).length > 0, "ContractName cannot be empty" ); //do not allow empty string as version name require( bytes(versionName).length > 0, "VersionName cannot be empty" ); //implementation must be a contract address require( Address.isContract(implementation), "Iimplementation cannot be a non-contract address" ); //version should not already exist for the contract require( _contractVsVersions[contractName][versionName].implementation == address(0), "This Version already exists for this contract" ); //if this is a new contractName then push it to the contracts[] array if (!_contractExists[contractName]) { _contracts.push(contractName); _contractExists[contractName] = true; } _contractVsVersionString[contractName].push(versionName); _contractVsVersions[contractName][versionName] = Version({ versionName:versionName, status:status, bugLevel:BugLevel.NONE, implementation:implementation, audited:false, timeAdded:block.timestamp }); emit VersionAdded(contractName, versionName, implementation); } /** * @dev Change the status of a version of a contract * @param contractName Name of the contract * @param versionName Version of the contract * @param status Status to be set */ function changeStatus( string contractName, string versionName, Status status ) external onlyOwner contractRegistered(contractName) versionExists(contractName, versionName) { string storage recommendedVersion = _contractVsRecommendedVersion[ contractName ]; //if the recommended version is being marked as DEPRECATED then it will //be removed from being recommended if ( keccak256( abi.encodePacked( recommendedVersion ) ) == keccak256( abi.encodePacked( versionName ) ) && status == Status.DEPRECATED ) { removeRecommendedVersion(contractName); } _contractVsVersions[contractName][versionName].status = status; emit StatusChanged(contractName, versionName, status); } /** * @dev Change the bug level for a version of a contract * @param contractName Name of the contract * @param versionName Version of the contract * @param bugLevel New bug level for the contract */ function changeBugLevel( string contractName, string versionName, BugLevel bugLevel ) external onlyOwner contractRegistered(contractName) versionExists(contractName, versionName) { string storage recommendedVersion = _contractVsRecommendedVersion[ contractName ]; //if the recommended version of this contract is being marked as // CRITICAL (status level 4) then it will no longer be marked as // recommended if ( keccak256( abi.encodePacked( recommendedVersion ) ) == keccak256( abi.encodePacked( versionName ) ) && bugLevel == BugLevel.CRITICAL ) { removeRecommendedVersion(contractName); } _contractVsVersions[contractName][versionName].bugLevel = bugLevel; emit BugLevelChanged(contractName, versionName, bugLevel); } /** * @dev Mark a version of a contract as having been audited * @param contractName Name of the contract * @param versionName Version of the contract */ function markVersionAudited( string contractName, string versionName ) external contractRegistered(contractName) versionExists(contractName, versionName) onlyOwner { //this version should not already be marked audited require( !_contractVsVersions[contractName][versionName].audited, "Version is already audited" ); _contractVsVersions[contractName][versionName].audited = true; emit VersionAudited(contractName, versionName); } /** * @dev Set recommended version * @param contractName Name of the contract * @param versionName Version of the contract * Version should be in Production stage (status 2) and bug level should * not be HIGH or CRITICAL (status level should be less than 3). * Version must be marked as audited */ function markRecommendedVersion( string contractName, string versionName ) external onlyOwner contractRegistered(contractName) versionExists(contractName, versionName) { //version must be in PRODUCTION state (status 2) require( _contractVsVersions[contractName][versionName].status == Status.PRODUCTION, "Version is not in PRODUCTION state (status level should be 2)" ); //check version must be audited require( _contractVsVersions[contractName][versionName].audited, "Version is not audited" ); //version must have bug level lower than HIGH require( _contractVsVersions[contractName][versionName].bugLevel < BugLevel.HIGH, "Version bug level is HIGH or CRITICAL (bugLevel should be < 3)" ); //mark new version as recommended version for the contract _contractVsRecommendedVersion[contractName] = versionName; emit VersionRecommended(contractName, versionName); } /** * @dev Get the version of the recommended version for a contract. * @return Details of recommended version */ function getRecommendedVersion( string contractName ) external view contractRegistered(contractName) returns ( string versionName, Status status, BugLevel bugLevel, address implementation, bool audited, uint256 timeAdded ) { versionName = _contractVsRecommendedVersion[contractName]; Version storage recommendedVersion = _contractVsVersions[ contractName ][ versionName ]; status = recommendedVersion.status; bugLevel = recommendedVersion.bugLevel; implementation = recommendedVersion.implementation; audited = recommendedVersion.audited; timeAdded = recommendedVersion.timeAdded; return ( versionName, status, bugLevel, implementation, audited, timeAdded ); } /** * @dev Get the total number of contracts registered */ function getTotalContractCount() external view returns (uint256 count) { count = _contracts.length; return count; } /** * @dev Get total count of versions for a contract * @param contractName Name of the contract */ function getVersionCountForContract(string contractName) external view returns (uint256 count) { count = _contractVsVersionString[contractName].length; return count; } /** * @dev Returns the contract at index * @param index The index to be searched for */ function getContractAtIndex(uint256 index) external view returns (string contractName) { contractName = _contracts[index]; return contractName; } /** * @dev Returns versionName of a contract at a specific index * @param contractName Name of the contract * @param index The index to be searched for */ function getVersionAtIndex(string contractName, uint256 index) external view returns (string versionName) { versionName = _contractVsVersionString[contractName][index]; return versionName; } /** * @dev Returns the version details for the given contract and version * @param contractName Name of the contract * @param versionName Version string for the contract */ function getVersionDetails(string contractName, string versionName) external view returns ( string versionString, Status status, BugLevel bugLevel, address implementation, bool audited, uint256 timeAdded ) { Version storage v = _contractVsVersions[contractName][versionName]; versionString = v.versionName; status = v.status; bugLevel = v.bugLevel; implementation = v.implementation; audited = v.audited; timeAdded = v.timeAdded; return ( versionString, status, bugLevel, implementation, audited, timeAdded ); } /** * @dev Remove the "recommended" status of the currently recommended version * of a contract (if any) * @param contractName Name of the contract */ function removeRecommendedVersion(string contractName) public onlyOwner contractRegistered(contractName) { //delete it from mapping delete _contractVsRecommendedVersion[contractName]; emit RecommendedVersionRemoved(contractName); } }
* @dev Returns the version details for the given contract and version @param contractName Name of the contract @param versionName Version string for the contract/
function getVersionDetails(string contractName, string versionName) external view returns ( string versionString, Status status, BugLevel bugLevel, address implementation, bool audited, uint256 timeAdded ) { Version storage v = _contractVsVersions[contractName][versionName]; versionString = v.versionName; status = v.status; bugLevel = v.bugLevel; implementation = v.implementation; audited = v.audited; timeAdded = v.timeAdded; return ( versionString, status, bugLevel, implementation, audited, timeAdded ); }
12,866,507
[ 1, 1356, 326, 1177, 3189, 364, 326, 864, 6835, 471, 1177, 225, 6835, 461, 1770, 434, 326, 6835, 225, 1177, 461, 4049, 533, 364, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8343, 3790, 12, 1080, 6835, 461, 16, 533, 1177, 461, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 533, 1177, 780, 16, 203, 5411, 2685, 1267, 16, 203, 5411, 16907, 2355, 7934, 2355, 16, 203, 5411, 1758, 4471, 16, 203, 5411, 1426, 8215, 329, 16, 203, 5411, 2254, 5034, 813, 8602, 203, 3639, 262, 203, 565, 288, 203, 3639, 4049, 2502, 331, 273, 389, 16351, 16082, 5940, 63, 16351, 461, 6362, 1589, 461, 15533, 203, 203, 3639, 1177, 780, 273, 331, 18, 1589, 461, 31, 203, 3639, 1267, 273, 331, 18, 2327, 31, 203, 3639, 7934, 2355, 273, 331, 18, 925, 2355, 31, 203, 3639, 4471, 273, 331, 18, 30810, 31, 203, 3639, 8215, 329, 273, 331, 18, 17413, 329, 31, 203, 3639, 813, 8602, 273, 331, 18, 957, 8602, 31, 203, 203, 3639, 327, 261, 203, 5411, 1177, 780, 16, 203, 5411, 1267, 16, 203, 5411, 7934, 2355, 16, 203, 5411, 4471, 16, 203, 5411, 8215, 329, 16, 203, 5411, 813, 8602, 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 ]
./full_match/1/0x6208410d391deb5A042632865833C56326C83CBa/sources/contracts/v4/platform/royalties/RoyaltiesState.sol
* @dev Get storage data from dedicated slot. This pattern avoids storage conflict during proxy upgrades and give more flexibility when creating extensions/
function _getRoyaltiesState() internal pure returns (RoyaltiesRegistryState storage state) { bytes32 storageSlot = keccak256("liveart.RoyalitiesState"); assembly { state.slot := storageSlot } }
17,184,791
[ 1, 967, 2502, 501, 628, 24328, 4694, 18, 1220, 1936, 24192, 2502, 7546, 4982, 2889, 28844, 471, 8492, 1898, 16600, 3628, 1347, 4979, 4418, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 54, 13372, 2390, 606, 1119, 1435, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 54, 13372, 2390, 606, 4243, 1119, 2502, 919, 13, 203, 565, 288, 203, 3639, 1731, 1578, 2502, 8764, 273, 417, 24410, 581, 5034, 2932, 16472, 485, 18, 54, 13372, 287, 1961, 1119, 8863, 203, 3639, 19931, 288, 203, 5411, 919, 18, 14194, 519, 2502, 8764, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/23295/0xd64a57003526ECe2e360b25A556963aB6E38407E/sources/contracts/HealDAOv1.sol
Remove the oldest diagnosis if the length exceeds the max length Remove the first element
function addDiagnosis(string memory diagnosisAbbreviation, uint16 numTimes, string memory locationList) public isAllowed { diagnoses.push(Diagnosis(diagnosisAbbreviation, numTimes, locationList)); emit DiagnosisAdded(address(this), diagnosisAbbreviation); while (diagnoses.length > MAX_DIAGNOSES_LENGTH) { for (uint i = 0; i < diagnoses.length - 1; i++) { diagnoses[i] = diagnoses[i + 1]; } diagnoses.pop(); } }
7,103,099
[ 1, 3288, 326, 17067, 6643, 18050, 291, 309, 326, 769, 14399, 326, 943, 769, 3581, 326, 1122, 930, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 527, 14058, 18050, 291, 12, 1080, 3778, 6643, 18050, 291, 5895, 15500, 16, 2254, 2313, 818, 10694, 16, 533, 3778, 2117, 682, 13, 1071, 21956, 288, 203, 3639, 6643, 18050, 281, 18, 6206, 12, 14058, 18050, 291, 12, 12264, 18050, 291, 5895, 15500, 16, 818, 10694, 16, 2117, 682, 10019, 203, 3639, 3626, 14539, 18050, 291, 8602, 12, 2867, 12, 2211, 3631, 6643, 18050, 291, 5895, 15500, 1769, 203, 203, 3639, 1323, 261, 12264, 18050, 281, 18, 2469, 405, 4552, 67, 2565, 1781, 3417, 1090, 55, 67, 7096, 13, 288, 203, 5411, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 6643, 18050, 281, 18, 2469, 300, 404, 31, 277, 27245, 288, 203, 7734, 6643, 18050, 281, 63, 77, 65, 273, 6643, 18050, 281, 63, 77, 397, 404, 15533, 203, 5411, 289, 203, 5411, 6643, 18050, 281, 18, 5120, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.7.0 <0.8.0; // OpenZeppelin Upgradeability contracts modified by Sam Porter. Proxy for Nameless Protocol contracts // You can find original set of contracts here: https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/proxy // Had to pack OpenZeppelin upgradeability contracts in one single contract for readability. It's basically the same OpenZeppelin functions // but in one contract with some differences: // 1. DEADLINE is a block after which it becomes impossible to upgrade the contract. Defined in constructor and here it's ~2 years. // Maybe not even required for most contracts, but I kept it in case if something happens to developers. // 2. PROPOSE_BLOCK defines how often the contract can be upgraded. Defined in _setNextLogic() function and the interval here is set // to 172800 blocks ~1 month. // 3. Admin rights are burnable. Rather not do that without deadline // 4. prolongLock() allows to add to PROPOSE_BLOCK. Basically allows to prolong lock. For example if there no upgrades planned soon, // then this function could be called to set next upgrade being possible only in a year, so investors won't need to monitor the code too closely // all the time. Could prolong to maximum solidity number so the deadline might not be needed // 5. logic contract is not being set suddenly. it's being stored in NEXT_LOGIC_SLOT for a month and only after that it can be set as LOGIC_SLOT. // Users have time to decide on if the deployer or the governance is malicious and exit safely. // 6. constructor does not require arguments // It fixes "upgradeability bug" I believe. Also I sincerely believe that upgradeability is not about fixing bugs, but about upgradeability, // so yeah, proposed logic has to be clean. // In my heart it exists as eip-1984 but it's too late for that number. https://ethereum-magicians.org/t/trust-minimized-proxy/5742/2 contract GovernanceTrustMinimizedProxy{ event Upgraded(address indexed toLogic); event AdminChanged(address indexed previousAdmin, address indexed newAdmin); event NextLogicDefined(address indexed nextLogic, uint timeOfArrivalBlock); event UpgradesRestrictedUntil(uint block); event NextLogicCanceled(address indexed toLogic); bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; bytes32 internal constant LOGIC_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; bytes32 internal constant NEXT_LOGIC_SLOT = 0xb182d207b11df9fb38eec1e3fe4966cf344774ba58fb0e9d88ea35ad46f3601e; bytes32 internal constant NEXT_LOGIC_BLOCK_SLOT = 0x96de003e85302815fe026bddb9630a50a1d4dc51c5c355def172204c3fd1c733; bytes32 internal constant PROPOSE_BLOCK_SLOT = 0xbc9d35b69e82e85049be70f91154051f5e20e574471195334bde02d1a9974c90; // bytes32 internal constant DEADLINE_SLOT = 0xb124b82d2ac46ebdb08de751ebc55102cc7325d133e09c1f1c25014e20b979ad; constructor() payable { // require(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1) && LOGIC_SLOT==bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) // this require is simply against human error, can be removed if you know what you are doing // && NEXT_LOGIC_SLOT == bytes32(uint256(keccak256('eip1984.proxy.nextLogic')) - 1) && NEXT_LOGIC_BLOCK_SLOT == bytes32(uint256(keccak256('eip1984.proxy.nextLogicBlock')) - 1) // && PROPOSE_BLOCK_SLOT == bytes32(uint256(keccak256('eip1984.proxy.proposeBlock')) - 1)/* && DEADLINE_SLOT == bytes32(uint256(keccak256('eip1984.proxy.deadline')) - 1)*/); _setAdmin(msg.sender); // uint deadline = block.number + 4204800; // ~2 years as default // assembly {sstore(DEADLINE_SLOT,deadline)} } modifier ifAdmin() {if (msg.sender == _admin()) {_;} else {_fallback();}} function _logic() internal view returns (address logic) {assembly { logic := sload(LOGIC_SLOT) }} function _proposeBlock() internal view returns (uint bl) {assembly { bl := sload(PROPOSE_BLOCK_SLOT) }} function _nextLogicBlock() internal view returns (uint bl) {assembly { bl := sload(NEXT_LOGIC_BLOCK_SLOT) }} // function _deadline() internal view returns (uint bl) {assembly { bl := sload(DEADLINE_SLOT) }} function _admin() internal view returns (address adm) {assembly { adm := sload(ADMIN_SLOT) }} function _isContract(address account) internal view returns (bool b) {uint256 size;assembly {size := extcodesize(account)}return size > 0;} function _setAdmin(address newAdm) internal {assembly {sstore(ADMIN_SLOT, newAdm)}} function changeAdmin(address newAdm) external ifAdmin {emit AdminChanged(_admin(), newAdm);_setAdmin(newAdm);} function upgrade() external ifAdmin {require(block.number>=_nextLogicBlock());address logic;assembly {logic := sload(NEXT_LOGIC_SLOT) sstore(LOGIC_SLOT,logic)}emit Upgraded(logic);} fallback () external payable {_fallback();} receive () external payable {_fallback();} function _fallback() internal {require(msg.sender != _admin());_delegate(_logic());} function cancelUpgrade() external ifAdmin {address logic; assembly {logic := sload(LOGIC_SLOT)sstore(NEXT_LOGIC_SLOT, logic)}emit NextLogicCanceled(logic);} function proposeTo(address newLogic) external ifAdmin { if (_logic() == address(0)) {_updateBlockSlots();assembly {sstore(LOGIC_SLOT,newLogic)}emit Upgraded(newLogic);} else{_setNextLogic(newLogic);} } function prolongLock(uint block_) external ifAdmin { uint pb; assembly {pb := sload(PROPOSE_BLOCK_SLOT) pb := add(pb,block_) sstore(PROPOSE_BLOCK_SLOT,pb)}emit UpgradesRestrictedUntil(pb); } function proposeToAndCall(address newLogic, bytes calldata data) payable external ifAdmin { if (_logic() == address(0)) {_updateBlockSlots();assembly {sstore(LOGIC_SLOT,newLogic)}}else{_setNextLogic(newLogic);} (bool success,) = newLogic.delegatecall(data);require(success); } function _setNextLogic(address nextLogic) internal { require(block.number >= _proposeBlock() && _isContract(nextLogic)); _updateBlockSlots(); assembly { sstore(NEXT_LOGIC_SLOT, nextLogic)} emit NextLogicDefined(nextLogic,block.number + 172800); } function _updateBlockSlots() internal { uint proposeBlock = block.number + 172800;uint nextLogicBlock = block.number + 172800; assembly {sstore(NEXT_LOGIC_BLOCK_SLOT,nextLogicBlock) sstore(PROPOSE_BLOCK_SLOT,proposeBlock)} } function _delegate(address logic_) internal { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), logic_, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } }
bytes32 internal constant DEADLINE_SLOT = 0xb124b82d2ac46ebdb08de751ebc55102cc7325d133e09c1f1c25014e20b979ad;
contract GovernanceTrustMinimizedProxy{ event Upgraded(address indexed toLogic); event AdminChanged(address indexed previousAdmin, address indexed newAdmin); event NextLogicDefined(address indexed nextLogic, uint timeOfArrivalBlock); event UpgradesRestrictedUntil(uint block); event NextLogicCanceled(address indexed toLogic); bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; bytes32 internal constant LOGIC_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; bytes32 internal constant NEXT_LOGIC_SLOT = 0xb182d207b11df9fb38eec1e3fe4966cf344774ba58fb0e9d88ea35ad46f3601e; bytes32 internal constant NEXT_LOGIC_BLOCK_SLOT = 0x96de003e85302815fe026bddb9630a50a1d4dc51c5c355def172204c3fd1c733; bytes32 internal constant PROPOSE_BLOCK_SLOT = 0xbc9d35b69e82e85049be70f91154051f5e20e574471195334bde02d1a9974c90; constructor() payable { _setAdmin(msg.sender); } modifier ifAdmin() {if (msg.sender == _admin()) {_;} else {_fallback();}} function _logic() internal view returns (address logic) {assembly { logic := sload(LOGIC_SLOT) }} function _proposeBlock() internal view returns (uint bl) {assembly { bl := sload(PROPOSE_BLOCK_SLOT) }} function _nextLogicBlock() internal view returns (uint bl) {assembly { bl := sload(NEXT_LOGIC_BLOCK_SLOT) }} function _admin() internal view returns (address adm) {assembly { adm := sload(ADMIN_SLOT) }} function _isContract(address account) internal view returns (bool b) {uint256 size;assembly {size := extcodesize(account)}return size > 0;} function _setAdmin(address newAdm) internal {assembly {sstore(ADMIN_SLOT, newAdm)}} function changeAdmin(address newAdm) external ifAdmin {emit AdminChanged(_admin(), newAdm);_setAdmin(newAdm);} function upgrade() external ifAdmin {require(block.number>=_nextLogicBlock());address logic;assembly {logic := sload(NEXT_LOGIC_SLOT) sstore(LOGIC_SLOT,logic)}emit Upgraded(logic);} fallback () external payable {_fallback();} receive () external payable {_fallback();} function _fallback() internal {require(msg.sender != _admin());_delegate(_logic());} function cancelUpgrade() external ifAdmin {address logic; assembly {logic := sload(LOGIC_SLOT)sstore(NEXT_LOGIC_SLOT, logic)}emit NextLogicCanceled(logic);} function proposeTo(address newLogic) external ifAdmin { } if (_logic() == address(0)) {_updateBlockSlots();assembly {sstore(LOGIC_SLOT,newLogic)}emit Upgraded(newLogic);} else{_setNextLogic(newLogic);} function prolongLock(uint block_) external ifAdmin { } uint pb; assembly {pb := sload(PROPOSE_BLOCK_SLOT) pb := add(pb,block_) sstore(PROPOSE_BLOCK_SLOT,pb)}emit UpgradesRestrictedUntil(pb); function proposeToAndCall(address newLogic, bytes calldata data) payable external ifAdmin { (bool success,) = newLogic.delegatecall(data);require(success); } if (_logic() == address(0)) {_updateBlockSlots();assembly {sstore(LOGIC_SLOT,newLogic)}}else{_setNextLogic(newLogic);} function _setNextLogic(address nextLogic) internal { require(block.number >= _proposeBlock() && _isContract(nextLogic)); _updateBlockSlots(); emit NextLogicDefined(nextLogic,block.number + 172800); } assembly { sstore(NEXT_LOGIC_SLOT, nextLogic)} function _updateBlockSlots() internal { } uint proposeBlock = block.number + 172800;uint nextLogicBlock = block.number + 172800; assembly {sstore(NEXT_LOGIC_BLOCK_SLOT,nextLogicBlock) sstore(PROPOSE_BLOCK_SLOT,proposeBlock)} function _delegate(address logic_) internal { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), logic_, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result } } function _delegate(address logic_) internal { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), logic_, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result } } case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } }
206,119
[ 1, 3890, 1578, 2713, 5381, 2030, 1880, 5997, 67, 55, 1502, 56, 273, 374, 6114, 24734, 70, 11149, 72, 22, 1077, 8749, 24008, 1966, 6840, 323, 5877, 21, 73, 13459, 2539, 20481, 952, 27, 1578, 25, 72, 28615, 73, 5908, 71, 21, 74, 21, 71, 2947, 1611, 24, 73, 3462, 70, 29, 7235, 361, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 611, 1643, 82, 1359, 14146, 2930, 381, 1235, 3886, 95, 203, 202, 2575, 1948, 19305, 12, 2867, 8808, 358, 20556, 1769, 203, 202, 2575, 7807, 5033, 12, 2867, 8808, 2416, 4446, 16, 1758, 8808, 394, 4446, 1769, 203, 202, 2575, 4804, 20556, 8116, 12, 2867, 8808, 1024, 20556, 16, 2254, 813, 951, 5715, 5162, 1768, 1769, 203, 202, 2575, 1948, 13088, 18784, 9716, 12, 11890, 1203, 1769, 203, 202, 2575, 4804, 20556, 23163, 12, 2867, 8808, 358, 20556, 1769, 203, 202, 203, 202, 3890, 1578, 2713, 5381, 25969, 67, 55, 1502, 56, 273, 374, 6114, 8643, 2138, 6669, 5193, 69, 4313, 28, 70, 23, 31331, 8906, 3437, 70, 29, 74, 28, 69, 26, 24171, 73, 3247, 23, 73, 4449, 70, 26, 73, 28, 1340, 2499, 8285, 72, 26, 69, 27, 4033, 28, 3361, 70, 25, 72, 26, 23494, 31, 203, 202, 3890, 1578, 2713, 5381, 2018, 2871, 67, 55, 1502, 56, 273, 374, 92, 29751, 6675, 24, 69, 3437, 12124, 21, 69, 1578, 2163, 6028, 27, 71, 11149, 5193, 9975, 1966, 10689, 72, 5353, 23, 73, 3462, 6669, 952, 6418, 4763, 69, 29, 3462, 69, 23, 5353, 3361, 25, 72, 7414, 22, 9897, 71, 31, 203, 202, 3890, 1578, 2713, 5381, 19252, 67, 4842, 2871, 67, 55, 1502, 56, 273, 374, 6114, 28246, 72, 3462, 27, 70, 2499, 2180, 29, 19192, 7414, 73, 557, 21, 73, 23, 3030, 7616, 6028, 8522, 5026, 24, 4700, 24, 12124, 8204, 19192, 20, 73, 29, 72, 5482, 24852, 4763, 361, 8749, 74, 5718, 1611, 73, 31, 203, 2 ]
./full_match/5/0x8bE53066AEB6E753f43e38B55F2d39c690228505/sources/src/BasedPowells.sol
* @notice Returns the metadata URI for an NFT. @dev See `BatchMintMetadata` for handling of metadata in this contract. @param _tokenId The tokenId of an NFT./
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { (uint256 batchId,) = _getBatchId(_tokenId); string memory batchUri = _getBaseURI(_tokenId); if (isEncryptedBatch(batchId)) { return string(abi.encodePacked(batchUri, "0")); return string(abi.encodePacked(batchUri, _tokenId.toString())); } } Overriden lazy minting logic
1,886,567
[ 1, 1356, 326, 1982, 3699, 364, 392, 423, 4464, 18, 2868, 2164, 1375, 4497, 49, 474, 2277, 68, 364, 5057, 434, 1982, 316, 333, 6835, 18, 282, 389, 2316, 548, 1021, 1147, 548, 434, 392, 423, 4464, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 261, 11890, 5034, 2581, 548, 16, 13, 273, 389, 588, 4497, 548, 24899, 2316, 548, 1769, 203, 3639, 533, 3778, 2581, 3006, 273, 389, 588, 2171, 3098, 24899, 2316, 548, 1769, 203, 203, 3639, 309, 261, 291, 14678, 4497, 12, 5303, 548, 3719, 288, 203, 5411, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 5303, 3006, 16, 315, 20, 7923, 1769, 203, 5411, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 5303, 3006, 16, 389, 2316, 548, 18, 10492, 1435, 10019, 203, 3639, 289, 203, 565, 289, 203, 203, 10792, 531, 1107, 17951, 7962, 312, 474, 310, 4058, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x44C1bCE3f284e9a672fa4ba6f5b02E8651da88a0/sources/MinterRole.sol
* @title Roles @dev Library for managing addresses assigned to a Role./
library Roles { pragma solidity 0.8.13; struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } }
9,138,017
[ 1, 6898, 225, 18694, 364, 30632, 6138, 6958, 358, 279, 6204, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 19576, 288, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3437, 31, 203, 565, 1958, 6204, 288, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 28802, 31, 203, 565, 289, 203, 203, 565, 445, 527, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 5, 5332, 12, 4615, 16, 2236, 10019, 203, 203, 3639, 2478, 18, 29400, 264, 63, 4631, 65, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1206, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 5332, 12, 4615, 16, 2236, 10019, 203, 203, 3639, 2478, 18, 29400, 264, 63, 4631, 65, 273, 629, 31, 203, 565, 289, 203, 203, 565, 445, 711, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 10019, 203, 3639, 327, 2478, 18, 29400, 264, 63, 4631, 15533, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; import "../L1Tokens/Asset721.sol"; contract ChildAsset721 is Asset721 { address public childChainManagerProxy; // limit batching of tokens due to gas limit restrictions uint256 public constant BATCH_LIMIT = 20; event WithdrawnBatch(address indexed user, uint256[] tokenIds); function init(address _childChainManagerProxy) external { childChainManagerProxy = _childChainManagerProxy; super.initialize(); } /** * @notice called when tokens are deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required tokens for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded ids array */ function deposit(address user, bytes calldata depositData) external { require( msg.sender == childChainManagerProxy, "Asset: Unauthorized Call" ); // deposit single if (depositData.length == 32) { uint256 tokenId = abi.decode(depositData, (uint256)); _mint(user, tokenId); // deposit batch } else { uint256[] memory tokenIds = abi.decode(depositData, (uint256[])); uint256 length = tokenIds.length; for (uint256 i; i < length; i++) { _mint(user, tokenIds[i]); } } } /** * @notice called when user wants to withdraw single token back to root chain * @dev Should burn user's token. This transaction will be verified when exiting on root chain * @param id id to withdraw */ function withdrawSingle(uint256 id) external { _burn(id); } /** * @notice called when user wants to batch withdraw tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param tokenIds ids to withdraw */ function withdrawBatch(uint256[] calldata tokenIds) external { uint256 length = tokenIds.length; require(length <= BATCH_LIMIT, "ChildERC721: EXCEEDS_BATCH_LIMIT"); for (uint256 i; i < length; i++) { uint256 tokenId = tokenIds[i]; require( _msgSender() == ownerOf(tokenId), string( abi.encodePacked( "ChildERC721: INVALID_TOKEN_OWNER ", tokenId ) ) ); _burn(tokenId); } emit WithdrawnBatch(_msgSender(), tokenIds); } function updateChildChainManager(address newChildChainManagerProxy) external onlyAdmin { require(newChildChainManagerProxy != address(0), "Asset: Bad address"); childChainManagerProxy = newChildChainManagerProxy; } }
* @notice called when user wants to batch withdraw tokens back to root chain @dev Should burn user's tokens. This transaction will be verified when exiting on root chain @param tokenIds ids to withdraw/
function withdrawBatch(uint256[] calldata tokenIds) external { uint256 length = tokenIds.length; require(length <= BATCH_LIMIT, "ChildERC721: EXCEEDS_BATCH_LIMIT"); for (uint256 i; i < length; i++) { uint256 tokenId = tokenIds[i]; require( _msgSender() == ownerOf(tokenId), string( abi.encodePacked( "ChildERC721: INVALID_TOKEN_OWNER ", tokenId ) ) ); _burn(tokenId); } emit WithdrawnBatch(_msgSender(), tokenIds); }
1,807,076
[ 1, 11777, 1347, 729, 14805, 358, 2581, 598, 9446, 2430, 1473, 358, 1365, 2687, 225, 9363, 18305, 729, 1807, 2430, 18, 1220, 2492, 903, 506, 13808, 1347, 15702, 603, 1365, 2687, 225, 1147, 2673, 3258, 358, 598, 9446, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 4497, 12, 11890, 5034, 8526, 745, 892, 1147, 2673, 13, 3903, 288, 203, 3639, 2254, 5034, 769, 273, 1147, 2673, 18, 2469, 31, 203, 3639, 2583, 12, 2469, 1648, 605, 5858, 67, 8283, 16, 315, 1763, 654, 39, 27, 5340, 30, 5675, 1441, 2056, 55, 67, 25147, 67, 8283, 8863, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 769, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 1147, 548, 273, 1147, 2673, 63, 77, 15533, 203, 5411, 2583, 12, 203, 7734, 389, 3576, 12021, 1435, 422, 3410, 951, 12, 2316, 548, 3631, 203, 7734, 533, 12, 203, 10792, 24126, 18, 3015, 4420, 329, 12, 203, 13491, 315, 1763, 654, 39, 27, 5340, 30, 10071, 67, 8412, 67, 29602, 3104, 203, 13491, 1147, 548, 203, 10792, 262, 203, 7734, 262, 203, 5411, 11272, 203, 5411, 389, 70, 321, 12, 2316, 548, 1769, 203, 3639, 289, 203, 3639, 3626, 3423, 9446, 82, 4497, 24899, 3576, 12021, 9334, 1147, 2673, 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 ]
pragma solidity ^0.4.18; /** * @title Smart City Token http://www.smartcitycoin.io * @dev ERC20 standard compliant / https://github.com/ethereum/EIPs/issues/20 / * @dev Amount not sold during Crowdsale can be burned by anyone */ contract SmartCityToken { using SafeMath for uint256; address public owner; // address of Token Owner address public crowdsale; // address of Crowdsale contract string constant public standard = "ERC20"; // token standard string constant public name = "Smart City"; // token name string constant public symbol = "CITY"; // token symbol uint256 constant public decimals = 5; // 1 CITY = 100000 tokens uint256 public totalSupply = 252862966307692; // total token provision; 1 CITY = 0,0001 ETH uint256 constant public amountForSale = 164360928100000; // amount that might be sold during ICO - 65% of total token supply; 164361 ETH equivalent uint256 constant public amountReserved = 88502038207692; // amount reserved for founders / loyalty / bounties / etc. - 35% of total token supply uint256 constant public amountLocked = 61951426745384; // the amount of tokens Owner cannot spend within first 2 years after Crowdsale - 70% of the reserved amount uint256 public startTime; // Crowdsale end time: from this time on transfer and transferFrom functions are available to anyone except of token Owner uint256 public unlockOwnerDate; // from this time on transfer and transferFrom functions are available to token Owner mapping(address => uint256) public balances; // balances array mapping(address => mapping(address => uint256)) public allowances; // allowances array bool public burned; // indicates whether excess tokens have already been burned event Transfer(address indexed from, address indexed to, uint256 value); // Transfer event event Approval(address indexed _owner, address indexed spender, uint256 value); // Approval event event Burned(uint256 amount); // Burned event modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } /** * @dev Contract initialization * @param _ownerAddress address Token owner address * @param _startTime uint256 Crowdsale end time * */ function SmartCityToken(address _ownerAddress, uint256 _startTime) public { owner = _ownerAddress; // token Owner startTime = _startTime; // token Start Time unlockOwnerDate = startTime + 2 years; balances[owner] = totalSupply; // all tokens are initially allocated to token owner } /** * @dev Transfers token for a specified address * @param _to address The address to transfer to * @param _value uint256 The amount to be transferred */ function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns(bool success) { require(now >= startTime); require(_to != address(0)); require(_value <= balances[msg.sender]); if (msg.sender == owner && now < unlockOwnerDate) require(balances[msg.sender].sub(_value) >= amountLocked); balances[msg.sender] = balances[msg.sender].sub(_value); // subtract requested amount from the sender address balances[_to] = balances[_to].add(_value); // send requested amount to the target address Transfer(msg.sender, _to, _value); // trigger Transfer event return true; } /** * @dev Transfers 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) onlyPayloadSize(3 * 32) public returns(bool success) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowances[_from][msg.sender]); if (now < startTime) require(_from == owner); if (_from == owner && now < unlockOwnerDate) require(balances[_from].sub(_value) >= amountLocked); uint256 _allowance = allowances[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); // subtract requested amount from the sender address balances[_to] = balances[_to].add(_value); // send requested amount to the target address allowances[_from][msg.sender] = _allowance.sub(_value); // reduce sender allowance by transferred amount Transfer(_from, _to, _value); // trigger Transfer event return true; } /** * @dev Gets the balance of the specified address. * @param _addr address The address to query the balance of. * @return uint256 representing the amount owned by the passed address. */ function balanceOf(address _addr) public view returns (uint256 balance) { return balances[_addr]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender address The address which will spend the funds * @param _value uint256 The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) onlyPayloadSize(2 * 32) public returns(bool success) { return _approve(_spender, _value); } /** * @dev Workaround for vulnerability described here: https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM */ function _approve(address _spender, uint256 _value) internal returns(bool success) { require((_value == 0) || (allowances[msg.sender][_spender] == 0)); allowances[msg.sender][_spender] = _value; // Set spender allowance Approval(msg.sender, _spender, _value); // Trigger Approval event return true; } /** * @dev Burns all the tokens which has not been sold during ICO */ function burn() public { if (!burned && now > startTime) { uint256 diff = balances[owner].sub(amountReserved); // Get the amount of unsold tokens balances[owner] = amountReserved; totalSupply = totalSupply.sub(diff); // Reduce total provision number burned = true; Burned(diff); // Trigger Burned event } } /** * @dev Sets Corwdsale contract address & allowance * @param _crowdsaleAddress address The address of the Crowdsale contract */ function setCrowdsale(address _crowdsaleAddress) public { require(msg.sender == owner); require(crowdsale == address(0)); crowdsale = _crowdsaleAddress; assert(_approve(crowdsale, amountForSale)); } /** * @dev Crowdsale contract is allowed to shift token start time to earlier than initially defined date * @param _newStartTime uint256 New Start Date */ function setTokenStart(uint256 _newStartTime) public { require(msg.sender == crowdsale && _newStartTime < startTime); startTime = _newStartTime; } } /** * @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) { uint256 c = a / b; return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * CITY token by www.SmartCityCoin.io * * .ossssss: `+sssss` * ` +ssssss+` `.://++++++//:.` .osssss+ * /sssssssssssssssssssssssss+ssssso` * -sssssssssssssssssssssssssssss+` * .+sssssssss+:--....--:/ossssssss+. * `/ssssssssssso` .sssssssssss/` * .ossssss+sssssss- :sssss+:ossssso. * `ossssso. .ossssss: `/sssss/ `/ssssss. * ossssso` `+ssssss+` .osssss: /ssssss` * :ssssss` /sssssso:ssssso. +o+/:-` * osssss+ -sssssssssss+` * ssssss: .ossssssss/ * osssss/ `+ssssss- * /ssssso :ssssss * .ssssss- :ssssss * :ssssss- :ssssss ` * /ssssss/` :ssssss `/s+:` * :sssssso:. :ssssss ./ssssss+` * .+ssssssso/-.`:ssssss``.-/osssssss+. * .+ssssssssssssssssssssssssssss+- * `:+ssssssssssssssssssssss+:` * `.:+osssssssssssso+:.` * `/ssssss.` * :ssssss */
address of Token Owner
address public owner;
1,043,798
[ 1, 2867, 434, 3155, 16837, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1758, 1071, 3410, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x8A04921c61F0f9850A02957530BdbA4aB50312D2/sources/ABSTRASCII.sol
* @notice Allow for public minting of tokens/
function mint(uint256 numTokens) external payable nonReentrant originalUser { require(isPublicSaleActive, "PUBLIC_SALE_IS_NOT_ACTIVE"); require( numTokens <= publicMintsAllowedPerTransaction, "MAX_MINTS_PER_TX_EXCEEDED" ); require( _numberMinted(msg.sender) + numTokens <= publicMintsAllowedPerAddress, "MAX_MINTS_EXCEEDED" ); require(totalSupply() + numTokens <= MAX_SUPPLY, "MAX_SUPPLY_EXCEEDED"); require(msg.value == publicPrice * numTokens, "PAYMENT_INCORRECT"); _safeMint(msg.sender, numTokens); if (totalSupply() >= MAX_SUPPLY) { isPublicSaleActive = false; } }
3,044,750
[ 1, 7009, 364, 1071, 312, 474, 310, 434, 2430, 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, 312, 474, 12, 11890, 5034, 818, 5157, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 2282, 1299, 203, 565, 288, 203, 3639, 2583, 12, 291, 4782, 30746, 3896, 16, 315, 14939, 67, 5233, 900, 67, 5127, 67, 4400, 67, 13301, 8863, 203, 203, 3639, 2583, 12, 203, 5411, 818, 5157, 1648, 1071, 49, 28142, 5042, 2173, 3342, 16, 203, 5411, 315, 6694, 67, 49, 3217, 55, 67, 3194, 67, 16556, 67, 2294, 26031, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 389, 2696, 49, 474, 329, 12, 3576, 18, 15330, 13, 397, 818, 5157, 1648, 203, 7734, 1071, 49, 28142, 5042, 2173, 1887, 16, 203, 5411, 315, 6694, 67, 49, 3217, 55, 67, 2294, 26031, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 397, 818, 5157, 1648, 4552, 67, 13272, 23893, 16, 315, 6694, 67, 13272, 23893, 67, 2294, 26031, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 1071, 5147, 380, 818, 5157, 16, 315, 16436, 67, 706, 9428, 4512, 8863, 203, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 818, 5157, 1769, 203, 203, 3639, 309, 261, 4963, 3088, 1283, 1435, 1545, 4552, 67, 13272, 23893, 13, 288, 203, 5411, 19620, 30746, 3896, 273, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.8; library BobbySafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BobbyERC20Base { address public ceoAddress; address public cfoAddress; //是否暂停智能合约的运行 bool public paused = false; constructor(address cfoAddr) public { ceoAddress = msg.sender; cfoAddress = cfoAddr; } modifier onlyCEO() { require(msg.sender == ceoAddress); _; } function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier allButCFO() { require(msg.sender != cfoAddress); _; } function setCFO(address _newCFO) public onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() external onlyCEO whenNotPaused { paused = true; } function unpause() public onlyCEO whenPaused { paused = false; } } contract ERC20Interface { //ERC20指定接口 event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); //extend event event Grant(address indexed src, address indexed dst, uint wad); //发放代币,有解禁期 event Unlock(address indexed user, uint wad); //解禁代币 function name() public view returns (string n); function symbol() public view returns (string s); function decimals() public view returns (uint8 d); function totalSupply() public view returns (uint256 t); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); } //Erc智能合约 contract ERC20 is ERC20Interface, BobbyERC20Base { using BobbySafeMath for uint256; uint private _Thousand = 1000; uint private _Billion = _Thousand * _Thousand * _Thousand; //代币基本信息 string private _name = "BOBBYTest"; //代币名称 string private _symbol = "BOBBYTest"; //代币标识 uint8 private _decimals = 9; //小数点后位数 uint256 private _totalSupply = 10 * _Billion * (10 ** uint256(_decimals)); //解封用户代币结构 struct UserToken { uint index; //放在数组中的下标 address addr; //用户账号 uint256 tokens; //通证数量 uint256 unlockUnit; // 每次解锁数量 uint256 unlockPeriod; // 解锁时间间隔 uint256 unlockLeft; // 未解锁通证数量 uint256 unlockLastTime; // 上次解锁时间 } mapping(address=>UserToken) private _balancesMap; //用户可用代币映射 address[] private _balancesArray; //用户可用代币数组,from 1 uint32 private actionTransfer = 0; uint32 private actionGrant = 1; uint32 private actionUnlock = 2; struct LogEntry { uint256 time; uint32 action; // 0 转账 1 发放 2 解锁 address from; address to; uint256 v1; uint256 v2; uint256 v3; } LogEntry[] private _logs; //构造方法,将代币的初始总供给都分配给合约的部署账户。合约的构造方法只在合约部署时执行一次 constructor(address cfoAddr) BobbyERC20Base(cfoAddr) public { //placeholder _balancesArray.push(address(0)); //此处需要注意,请使用CEO的地址,因为初始化后,将会使用这个地址作为CEO地址 //注意,一定要使用memory类型,否则,后面的赋值会影响其它成员变量 UserToken memory userCFO; userCFO.index = _balancesArray.length; userCFO.addr = cfoAddr; userCFO.tokens = _totalSupply; userCFO.unlockUnit = 0; userCFO.unlockPeriod = 0; userCFO.unlockLeft = 0; userCFO.unlockLastTime = 0; _balancesArray.push(cfoAddr); _balancesMap[cfoAddr] = userCFO; } //返回合约名称。view关键子表示函数只查询状态变量,而不写入 function name() public view returns (string n){ n = _name; } //返回合约标识符 function symbol() public view returns (string s){ s = _symbol; } //返回合约小数位 function decimals() public view returns (uint8 d){ d = _decimals; } //返回合约总供给额 function totalSupply() public view returns (uint256 t){ t = _totalSupply; } //查询账户_owner的账户余额 function balanceOf(address _owner) public view returns (uint256 balance){ UserToken storage user = _balancesMap[_owner]; balance = user.tokens.add(user.unlockLeft); } //从代币合约的调用者地址上转移_value的数量token到的地址_to,并且必须触发Transfer事件 function transfer(address _to, uint256 _value) public returns (bool success){ require(!paused); require(msg.sender != cfoAddress); require(msg.sender != _to); //先判断是否有可以解禁 if(_balancesMap[msg.sender].unlockLeft > 0){ UserToken storage sender = _balancesMap[msg.sender]; uint256 diff = now.sub(sender.unlockLastTime); uint256 round = diff.div(sender.unlockPeriod); if(round > 0) { uint256 unlocked = sender.unlockUnit.mul(round); if (unlocked > sender.unlockLeft) { unlocked = sender.unlockLeft; } sender.unlockLeft = sender.unlockLeft.sub(unlocked); sender.tokens = sender.tokens.add(unlocked); sender.unlockLastTime = sender.unlockLastTime.add(sender.unlockPeriod.mul(round)); emit Unlock(msg.sender, unlocked); log(actionUnlock, msg.sender, 0, unlocked, 0, 0); } } require(_balancesMap[msg.sender].tokens >= _value); _balancesMap[msg.sender].tokens = _balancesMap[msg.sender].tokens.sub(_value); uint index = _balancesMap[_to].index; if(index == 0){ UserToken memory user; user.index = _balancesArray.length; user.addr = _to; user.tokens = _value; user.unlockUnit = 0; user.unlockPeriod = 0; user.unlockLeft = 0; user.unlockLastTime = 0; _balancesMap[_to] = user; _balancesArray.push(_to); } else{ _balancesMap[_to].tokens = _balancesMap[_to].tokens.add(_value); } emit Transfer(msg.sender, _to, _value); log(actionTransfer, msg.sender, _to, _value, 0, 0); success = true; } function transferFrom(address, address, uint256) public returns (bool success){ require(!paused); success = true; } function approve(address, uint256) public returns (bool success){ require(!paused); success = true; } function allowance(address, address) public view returns (uint256 remaining){ require(!paused); remaining = 0; } function grant(address _to, uint256 _value, uint256 _duration, uint256 _periods) public returns (bool success){ require(msg.sender != _to); require(_balancesMap[msg.sender].tokens >= _value); require(_balancesMap[_to].unlockLastTime == 0); _balancesMap[msg.sender].tokens = _balancesMap[msg.sender].tokens.sub(_value); if(_balancesMap[_to].index == 0){ UserToken memory user; user.index = _balancesArray.length; user.addr = _to; user.tokens = 0; user.unlockUnit = _value.div(_periods); // user.unlockPeriod = _duration.mul(30).mul(1 days).div(_periods); user.unlockPeriod = _duration.mul(1 days).div(_periods); //for test user.unlockLeft = _value; user.unlockLastTime = now; _balancesMap[_to] = user; _balancesArray.push(_to); } else{ _balancesMap[_to].unlockUnit = _value.div(_periods); // _balancesMap[_to].unlockPeriod = _duration.mul(30).mul(1 days).div(_periods); _balancesMap[_to].unlockPeriod = _duration.mul(1 days).div(_periods); //for test _balancesMap[_to].unlockLeft = _value; _balancesMap[_to].unlockLastTime = now; } emit Grant(msg.sender, _to, _value); log(actionGrant, msg.sender, _to, _value, _duration, _periods); success = true; } function getBalanceAddr(uint256 _index) public view returns(address addr){ require(_index < _balancesArray.length); require(_index >= 0); addr = _balancesArray[_index]; } function getBalanceSize() public view returns(uint256 size){ size = _balancesArray.length; } function getLockInfo(address addr) public view returns (uint256 unlocked, uint256 unit, uint256 period, uint256 last) { UserToken storage user = _balancesMap[addr]; unlocked = user.unlockLeft; unit = user.unlockUnit; period = user.unlockPeriod; last = user.unlockLastTime; } function log(uint32 action, address from, address to, uint256 _v1, uint256 _v2, uint256 _v3) private { LogEntry memory entry; entry.action = action; entry.time = now; entry.from = from; entry.to = to; entry.v1 = _v1; entry.v2 = _v2; entry.v3 = _v3; _logs.push(entry); } function getLogSize() public view returns(uint256 size){ size = _logs.length; } function getLog(uint256 _index) public view returns(uint time, uint32 action, address from, address to, uint256 _v1, uint256 _v2, uint256 _v3){ require(_index < _logs.length); require(_index >= 0); LogEntry storage entry = _logs[_index]; action = entry.action; time = entry.time; from = entry.from; to = entry.to; _v1 = entry.v1; _v2 = entry.v2; _v3 = entry.v3; } }
构造方法,将代币的初始总供给都分配给合约的部署账户。合约的构造方法只在合约部署时执行一次placeholder此处需要注意,请使用CEO的地址,因为初始化后,将会使用这个地址作为CEO地址注意,一定要使用memory类型,否则,后面的赋值会影响其它成员变量
constructor(address cfoAddr) BobbyERC20Base(cfoAddr) public { _balancesArray.push(address(0)); UserToken memory userCFO; userCFO.index = _balancesArray.length; userCFO.addr = cfoAddr; userCFO.tokens = _totalSupply; userCFO.unlockUnit = 0; userCFO.unlockPeriod = 0; userCFO.unlockLeft = 0; userCFO.unlockLastTime = 0; _balancesArray.push(cfoAddr); _balancesMap[cfoAddr] = userCFO; }
14,299
[ 1, 167, 257, 231, 170, 227, 259, 167, 249, 122, 167, 116, 248, 176, 125, 239, 166, 113, 233, 165, 124, 101, 166, 121, 228, 168, 253, 231, 166, 235, 256, 166, 105, 238, 167, 227, 124, 165, 127, 254, 168, 124, 252, 170, 230, 126, 166, 235, 233, 170, 232, 240, 168, 124, 252, 166, 243, 235, 168, 123, 104, 168, 253, 231, 170, 230, 106, 168, 126, 115, 169, 117, 104, 167, 235, 120, 164, 227, 229, 166, 243, 235, 168, 123, 104, 168, 253, 231, 167, 257, 231, 170, 227, 259, 167, 249, 122, 167, 116, 248, 166, 242, 108, 166, 255, 106, 166, 243, 235, 168, 123, 104, 170, 230, 106, 168, 126, 115, 167, 250, 119, 167, 236, 105, 169, 99, 239, 165, 121, 227, 167, 110, 99, 12988, 167, 260, 102, 166, 102, 231, 170, 255, 227, 169, 104, 228, 167, 116, 106, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 3885, 12, 2867, 276, 617, 3178, 13, 605, 947, 1637, 654, 39, 3462, 2171, 12, 71, 617, 3178, 13, 1071, 288, 203, 203, 3639, 389, 70, 26488, 1076, 18, 6206, 12, 2867, 12, 20, 10019, 203, 203, 3639, 2177, 1345, 3778, 729, 39, 3313, 31, 203, 3639, 729, 39, 3313, 18, 1615, 273, 389, 70, 26488, 1076, 18, 2469, 31, 203, 3639, 729, 39, 3313, 18, 4793, 273, 276, 617, 3178, 31, 203, 3639, 729, 39, 3313, 18, 7860, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 729, 39, 3313, 18, 26226, 2802, 273, 374, 31, 203, 3639, 729, 39, 3313, 18, 26226, 5027, 273, 374, 31, 203, 3639, 729, 39, 3313, 18, 26226, 3910, 273, 374, 31, 203, 3639, 729, 39, 3313, 18, 26226, 3024, 950, 273, 374, 31, 203, 3639, 389, 70, 26488, 1076, 18, 6206, 12, 71, 617, 3178, 1769, 203, 3639, 389, 70, 26488, 863, 63, 71, 617, 3178, 65, 273, 729, 39, 3313, 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 ]
./full_match/4/0x9715C55907BD2B93140715dFc421e60f3F486C62/sources/browser/bondingcurve.sol
add x^(09-1) * (34! * 09^(09-1) / 09!)
res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000;
736,104
[ 1, 1289, 619, 29020, 5908, 17, 21, 13, 225, 261, 5026, 5, 225, 21058, 29020, 5908, 17, 21, 13, 342, 21058, 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 ]
[ 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, 3639, 400, 1011, 14087, 380, 374, 92, 12648, 6028, 73, 12124, 1077, 24, 71, 6418, 71, 26, 3787, 449, 11149, 5482, 69, 27, 24008, 21, 70, 22, 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 ]
./full_match/42/0x457901AC17450b6448F85ccbD362aF10910634B4/sources/contracts/oracles/ChainlinkOracle.sol
slither-disable-next-line costly-loop
priceFeedKeys.pop();
9,565,160
[ 1, 2069, 2927, 17, 8394, 17, 4285, 17, 1369, 6991, 715, 17, 6498, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 6205, 8141, 2396, 18, 5120, 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 ]
./partial_match/3/0xdecA60F46117c5E80D3dD6393b569011d34fdf02/sources/ERC721.sol
* @title ERC165 @author Matt Condon (@shrugs) @dev Implements ERC165 using a lookup table./
contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor() public } { _registerInterface(_InterfaceId_ERC165); } function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } }
5,205,060
[ 1, 654, 39, 28275, 225, 490, 4558, 735, 19752, 261, 36, 674, 8653, 564, 13, 225, 29704, 4232, 39, 28275, 1450, 279, 3689, 1014, 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, 16351, 4232, 39, 28275, 353, 467, 654, 39, 28275, 288, 203, 225, 1731, 24, 3238, 5381, 389, 1358, 548, 67, 654, 39, 28275, 273, 374, 92, 1611, 1403, 71, 29, 69, 27, 31, 203, 203, 225, 2874, 12, 3890, 24, 516, 1426, 13, 3238, 389, 4127, 10273, 31, 203, 203, 225, 3885, 1435, 203, 565, 1071, 203, 97, 203, 225, 288, 203, 565, 389, 4861, 1358, 24899, 1358, 548, 67, 654, 39, 28275, 1769, 203, 225, 289, 203, 203, 225, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 6430, 13, 203, 225, 288, 203, 565, 327, 389, 4127, 10273, 63, 5831, 548, 15533, 203, 225, 289, 203, 203, 225, 445, 389, 4861, 1358, 12, 3890, 24, 1560, 548, 13, 203, 565, 2713, 203, 225, 288, 203, 565, 2583, 12, 5831, 548, 480, 374, 28857, 1769, 203, 565, 389, 4127, 10273, 63, 5831, 548, 65, 273, 638, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); 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 Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ifoodToken is ERC20 { using SafeMath for uint256; // the controller of minting address public ifoodDev = 0x4E471f031D03E5856125993dc3D59520229141Ce; // the controller of approving of minting and withdraw tokens address public ifoodCommunity = 0x0d72e931932356FcCf8CFF3f83390e24BE72771d; struct TokensWithLock { uint256 value; uint256 blockNumber; } // Balances for each account mapping(address => uint256) balances; // Tokens with time lock // Only when the tokens' blockNumber is less than current block number, // can the tokens be minted to the owner mapping(address => TokensWithLock) lockTokens; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // Token Info string public name = "Ifoods Token"; string public symbol = "IFOOD"; uint8 public decimals = 18; // Token Cap uint256 public totalSupplyCap = 10**10 * 10**uint256(decimals); // True if mintingFinished bool public mintingFinished = false; // The block number when deploy uint256 public deployBlockNumber = getCurrentBlockNumber(); // The min threshold of lock time uint256 public constant TIMETHRESHOLD = 7200; // The lock time of minted tokens uint256 public durationOfLock = 7200; // True if transfers are allowed bool public transferable = false; // True if the transferable can be change bool public canSetTransferable = true; modifier canMint() { require(!mintingFinished); _; } modifier only(address _address) { require(msg.sender == _address); _; } modifier nonZeroAddress(address _address) { require(_address != address(0)); _; } modifier canTransfer() { require(transferable == true); _; } event SetDurationOfLock(address indexed _caller); event ApproveMintTokens(address indexed _owner, uint256 _amount); event WithdrawMintTokens(address indexed _owner, uint256 _amount); event MintTokens(address indexed _owner, uint256 _amount); event BurnTokens(address indexed _owner, uint256 _amount); event MintFinished(address indexed _caller); event SetTransferable(address indexed _address, bool _transferable); event SetifoodDevAddress(address indexed _old, address indexed _new); event SetifoodCommunityAddress(address indexed _old, address indexed _new); event DisableSetTransferable(address indexed _address, bool _canSetTransferable); /** * @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) canTransfer 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]; } /** * @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) canTransfer 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; } // Allow `_spender` to withdraw from your account, multiple times. function approve(address _spender, uint _value) public 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 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } 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 Enables token holders to transfer their tokens freely if true * @param _transferable True if transfers are allowed */ function setTransferable(bool _transferable) only(ifoodDev) public { require(canSetTransferable == true); transferable = _transferable; SetTransferable(msg.sender, _transferable); } /** * @dev disable the canSetTransferable */ function disableSetTransferable() only(ifoodDev) public { transferable = true; canSetTransferable = false; DisableSetTransferable(msg.sender, false); } /** * @dev Set the ifoodDev * @param _ifoodDev The new ifood dev address */ function setifoodDevAddress(address _ifoodDev) only(ifoodDev) nonZeroAddress(ifoodDev) public { ifoodDev = _ifoodDev; SetifoodDevAddress(msg.sender, _ifoodDev); } /** * @dev Set the ifoodCommunity * @param _ifoodCommunity The new ifood community address */ function setifoodCommunityAddress(address _ifoodCommunity) only(ifoodCommunity) nonZeroAddress(_ifoodCommunity) public { ifoodCommunity = _ifoodCommunity; SetifoodCommunityAddress(msg.sender, _ifoodCommunity); } /** * @dev Set the duration of lock of tokens approved of minting * @param _durationOfLock the new duration of lock */ function setDurationOfLock(uint256 _durationOfLock) canMint only(ifoodCommunity) public { require(_durationOfLock >= TIMETHRESHOLD); durationOfLock = _durationOfLock; SetDurationOfLock(msg.sender); } /** * @dev Get the quantity of locked tokens * @param _owner The address of locked tokens * @return the quantity and the lock time of locked tokens */ function getLockTokens(address _owner) nonZeroAddress(_owner) view public returns (uint256 value, uint256 blockNumber) { return (lockTokens[_owner].value, lockTokens[_owner].blockNumber); } /** * @dev Approve of minting `_amount` tokens that are assigned to `_owner` * @param _owner The address that will be assigned the new tokens * @param _amount The quantity of tokens approved of mintting * @return True if the tokens are approved of mintting correctly */ function approveMintTokens(address _owner, uint256 _amount) nonZeroAddress(_owner) canMint only(ifoodCommunity) public returns (bool) { require(_amount > 0); uint256 previousLockTokens = lockTokens[_owner].value; require(previousLockTokens + _amount >= previousLockTokens); uint256 curTotalSupply = totalSupply; require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow require(curTotalSupply + _amount <= totalSupplyCap); // Check for overflow of total supply cap uint256 previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow lockTokens[_owner].value = previousLockTokens.add(_amount); uint256 curBlockNumber = getCurrentBlockNumber(); lockTokens[_owner].blockNumber = curBlockNumber.add(durationOfLock); ApproveMintTokens(_owner, _amount); return true; } /** * @dev Withdraw approval of minting `_amount` tokens that are assigned to `_owner` * @param _owner The address that will be withdrawn the tokens * @param _amount The quantity of tokens withdrawn approval of mintting * @return True if the tokens are withdrawn correctly */ function withdrawMintTokens(address _owner, uint256 _amount) nonZeroAddress(_owner) canMint only(ifoodCommunity) public returns (bool) { require(_amount > 0); uint256 previousLockTokens = lockTokens[_owner].value; require(previousLockTokens - _amount >= 0); lockTokens[_owner].value = previousLockTokens.sub(_amount); if (previousLockTokens - _amount == 0) { lockTokens[_owner].blockNumber = 0; } WithdrawMintTokens(_owner, _amount); return true; } /** * @dev Mints `_amount` tokens that are assigned to `_owner` * @param _owner The address that will be assigned the new tokens * @return True if the tokens are minted correctly */ function mintTokens(address _owner) canMint only(ifoodDev) nonZeroAddress(_owner) public returns (bool) { require(lockTokens[_owner].blockNumber <= getCurrentBlockNumber()); uint256 _amount = lockTokens[_owner].value; uint256 curTotalSupply = totalSupply; require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow require(curTotalSupply + _amount <= totalSupplyCap); // Check for overflow of total supply cap uint256 previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow totalSupply = curTotalSupply.add(_amount); balances[_owner] = previousBalanceTo.add(_amount); lockTokens[_owner].value = 0; lockTokens[_owner].blockNumber = 0; MintTokens(_owner, _amount); Transfer(0, _owner, _amount); return true; } /** * @dev Transfer tokens to multiple addresses * @param _addresses The addresses that will receieve tokens * @param _amounts The quantity of tokens that will be transferred * @return True if the tokens are transferred correctly */ function transferForMultiAddresses(address[] _addresses, uint256[] _amounts) canTransfer public returns (bool) { for (uint256 i = 0; i < _addresses.length; i++) { require(_addresses[i] != address(0)); require(_amounts[i] <= balances[msg.sender]); require(_amounts[i] > 0); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_amounts[i]); balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]); Transfer(msg.sender, _addresses[i], _amounts[i]); } return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() only(ifoodDev) canMint public returns (bool) { mintingFinished = true; MintFinished(msg.sender); return true; } function getCurrentBlockNumber() private view returns (uint256) { return block.number; } function () public payable { revert(); } }
The min threshold of lock time
uint256 public constant TIMETHRESHOLD = 7200;
6,853,540
[ 1, 1986, 1131, 5573, 434, 2176, 813, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 5381, 8721, 23840, 273, 2371, 6976, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xE954DB0fa144a2BD48a6473855cb0A25cdE4049A/sources/BRDReward.sol
* Claim back your BRDs. Unclocks the staked + gained BRD and burns xBRD @param _share amount of xBRD/ Gets the amount of xBRD in existence Calculates the amount of BRD the xBRD is worth
function leave(uint256 _share) external { uint256 totalShares = totalSupply(); uint256 what = _share.mul(BRD.balanceOf(address(this))).div( totalShares ); _burn(msg.sender, _share); BRD.transfer(msg.sender, what); }
5,208,420
[ 1, 9762, 1473, 3433, 605, 20403, 87, 18, 1351, 18517, 87, 326, 384, 9477, 397, 314, 8707, 605, 20403, 471, 18305, 87, 619, 7192, 40, 225, 389, 14419, 3844, 434, 619, 7192, 40, 19, 11881, 326, 3844, 434, 619, 7192, 40, 316, 15782, 26128, 326, 3844, 434, 605, 20403, 326, 619, 7192, 40, 353, 26247, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8851, 12, 11890, 5034, 389, 14419, 13, 3903, 288, 203, 3639, 2254, 5034, 2078, 24051, 273, 2078, 3088, 1283, 5621, 203, 203, 3639, 2254, 5034, 4121, 273, 389, 14419, 18, 16411, 12, 7192, 40, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 2934, 2892, 12, 203, 5411, 2078, 24051, 203, 3639, 11272, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 389, 14419, 1769, 203, 203, 3639, 605, 20403, 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 ]
pragma solidity ^0.5.16; import "./SToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./STRK.sol"; /** * @title Strike's Comptroller Contract * @author Strike */ contract Comptroller is ComptrollerV5Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(SToken sToken); /// @notice Emitted when an account enters a market event MarketEntered(SToken sToken, address account); /// @notice Emitted when an account exits a market event MarketExited(SToken sToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(SToken sToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(SToken sToken, string action, bool pauseState); /// @notice Emitted when market striked status is changed event MarketStriked(SToken sToken, bool isStriked); /// @notice Emitted when STRK rate is changed event NewStrikeRate(uint oldStrikeRate, uint newStrikeRate); /// @notice Emitted when a new STRK speed is calculated for a market event StrikeSpeedUpdated(SToken indexed sToken, uint newSpeed); /// @notice Emitted when STRK is distributed to a supplier event DistributedSupplierStrike(SToken indexed sToken, address indexed supplier, uint strikeDelta, uint strikeSupplyIndex); /// @notice Emitted when STRK is distributed to a borrower event DistributedBorrowerStrike(SToken indexed sToken, address indexed borrower, uint strikeDelta, uint strikeBorrowIndex); /// @notice Emitted when new Strike speed is set event ContributorStrikeSpeedUpdated(address indexed contributor, uint newStrikeSpeed); /// @notice Emitted when Strike is granted event StrikeGranted(address recipient, uint amount); /// @notice Emitted when a new borrow-side Strike speed is calculated for a market event StrikeBorrowSpeedUpdated(SToken indexed sToken, uint newSpeed); /// @notice Emitted when a new supply-side Strike speed is calculated for a market event StrikeSupplySpeedUpdated(SToken indexed sToken, uint newSpeed); /// @notice The threshold above which the flywheel transfers STRK, in wei uint public constant strikeClaimThreshold = 0.001e18; /// @notice The initial STRK index for a market uint224 public constant strikeInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (SToken[] memory) { SToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param sToken The sToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, SToken sToken) external view returns (bool) { return markets[address(sToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param sTokens The list of addresses of the sToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory sTokens) public returns (uint[] memory) { uint len = sTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { SToken sToken = SToken(sTokens[i]); results[i] = uint(addToMarketInternal(sToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param sToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(SToken sToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(sToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(sToken); emit MarketEntered(sToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param sTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address sTokenAddress) external returns (uint) { SToken sToken = SToken(sTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the sToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = sToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(sTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(sToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set sToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete sToken from the account’s list of assets */ // load into memory for faster iteration SToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == sToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 SToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(sToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param sToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address sToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[sToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[sToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateStrikeSupplyIndex(sToken); distributeSupplierStrike(sToken, minter); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param sToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address sToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused sToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param sToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of sTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address sToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(sToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateStrikeSupplyIndex(sToken); distributeSupplierStrike(sToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address sToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[sToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[sToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, SToken(sToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param sToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address sToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused sToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param sToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address sToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[sToken], "borrow is paused"); if (!markets[sToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[sToken].accountMembership[borrower]) { // only sTokens may call borrowAllowed if borrower not in market require(msg.sender == sToken, "sender must be sToken"); // attempt to add borrower to the market Error err = addToMarketInternal(SToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[sToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(SToken(sToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, SToken(sToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: SToken(sToken).borrowIndex()}); updateStrikeBorrowIndex(sToken, borrowIndex); distributeBorrowerStrike(sToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param sToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address sToken, address borrower, uint borrowAmount) external { // Shh - currently unused sToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param sToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address sToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[sToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: SToken(sToken).borrowIndex()}); updateStrikeBorrowIndex(sToken, borrowIndex); distributeBorrowerStrike(sToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param sToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address sToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused sToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param sTokenBorrowed Asset which was borrowed by the borrower * @param sTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address sTokenBorrowed, address sTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[sTokenBorrowed].isListed || !markets[sTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = SToken(sTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param sTokenBorrowed Asset which was borrowed by the borrower * @param sTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address sTokenBorrowed, address sTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused sTokenBorrowed; sTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param sTokenCollateral Asset which was used as collateral and will be seized * @param sTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address sTokenCollateral, address sTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[sTokenCollateral].isListed || !markets[sTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (SToken(sTokenCollateral).comptroller() != SToken(sTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateStrikeSupplyIndex(sTokenCollateral); distributeSupplierStrike(sTokenCollateral, borrower); distributeSupplierStrike(sTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param sTokenCollateral Asset which was used as collateral and will be seized * @param sTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address sTokenCollateral, address sTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused sTokenCollateral; sTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param sToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of sTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address sToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(sToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateStrikeSupplyIndex(sToken); distributeSupplierStrike(sToken, src); distributeSupplierStrike(sToken, dst); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param sToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of sTokens to transfer */ function transferVerify(address sToken, address src, address dst, uint transferTokens) external { // Shh - currently unused sToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `sTokenBalance` is the number of sTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint sTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, SToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, SToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param sTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address sTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, SToken(sTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param sTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral sToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, SToken sTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in SToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { SToken asset = assets[i]; // Read the balances and exchange rate from the sToken (oErr, vars.sTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * sTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.sTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with sTokenModify if (asset == sTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in sToken.liquidateBorrowFresh) * @param sTokenBorrowed The address of the borrowed sToken * @param sTokenCollateral The address of the collateral sToken * @param actualRepayAmount The amount of sTokenBorrowed underlying to convert into sTokenCollateral tokens * @return (errorCode, number of sTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address sTokenBorrowed, address sTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(SToken(sTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(SToken(sTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = SToken(sTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param sToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(SToken sToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(sToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(sToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(sToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param sToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(SToken sToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(sToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } sToken.isSToken(); // Sanity check to make sure its really a SToken markets[address(sToken)] = Market({isListed: true, isStriked: false, collateralFactorMantissa: 0}); _addMarketInternal(address(sToken)); _initializeMarket(address(sToken)); emit MarketListed(sToken); return uint(Error.NO_ERROR); } function _initializeMarket(address sToken) internal { uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits"); StrikeMarketState storage supplyState = strikeSupplyState[sToken]; StrikeMarketState storage borrowState = strikeBorrowState[sToken]; /* * Update market state indices */ if (supplyState.index == 0) { // Initialize supply state index with default value supplyState.index = strikeInitialIndex; } if (borrowState.index == 0) { // Initialize borrow state index with default value borrowState.index = strikeInitialIndex; } supplyState.block = borrowState.block = blockNumber; } function _addMarketInternal(address sToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != SToken(sToken), "market already added"); } allMarkets.push(SToken(sToken)); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(SToken sToken, bool state) public returns (bool) { require(markets[address(sToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(sToken)] = state; emit ActionPaused(sToken, "Mint", state); return state; } function _setBorrowPaused(SToken sToken, bool state) public returns (bool) { require(markets[address(sToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(sToken)] = state; emit ActionPaused(sToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /*** STRK Distribution ***/ /** * @notice Set STRK speed for a single market * @param sToken The market whose STRK speed to update * @param supplySpeeds New supply-side STRK speed for market * @param borrowSpeeds New borrow-side STRK speed for market */ function _setStrikeSpeeds(SToken[] memory sToken, uint[] memory supplySpeeds, uint[] memory borrowSpeeds) public { require(adminOrInitializing(), "only admin can set strike speed"); uint numTokens = sToken.length; require(numTokens == supplySpeeds.length && numTokens == borrowSpeeds.length, "Comptroller::_setCompSpeeds invalid input"); for (uint i = 0; i < numTokens; ++i) { setStrikeSpeedInternal(sToken[i], supplySpeeds[i], borrowSpeeds[i]); } } function setStrikeSpeedInternal(SToken sToken, uint supplySpeed, uint borrowSpeed) internal { Market storage market = markets[address(sToken)]; require(market.isListed, "strike market is not listed"); if (strikeSupplySpeeds[address(sToken)] != supplySpeed) { updateStrikeSupplyIndex(address(sToken)); strikeSupplySpeeds[address(sToken)] = supplySpeed; emit StrikeSupplySpeedUpdated(sToken, supplySpeed); } if (strikeBorrowSpeeds[address(sToken)] != borrowSpeed) { Exp memory borrowIndex = Exp({mantissa: sToken.borrowIndex()}); updateStrikeBorrowIndex(address(sToken), borrowIndex); // Update speed and emit event strikeBorrowSpeeds[address(sToken)] = borrowSpeed; emit StrikeBorrowSpeedUpdated(sToken, borrowSpeed); } } /** * @notice Accrue STRK to the market by updating the supply index * @param sToken The market whose supply index to update */ function updateStrikeSupplyIndex(address sToken) internal { StrikeMarketState storage supplyState = strikeSupplyState[sToken]; uint supplySpeed = strikeSupplySpeeds[sToken]; uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits"); uint deltaBlocks = sub_(uint(blockNumber), uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = SToken(sToken).totalSupply(); uint strikeAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(strikeAccrued, supplyTokens) : Double({mantissa: 0}); supplyState.index = safe224(add_(Double({mantissa: supplyState.index}), ratio).mantissa, "new index exceeds 224 bits"); supplyState.block = blockNumber; } else if (deltaBlocks > 0) { supplyState.block = blockNumber; } } /** * @notice Accrue STRK to the market by updating the borrow index * @param sToken The market whose borrow index to update */ function updateStrikeBorrowIndex(address sToken, Exp memory marketBorrowIndex) internal { StrikeMarketState storage borrowState = strikeBorrowState[sToken]; uint borrowSpeed = strikeBorrowSpeeds[sToken]; uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits"); uint deltaBlocks = sub_(uint(blockNumber), uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(SToken(sToken).totalBorrows(), marketBorrowIndex); uint strikeAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(strikeAccrued, borrowAmount) : Double({mantissa: 0}); borrowState.index = safe224(add_(Double({mantissa: borrowState.index}), ratio).mantissa, "new index exceeds 224 bits"); borrowState.block = blockNumber; } else if (deltaBlocks > 0) { borrowState.block = blockNumber; } } /** * @notice Calculate STRK accrued by a supplier and possibly transfer it to them * @param sToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute STRK to */ function distributeSupplierStrike(address sToken, address supplier) internal { StrikeMarketState storage supplyState = strikeSupplyState[sToken]; uint supplyIndex = supplyState.index; uint supplierIndex = strikeSupplierIndex[sToken][supplier]; strikeSupplierIndex[sToken][supplier] = supplyIndex; if (supplierIndex == 0 && supplyIndex >= strikeInitialIndex) { supplierIndex = strikeInitialIndex; } Double memory deltaIndex = Double({mantissa: sub_(supplyIndex, supplierIndex)}); uint supplierTokens = SToken(sToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(strikeAccrued[supplier], supplierDelta); strikeAccrued[supplier] = supplierAccrued; emit DistributedSupplierStrike(SToken(sToken), supplier, supplierDelta, supplyIndex); } /** * @notice Calculate STRK accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param sToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute STRK to */ function distributeBorrowerStrike(address sToken, address borrower, Exp memory marketBorrowIndex) internal { StrikeMarketState storage borrowState = strikeBorrowState[sToken]; uint borrowIndex = borrowState.index; uint borrowerIndex = strikeBorrowerIndex[sToken][borrower]; strikeBorrowerIndex[sToken][borrower] = borrowIndex; if (borrowerIndex == 0 && borrowIndex >= strikeInitialIndex) { borrowerIndex = strikeInitialIndex; } Double memory deltaIndex = Double({mantissa: sub_(borrowIndex, borrowerIndex)}); uint borrowerAmount = div_(SToken(sToken).borrowBalanceStored(borrower), marketBorrowIndex); // Calculate strike accrued: sTokenAmount * accruedPerBorrowedUnit uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(strikeAccrued[borrower], borrowerDelta); strikeAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerStrike(SToken(sToken), borrower, borrowerDelta, borrowIndex); } /** * @notice Transfer STRK to the user, if they are above the threshold * @dev Note: If there is not enough STRK, we do not perform the transfer all. * @param user The address of the user to transfer STRK to * @param userAccrued The amount of STRK to (possibly) transfer * @return The amount of STRK which was NOT transferred to the user */ function transferStrike(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { STRK strk = STRK(getSTRKAddress()); uint strikeRemaining = strk.balanceOf(address(this)); if (userAccrued <= strikeRemaining) { strk.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the strike accrued by holder in all markets * @param holder The address to claim STRK for */ function claimStrike(address holder) public { return claimStrike(holder, allMarkets); } /** * @notice Claim all the strike accrued by holder in the specified markets * @param holder The address to claim STRK for * @param sTokens The list of markets to claim STRK in */ function claimStrike(address holder, SToken[] memory sTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimStrike(holders, sTokens, true, true); } /** * @notice Claim all strike accrued by the holders * @param holders The addresses to claim STRK for * @param sTokens The list of markets to claim STRK in * @param borrowers Whether or not to claim STRK earned by borrowing * @param suppliers Whether or not to claim STRK earned by supplying */ function claimStrike(address[] memory holders, SToken[] memory sTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < sTokens.length; i++) { SToken sToken = sTokens[i]; require(markets[address(sToken)].isListed, "market must be listed"); if (borrowers) { Exp memory borrowIndex = Exp({mantissa: sToken.borrowIndex()}); updateStrikeBorrowIndex(address(sToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerStrike(address(sToken), holders[j], borrowIndex); } } if (suppliers) { updateStrikeSupplyIndex(address(sToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierStrike(address(sToken), holders[j]); } } } for (uint j = 0; j < holders.length; j++) { strikeAccrued[holders[j]] = grantSTRKInternal(holders[j], strikeAccrued[holders[j]]); } } /** * @notice Transfer STRK to the user * @dev Note: If there is not enough STRK, we do not perform the transfer all. * @param user The address of the user to transfer STRK to * @param amount The amount of STRK to (possibly) transfer * @return The amount of STRK which was NOT transferred to the user */ function grantSTRKInternal(address user, uint amount) internal returns (uint) { STRK strk = STRK(getSTRKAddress()); uint strikeRemaining = strk.balanceOf(address(this)); if (amount > 0 && amount <= strikeRemaining) { strk.transfer(user, amount); return 0; } return amount; } /*** STRK Distribution Admin ***/ /** * @notice Update additional accrued Strike for a contributor * @param contributor The address to calculate contributor rewards */ function updateContributorRewards(address contributor) public { uint strikeSpeed = strikeContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && strikeSpeed > 0) { uint newAccrued = mul_(deltaBlocks, strikeSpeed); uint contributorAccrued = add_(strikeAccrued[contributor], newAccrued); strikeAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } } /** * @notice Set Strike speed for a single contributor * @param contributor The contributor whose Strike speed to set * @param strikeSpeed New Strike speed for contributor */ function _setContributorStrikeSpeed(address contributor, uint strikeSpeed) public { require(adminOrInitializing(), "Only Admin can set STRK speed"); // Update contributor STRK reward before update speed updateContributorRewards(contributor); if (strikeSpeed == 0) { // release storage delete lastContributorBlock[contributor]; } // Update last block lastContributorBlock[contributor] = getBlockNumber(); // Update STRK speed strikeContributorSpeeds[contributor] = strikeSpeed; emit ContributorStrikeSpeedUpdated(contributor, strikeSpeed); } /** * @notice Transfer STRK to the recipient * @param recipient The address of the receipient to transfer STRK to * @param amount The amount of STRK to (possibly) transfer */ function _grantSTRK(address recipient, uint amount) public { require(adminOrInitializing(), "Only Admin can grant STRK"); uint amountLeft = grantSTRKInternal(recipient, amount); require(amountLeft == 0, "Insufficient STRK for grant"); emit StrikeGranted(recipient, amount); } /** * @notice Set the amount of STRK distributed per block * @param strikeRate_ The amount of STRK wei per block to distribute */ function _setStrikeRate(uint strikeRate_) public { require(adminOrInitializing(), "only admin can change strike rate"); uint oldRate = strikeRate; strikeRate = strikeRate_; emit NewStrikeRate(oldRate, strikeRate_); // refreshStrikeSpeedsInternal(); } /** * @notice Remove a market from strikeMarkets, preventing it from earning STRK in the flywheel * @param sToken The address of the market to drop */ function _dropStrikeMarket(address sToken) public { require(msg.sender == admin, "only admin can drop strike market"); Market storage market = markets[sToken]; require(market.isStriked == true, "market is not a strike market"); market.isStriked = false; emit MarketStriked(SToken(sToken), false); // refreshStrikeSpeedsInternal(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (SToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the STRK token * @return The address of STRK */ function getSTRKAddress() public view returns (address) { return 0x74232704659ef37c08995e386A2E26cc27a8d7B1; } /** * @notice check user can claim Strike Token by suppling * @return bool: true - can claim, false: cannot claim */ function canClaimStrikeBySuppling(address user) public view returns (bool) { SToken[] memory sTokens = accountAssets[user]; for (uint i = 0; i < sTokens.length; i++) { SToken asset = sTokens[i]; if (asset.balanceOf(user) > 0) { return true; } } return false; } }
If the redeemer is not 'in' the market, then we can bypass the liquidity check */
function redeemAllowedInternal(address sToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[sToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[sToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); }
6,002,534
[ 1, 2047, 326, 283, 24903, 264, 353, 486, 296, 267, 11, 326, 13667, 16, 1508, 732, 848, 17587, 326, 4501, 372, 24237, 866, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 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, 283, 24903, 5042, 3061, 12, 2867, 272, 1345, 16, 1758, 283, 24903, 264, 16, 2254, 283, 24903, 5157, 13, 2713, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 309, 16051, 3355, 2413, 63, 87, 1345, 8009, 291, 682, 329, 13, 288, 203, 5411, 327, 2254, 12, 668, 18, 12693, 1584, 67, 4400, 67, 7085, 2056, 1769, 203, 3639, 289, 203, 203, 3639, 309, 16051, 3355, 2413, 63, 87, 1345, 8009, 4631, 13447, 63, 266, 24903, 264, 5717, 288, 203, 5411, 327, 2254, 12, 668, 18, 3417, 67, 3589, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 370, 480, 1068, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 2254, 12, 370, 1769, 203, 3639, 289, 203, 3639, 309, 261, 6620, 25602, 405, 374, 13, 288, 203, 5411, 327, 2254, 12, 668, 18, 706, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 1769, 203, 3639, 289, 203, 203, 3639, 327, 2254, 12, 668, 18, 3417, 67, 3589, 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 ]
pragma solidity ^0.4.22; /* * Creator: IBR (Ibera) */ /* * Abstract Token Smart Contract * */ /* * Safe Math Smart Contract. * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * Abstract Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; } /** * IBR token smart contract. */ contract IBRToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 250000000 * (10**18); /** * Address of the owner of this smart contract. */ address private owner; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function IBRToken () { owner = msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "Ibera"; string constant public symbol = "IBR"; uint8 constant public decimals = 18; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address emit Transfer(0x0, msg.sender, _value); return true; } return false; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze ALL token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } /** * Unfreeze ALL token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } /** * Freeze specific account * May only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
* IBR token smart contract./
contract IBRToken is AbstractToken { uint256 constant MAX_TOKEN_COUNT = 250000000 * (10**18); address private owner; mapping (address => bool) private frozenAccount; uint256 tokenCount = 0; bool frozen = false; function IBRToken () { owner = msg.sender; } function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "Ibera"; string constant public symbol = "IBR"; uint8 constant public decimals = 18; function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); emit Transfer(0x0, msg.sender, _value); return true; } return false; } function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); emit Transfer(0x0, msg.sender, _value); return true; } return false; } function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } event FrozenFunds(address target, bool frozen); event RefundTokens(address _token, address _refund, uint256 _value); event Freeze (); event Unfreeze (); }
1,415,497
[ 1, 45, 7192, 1147, 13706, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 467, 7192, 1345, 353, 4115, 1345, 288, 203, 27699, 27699, 225, 2254, 5034, 5381, 4552, 67, 8412, 67, 7240, 273, 6969, 17877, 380, 261, 2163, 636, 2643, 1769, 203, 27699, 225, 1758, 3238, 3410, 31, 203, 21281, 225, 2874, 261, 2867, 516, 1426, 13, 3238, 12810, 3032, 31, 203, 203, 225, 2254, 5034, 1147, 1380, 273, 374, 31, 203, 21281, 7010, 225, 1426, 12810, 273, 629, 31, 203, 21281, 7010, 225, 445, 467, 7192, 1345, 1832, 288, 203, 565, 3410, 273, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 225, 445, 2078, 3088, 1283, 1435, 5381, 1135, 261, 11890, 5034, 14467, 13, 288, 203, 565, 327, 1147, 1380, 31, 203, 225, 289, 203, 203, 225, 533, 5381, 1071, 508, 273, 315, 45, 744, 69, 14432, 203, 225, 533, 5381, 1071, 3273, 273, 315, 45, 7192, 14432, 203, 225, 2254, 28, 5381, 1071, 15105, 273, 6549, 31, 203, 21281, 225, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1135, 261, 6430, 2216, 13, 288, 203, 565, 2583, 12, 5, 28138, 3032, 63, 3576, 18, 15330, 19226, 203, 202, 430, 261, 28138, 13, 327, 629, 31, 203, 565, 469, 327, 4115, 1345, 18, 13866, 261, 67, 869, 16, 389, 1132, 1769, 203, 225, 289, 203, 203, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 203, 565, 1135, 261, 6430, 2216, 13, 288, 203, 202, 6528, 12, 5, 28138, 3032, 63, 67, 2080, 19226, 203, 565, 309, 261, 28138, 13, 327, 2 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- //Inke直播 contract // //Inke黄金 // Symbol : IKG // Name : Inke Gold // Total supply: 45000 // Decimals : 0 // //Inke币 // Symbol : Inke // Name : Inke Token // Total supply: 100000000000 // Decimals : 18 // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Admin contract // ---------------------------------------------------------------------------- contract Administration { event AdminTransferred(address indexed _from, address indexed _to); event Pause(); event Unpause(); address public CEOAddress = 0xDc08d076b65c3d876Bb2369b167Dc304De4b9677; address public CFOAddress = 0x4Ea72110C00f416963D34A7FECbF0FCDd306D15A; bool public paused = false; modifier onlyCEO() { require(msg.sender == CEOAddress); _; } modifier onlyAdmin() { require(msg.sender == CEOAddress || msg.sender == CFOAddress); _; } function setCFO(address _newAdmin) public onlyCEO { require(_newAdmin != address(0)); emit AdminTransferred(CFOAddress, _newAdmin); CFOAddress = _newAdmin; } function withdrawBalance() external onlyAdmin { CEOAddress.transfer(address(this).balance); } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() public onlyAdmin whenNotPaused returns(bool) { paused = true; emit Pause(); return true; } function unpause() public onlyAdmin whenPaused returns(bool) { paused = false; emit Unpause(); return true; } uint oneEth = 1 ether; } contract InkeGold is ERC20Interface, Administration, SafeMath { event GoldTransfer(address indexed from, address indexed to, uint tokens); string public goldSymbol; string public goldName; uint8 public goldDecimals; uint public _goldTotalSupply; mapping(address => uint) goldBalances; mapping(address => bool) goldFreezed; mapping(address => uint) goldFreezeAmount; mapping(address => uint) goldUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { goldSymbol = "IKG"; goldName = "Inke Gold"; goldDecimals = 0; _goldTotalSupply = 45000; goldBalances[CEOAddress] = _goldTotalSupply; emit GoldTransfer(address(0), CEOAddress, _goldTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function goldTotalSupply() public constant returns (uint) { return _goldTotalSupply - goldBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function goldBalanceOf(address tokenOwner) public constant returns (uint balance) { return goldBalances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to to account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(goldFreezed[msg.sender] == false){ goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } else { if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) { require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender])); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], amount); _goldTotalSupply = safeAdd(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], amount); _goldTotalSupply = safeSub(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function goldFreeze(address user, uint amount, uint period) public onlyAdmin { require(goldBalances[user] >= amount); goldFreezed[user] = true; goldUnlockTime[user] = uint(now) + period; goldFreezeAmount[user] = amount; } function _goldFreeze(uint amount) internal { require(goldFreezed[msg.sender] == false); require(goldBalances[msg.sender] >= amount); goldFreezed[msg.sender] = true; goldUnlockTime[msg.sender] = uint(-1); goldFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function goldUnFreeze() public whenNotPaused { require(goldFreezed[msg.sender] == true); require(goldUnlockTime[msg.sender] < uint(now)); goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = 0; } function _goldUnFreeze(uint _amount) internal { require(goldFreezed[msg.sender] == true); goldUnlockTime[msg.sender] = 0; goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = safeSub(goldFreezeAmount[msg.sender], _amount); } function goldIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = goldFreezed[user]; amount = goldFreezeAmount[user]; timeLeft = goldUnlockTime[user] - uint(now); } } contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to to account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner&#39;s account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner&#39;s account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } } contract Inke is InkeToken { event MembershipUpdate(address indexed member, uint indexed level); event MemberAllowance(address indexed member, uint indexed amount); event MembershipCancel(address indexed member); event InkeTradeCreated(uint indexed tradeId, bool indexed ifGold, uint gold, uint token); event TradeCancel(uint indexed tradeId); event TradeComplete(uint indexed tradeId, address indexed buyer, address indexed seller, uint gold, uint token); event Mine(address indexed miner, uint indexed salary); mapping (address => uint) MemberToLevel; mapping (address => uint) MemberToGold; mapping (address => uint) MemberToToken; mapping (address => uint) MemberToTime; mapping (address => address) MemberToBoss; mapping (address => uint) MemberToAllowance; uint public period = 30 days; uint leaseTimeI = uint(now) + 388 days; uint leaseTimeII = uint(now) + 99 days; uint[4] public boardSpot = [ 0, 20000, 1000, 100 ]; uint[4] public boardMember =[ 0, 1, 10, 100 ]; uint[4] public salary = [ 0, 27397000000000000000000, 273970000000000000000000, 2739700000000000000000000 ]; struct InkeTrade { address seller; bool ifGold; uint gold; uint token; } InkeTrade[] inkeTrades; function boardMemberApply(uint _level) public whenNotPaused { require(_level > 0 && _level <= 3); require(boardSpot[_level] > 0); require(goldBalances[msg.sender] >= boardMember[_level]); _goldFreeze(boardMember[_level]); MemberToLevel[msg.sender] = _level; if(MemberToTime[msg.sender] == 0) { MemberToTime[msg.sender] = uint(now); } boardSpot[_level]--; emit MembershipUpdate(msg.sender, _level); } function giveMemberAllowance(address _member, uint _amount) public onlyAdmin { MemberToAllowance[_member] = safeAdd(MemberToAllowance[_member], _amount); emit MemberAllowance(_member, _amount); } function assignSubMember(address _subMember, uint _level) public whenNotPaused { require(_level > 0 && _level < 3); require(MemberToAllowance[msg.sender] >= boardMember[_level]); MemberToAllowance[msg.sender] = MemberToAllowance[msg.sender] - boardMember[_level]; MemberToLevel[_subMember] = _level; if(MemberToTime[_subMember] == 0) { MemberToTime[_subMember] = uint(now); } MemberToBoss[_subMember] = msg.sender; boardSpot[_level]--; emit MembershipUpdate(_subMember, _level); } function getBoardMember(address _member) public view returns ( uint level, uint allowance, uint timeLeft ) { level = MemberToLevel[_member]; allowance = MemberToAllowance[_member]; if(MemberToTime[_member] > uint(now)) { timeLeft = safeSub(MemberToTime[_member], uint(now)); } else { timeLeft = 0; } } function getMemberBoss(address _member) public view returns (address) { return MemberToBoss[_member]; } function boardMemberCancel() public whenNotPaused { uint level = MemberToLevel[msg.sender]; require(level > 0); if(level == 1) { require(leaseTimeII < uint(now)); } else { require(leaseTimeI < uint(now)); } _goldUnFreeze(boardMember[MemberToLevel[msg.sender]]); boardSpot[level]++; MemberToLevel[msg.sender] = 0; emit MembershipCancel(msg.sender); } function createInkeTrade(bool _ifGold, uint _gold, uint _token) public whenNotPaused returns (uint) { if(_ifGold) { require(goldBalances[msg.sender] >= _gold); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], _gold); MemberToGold[msg.sender] = _gold; InkeTrade memory inke = InkeTrade({ seller: msg.sender, ifGold:_ifGold, gold: _gold, token: _token }); uint newGoldTradeId = inkeTrades.push(inke) - 1; emit InkeTradeCreated(newGoldTradeId, _ifGold, _gold, _token); return newGoldTradeId; } else { require(balances[msg.sender] >= _token); balances[msg.sender] = safeSub(balances[msg.sender], _token); MemberToToken[msg.sender] = _token; InkeTrade memory _inke = InkeTrade({ seller: msg.sender, ifGold:_ifGold, gold: _gold, token: _token }); uint newTokenTradeId = inkeTrades.push(_inke) - 1; emit InkeTradeCreated(newTokenTradeId, _ifGold, _gold, _token); return newTokenTradeId; } } function cancelTrade(uint _tradeId) public whenNotPaused { InkeTrade memory inke = inkeTrades[_tradeId]; require(inke.seller == msg.sender); if(inke.ifGold){ goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], inke.gold); MemberToGold[msg.sender] = 0; } else { balances[msg.sender] = safeAdd(balances[msg.sender], inke.token); MemberToToken[msg.sender] = 0; } delete inkeTrades[_tradeId]; emit TradeCancel(_tradeId); } function trade(uint _tradeId) public whenNotPaused { InkeTrade memory inke = inkeTrades[_tradeId]; if(inke.ifGold){ goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], inke.gold); MemberToGold[inke.seller] = 0; transfer(inke.seller, inke.token); delete inkeTrades[_tradeId]; emit TradeComplete(_tradeId, msg.sender, inke.seller, inke.gold, inke.token); } else { balances[msg.sender] = safeAdd(balances[msg.sender], inke.token); MemberToToken[inke.seller] = 0; goldTransfer(inke.seller, inke.gold); delete inkeTrades[_tradeId]; emit TradeComplete(_tradeId, msg.sender, inke.seller, inke.gold, inke.token); } } function mine() public whenNotPaused { uint level = MemberToLevel[msg.sender]; require(MemberToTime[msg.sender] < uint(now)); require(level > 0); _mine(salary[level], msg.sender); MemberToTime[msg.sender] = safeAdd(MemberToTime[msg.sender], period); emit Mine(msg.sender, salary[level]); } function setBoardMember(uint one, uint two, uint three) public onlyAdmin { boardMember[1] = one; boardMember[2] = two; boardMember[3] = three; } function setSalary(uint one, uint two, uint three) public onlyAdmin { salary[1] = one; salary[2] = two; salary[3] = three; } function setPeriod(uint time) public onlyAdmin { period = time; } function getTrade(uint _tradeId) public view returns ( address seller, bool ifGold, uint gold, uint token ) { InkeTrade memory _inke = inkeTrades[_tradeId]; seller = _inke.seller; ifGold = _inke.ifGold; gold = _inke.gold; token = _inke.token; } function WhoIsTheContractMaster() public pure returns (string) { return "Alexander The Exlosion"; } }
------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); }
1,980,052
[ 1, 29461, 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, 0, 0, 0, 0, 0, 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, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 382, 4491, 14432, 203, 3639, 508, 273, 315, 382, 4491, 3155, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 2787, 9449, 31, 203, 3639, 312, 558, 2864, 273, 1666, 12648, 12648, 12648, 2787, 31, 203, 3639, 284, 1074, 2864, 273, 890, 12648, 12648, 12648, 2787, 31, 203, 540, 203, 3639, 324, 26488, 63, 1441, 51, 1887, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 29538, 51, 1887, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xB75d77f3614f80Bf422b058C1956A9646a6F74f5/sources/GlitchLegacy.sol
Contract Constants supplypriceMaxPerWallet Founders and Project Addresses Constructor
contract GlitchLegacy is ERC721A, Ownable, ReentrancyGuard, DefaultOperatorFilterer { using Strings for uint256; uint256 constant MAX_SUPPLY = 3333; uint256 public price = 0.033 ether; uint256 public publicprice =0.04 ether; uint256 public maxMint = 3; uint256 public maxPresaleMint = 2; bool public saleActive= false; bool public presaleActive= false; mapping (address => uint256) public _tokensMintedByAddress; mapping (address => uint256) public publicsaleAddressMinted; bytes32 public presaleMerkleRoot=0x8e12ac29d74e210a6386c85c9e1c379af7674c4d287be74d3d299231b49c5163; bytes32 public VipMerkleRoot=0xadafdcb5730c8e0400a2864ecb7f49e0cd6ca71779bd8667ce7551f1d770eb5e; constructor( ) ERC721A("Glitch Legacy", "Glitch") { _safeMint(msg.sender,1); } modifier onlySaleActive() { require(saleActive, "Public sale is not active"); _; } modifier onlyPresaleActive() { require(presaleActive, "Presale is not active"); _; } function mint(uint256 quantity) external payable onlySaleActive nonReentrant() { require(publicprice * quantity <= msg.value,"Wrong amout of ETH sent"); require(publicsaleAddressMinted[msg.sender] + quantity <= maxMint, "YOU HAVE ALREADY MINTED THE MAX AMOUNT ALLOWED, TRY DECREASING THE MINT QUANTITY"); require(totalSupply() + quantity <= MAX_SUPPLY, "Sold Out"); publicsaleAddressMinted[msg.sender] += quantity; _safeMint( msg.sender, quantity); } function mintWhitelist(uint256 quantity, bytes32[] memory proof) external payable onlyPresaleActive nonReentrant() { require(MerkleProof.verify(proof, presaleMerkleRoot, keccak256(abi.encodePacked(msg.sender))), "YOU ARE NOT ALLOWED TO MINT... YET!"); require(price * quantity <= msg.value, "Wrong amout of ETH sent"); require(_tokensMintedByAddress[msg.sender] + quantity <= maxPresaleMint, "YOU HAVE ALREADY MINTED THE MAX AMOUNT ALLOWED, TRY DECREASING THE MINT QUANTITY"); require(totalSupply() + quantity < MAX_SUPPLY, "SoldOut!"); _tokensMintedByAddress[msg.sender] += quantity; _safeMint(msg.sender, quantity); } function mintVip(uint256 quantity, bytes32[] memory proof) external payable onlyPresaleActive nonReentrant() { require(MerkleProof.verify(proof, VipMerkleRoot, keccak256(abi.encodePacked(msg.sender))), "YOU ARE NOT ALLOWED TO MINT... YET!"); require(_tokensMintedByAddress[msg.sender] + quantity <= maxPresaleMint, "YOU HAVE ALREADY MINTED THE MAX AMOUNT ALLOWED, TRY DECREASING THE MINT QUANTITY"); require(totalSupply() + quantity < MAX_SUPPLY, "SoldOut!"); _tokensMintedByAddress[msg.sender] += quantity; _safeMint(msg.sender, quantity); } function mintDev(uint256 quantity) external onlyOwner { require(totalSupply() + quantity <= MAX_SUPPLY, "Minting too many"); _safeMint(msg.sender, quantity); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) external onlyOwner { _baseTokenURI = baseURI; } function setPresaleMerkleRoot(bytes32 presaleRoot) public onlyOwner { presaleMerkleRoot = presaleRoot; } function setVipMerkleRoot(bytes32 VipRoot) public onlyOwner { VipMerkleRoot = VipRoot; } function setPresaleActive() external onlyOwner { presaleActive = !presaleActive; } function setSaleActive() external onlyOwner { saleActive = !saleActive; } function setPrice(uint256 newPrice) external onlyOwner { price = newPrice; } function setpublicPrice(uint256 _newPrice) external onlyOwner { publicprice = _newPrice; } function setMaxMint(uint256 _maxMint) external onlyOwner { maxMint = _maxMint; } function setMaxPresaleMint(uint256 _maxPresaleMint) external onlyOwner { maxPresaleMint = _maxPresaleMint; } function withdrawAll() public onlyOwner nonReentrant() { uint256 _balance = address(this).balance; uint256 percent = _balance / 100; require(sent, "Failed to send Ether"); require(sent, "Failed to send Ether"); require(sent, "Failed to send Ether"); require(sent, "Failed to send Ether"); require(sent, "Failed to send Ether"); require(sent, "Failed to send Ether"); } (bool sent, bytes memory data) = a6.call{value: percenta6}(""); ( sent, data) = a1.call{value: percenta1}(""); ( sent, data) = a2.call{value: percenta2}(""); ( sent, data) = a3.call{value: percenta3}(""); ( sent, data) = a4.call{value: percenta4}(""); ( sent, data)= a5.call{value: percenta5}(""); function tokenURI(uint256 tokenId) override public view returns (string memory) { return string(abi.encodePacked(_baseURI(), "", uint256(tokenId).toString(), ".json")); } function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { super.setApprovalForAll(operator, approved); } function approve(address operator, uint256 tokenId) public payable override onlyAllowedOperatorApproval(operator) { super.approve(operator, tokenId); } function transferFrom(address from, address to, uint256 tokenId) public payable override onlyAllowedOperator(from) { super.transferFrom(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public payable override onlyAllowedOperator(from) { super.safeTransferFrom(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override payable onlyAllowedOperator(from) { super.safeTransferFrom(from, to, tokenId, data); } }
8,300,773
[ 1, 8924, 225, 5245, 1169, 412, 879, 3057, 2747, 2173, 16936, 10750, 414, 471, 5420, 23443, 225, 11417, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 15157, 1437, 12235, 353, 4232, 39, 27, 5340, 37, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 16, 2989, 5592, 1586, 264, 288, 21281, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 203, 565, 2254, 5034, 5381, 4552, 67, 13272, 23893, 273, 890, 3707, 23, 31, 203, 565, 2254, 5034, 1071, 6205, 273, 374, 18, 15265, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 1071, 8694, 273, 20, 18, 3028, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 943, 49, 474, 273, 890, 31, 7010, 565, 2254, 5034, 1071, 943, 12236, 5349, 49, 474, 273, 576, 31, 7010, 203, 565, 1426, 1071, 272, 5349, 3896, 33, 629, 31, 203, 565, 1426, 1071, 4075, 5349, 3896, 33, 629, 31, 203, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 389, 7860, 49, 474, 18696, 1887, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 1071, 87, 5349, 1887, 49, 474, 329, 31, 203, 565, 1731, 1578, 1071, 4075, 5349, 8478, 15609, 2375, 33, 20, 92, 28, 73, 2138, 1077, 5540, 72, 5608, 73, 22, 2163, 69, 4449, 5292, 71, 7140, 71, 29, 73, 21, 71, 6418, 29, 1727, 6669, 5608, 71, 24, 72, 6030, 27, 2196, 5608, 72, 23, 72, 22, 2733, 4366, 21, 70, 7616, 71, 25, 30886, 31, 203, 565, 1731, 1578, 1071, 776, 625, 8478, 15609, 2375, 33, 20, 92, 361, 1727, 7201, 70, 10321, 5082, 71, 28, 73, 3028, 713, 69, 6030, 1105, 557, 70, 27, 74, 7616, 73, 20, 4315, 26, 5353, 27, 4033, 2 ]
pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { // Result must be a positive or zero assert(b <= a); return a - b; } function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); // Result must be a positive or zero if (0 < c) c = 0; return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } contract Ownable { address public owner; // The Ownable constructor sets the original `owner` of the contract to the sender account. function Ownable() { owner = msg.sender; } // Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } } /** * Main contract: * *) You can refund eth*3 only between "refundTime" and "ownerTime". * *) The creator can only get the contract balance after "ownerTime". * *) IMPORTANT! If the contract balance is less (you eth*3) then you get only half of the balance. * *) For 3x refund you must pay a fee 0.1 Eth. */ contract Multiple3x is Ownable{ using SafeMath for uint256; mapping (address=>uint) public deposits; uint public refundTime = 1507719600; // GMT: 11 October 2017, 11:00 uint public ownerTime = (refundTime + 1 minutes); // +1 minute uint maxDeposit = 1 ether; uint minDeposit = 100 finney; // 0.1 eth function() payable { deposit(); } function deposit() payable { require(now < refundTime); require(msg.value >= minDeposit); uint256 dep = deposits[msg.sender]; uint256 sumDep = msg.value.add(dep); if (sumDep > maxDeposit){ msg.sender.send(sumDep.sub(maxDeposit)); // return of overpaid eth deposits[msg.sender] = maxDeposit; } else{ deposits[msg.sender] = sumDep; } } function refund() payable { require(now >= refundTime && now < ownerTime); require(msg.value >= 100 finney); // fee for refund uint256 dep = deposits[msg.sender]; uint256 depHalf = this.balance.div(2); uint256 dep3x = dep.mul(3); deposits[msg.sender] = 0; if (this.balance > 0 && dep3x > 0){ if (dep3x > this.balance){ msg.sender.send(dep3x); // refund 3x } else{ msg.sender.send(depHalf); // refund half of balance } } } function refundOwner() { require(now >= ownerTime); if(owner.send(this.balance)){ suicide(owner); } } }
refund half of balance
msg.sender.send(depHalf);
12,576,079
[ 1, 1734, 1074, 8816, 434, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 1234, 18, 15330, 18, 4661, 12, 15037, 16168, 1769, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xc3E9E42DE399F50C5Fc2BC971f0b8D10A631688D/sources/contracts/p1/RToken.sol
Mint an amount of RToken equivalent to amtBaskets and scale basketsNeeded up @param recipient The address to receive the RTokens @param amtBaskets {BU} The number of amtBaskets to mint RToken for @param totalSupply {qRTok} The current totalSupply effects: bal'[recipient] = bal[recipient] + amtRToken totalSupply' = totalSupply + amtRToken basketsNeeded' = basketsNeeded + amtBaskets BU exchange rate cannot decrease, and it can only increase when < FIX_ONE. take advantage of 18 decimals during casting Mint RToken to recipient
function _scaleUp( address recipient, uint192 amtBaskets, uint256 totalSupply ) private { uint256 amtRToken = totalSupply > 0 emit BasketsNeededChanged(basketsNeeded, basketsNeeded + amtBaskets); basketsNeeded += amtBaskets; _mint(recipient, amtRToken); }
16,435,920
[ 1, 49, 474, 392, 3844, 434, 534, 1345, 7680, 358, 25123, 38, 835, 2413, 471, 3159, 324, 835, 2413, 11449, 731, 225, 8027, 1021, 1758, 358, 6798, 326, 534, 5157, 225, 25123, 38, 835, 2413, 288, 3000, 97, 1021, 1300, 434, 25123, 38, 835, 2413, 358, 312, 474, 534, 1345, 364, 225, 2078, 3088, 1283, 288, 85, 12185, 601, 97, 1021, 783, 2078, 3088, 1283, 16605, 30, 282, 324, 287, 11, 63, 20367, 65, 273, 324, 287, 63, 20367, 65, 397, 25123, 54, 1345, 282, 2078, 3088, 1283, 11, 273, 2078, 3088, 1283, 397, 25123, 54, 1345, 282, 324, 835, 2413, 11449, 11, 273, 324, 835, 2413, 11449, 397, 25123, 38, 835, 2413, 10937, 7829, 4993, 2780, 20467, 16, 471, 518, 848, 1338, 10929, 1347, 411, 8563, 67, 5998, 18, 4862, 1261, 7445, 410, 434, 6549, 15105, 4982, 27660, 490, 474, 534, 1345, 358, 8027, 2, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5864, 1211, 12, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 15561, 25123, 38, 835, 2413, 16, 203, 3639, 2254, 5034, 2078, 3088, 1283, 203, 565, 262, 3238, 288, 203, 3639, 2254, 5034, 25123, 54, 1345, 273, 2078, 3088, 1283, 405, 374, 203, 3639, 3626, 605, 835, 2413, 11449, 5033, 12, 70, 835, 2413, 11449, 16, 324, 835, 2413, 11449, 397, 25123, 38, 835, 2413, 1769, 203, 3639, 324, 835, 2413, 11449, 1011, 25123, 38, 835, 2413, 31, 203, 203, 3639, 389, 81, 474, 12, 20367, 16, 25123, 54, 1345, 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 ]
./partial_match/1/0x5CaB28E60A8aA4E1DE012293b862e32730D69473/sources/BOCI.sol
Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract BOCI is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; mapping (address => uint256) private _holderFirstBuyTimestamp; mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; uint256 launchedAt; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("BOCI", unicode"中银国际") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 10; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 20; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 90000000000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0xDEc8C333dA21a3645C48D1627878aCa69B315447); devWallet = address(0xDEc8C333dA21a3645C48D1627878aCa69B315447); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(address(marketingWallet), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(address(devWallet), true); excludeFromMaxTransaction(address(marketingWallet), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateBuyFees( uint256 _devFee, uint256 _liquidityFee, uint256 _marketingFee ) external onlyOwner { buyDevFee = _devFee; buyLiquidityFee = _liquidityFee; buyMarketingFee = _marketingFee; buyTotalFees = buyDevFee + buyLiquidityFee + buyMarketingFee; } function updateSellFees( uint256 _devFee, uint256 _liquidityFee, uint256 _marketingFee ) external onlyOwner { sellDevFee = _devFee; sellLiquidityFee = _liquidityFee; sellMarketingFee = _marketingFee; sellTotalFees = sellDevFee + sellLiquidityFee + sellMarketingFee; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); }
3,616,646
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4352, 749, 1635, 22467, 1098, 1635, 1203, 1300, 434, 10191, 1284, 7459, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 9784, 7266, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 3238, 13667, 310, 16936, 31, 203, 565, 1758, 3238, 4461, 16936, 31, 203, 7010, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 7010, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 7010, 7010, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3759, 38, 9835, 4921, 31, 203, 7010, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 22491, 31, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 7010, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 8870, 14667, 31, 203, 7010, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 48, 18988, 24237, 14667, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@api3/protocol/contracts/authorizers/Api3Authorizer.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/IApi3Token.sol"; import "./interfaces/IApi3TokenLockExternal.sol"; /// @title The contract used to lock API3 Tokens in order to gain access to Airnodes contract Api3TokenLockExternal is IApi3TokenLockExternal, Ownable { string private constant ERROR_UNAUTHORIZED = "Unauthorized"; string private constant ERROR_ZERO_ADDRESS = "Zero address"; string private constant ERROR_ZERO_AMOUNT = "Zero amount"; string private constant ERROR_INSUFFICIENT_AMOUNT = "Insufficient amount"; string private constant ERROR_ALREADY_LOCKED = "Already locked"; string private constant ERROR_NOT_LOCKED = "No amount locked"; string private constant ERROR_LOCK_PERIOD_NOT_EXPIRED = "Locking period not expired"; string private constant ERROR_LOCK_PERIOD_ZERO = "Zero lock period"; string private constant ERROR_CLIENT_BLACKLISTED = "Client blacklisted"; string private constant ERROR_CLIENT_NOT_BLACKLISTED = "Client not blacklisted"; /// @dev Address of Api3Token address public api3Token; /// @dev The Minimum locking time (in seconds) uint256 public minimumLockingTime; /// @dev Lock amount for each user uint256 public lockAmount; /// @dev Represents the locked amounts, periods and whitelist counts /// of a chainId-airnode-client pair struct AirnodeClient { mapping(address => uint256) lockAmountAt; mapping(address => uint256) canUnlockAt; uint256 whitelistCount; } /// @dev Meta admin sets the admin statuses of addresses and has super /// admin privileges address public metaAdmin; /// @dev Stores information about admins mapping(address => AdminStatus) public adminStatuses; /// @dev Stores information about all token locks for chainId-airnode-client pair mapping(uint256 => mapping(bytes32 => mapping(address => AirnodeClient))) public tokenLocks; /// @dev Stores information for blacklisted clients mapping(address => bool) public clientAddressToBlacklistStatus; /// @dev Sets the values for {_metaAdmin}, {_minimumLockingTime} and {_lockAmount} /// @param _metaAdmin The address that will be set as meta admin /// @param _minimumLockingTime The minimum lock time of API3 tokens for users /// @param _lockAmount The lock amount constructor( address _metaAdmin, uint256 _minimumLockingTime, uint256 _lockAmount ) { require(_metaAdmin != address(0), ERROR_ZERO_ADDRESS); require(_lockAmount != 0, ERROR_ZERO_AMOUNT); minimumLockingTime = _minimumLockingTime; lockAmount = _lockAmount; metaAdmin = _metaAdmin; } /// @notice Called by the meta admin to set the meta admin /// @param _metaAdmin Address that will be set as the meta admin function setMetaAdmin(address _metaAdmin) external override { require(msg.sender == metaAdmin, ERROR_UNAUTHORIZED); require(_metaAdmin != address(0), ERROR_ZERO_ADDRESS); metaAdmin = _metaAdmin; emit SetMetaAdmin(metaAdmin); } /// @notice Called by the meta admin to set the admin status of an address /// @param _admin Address whose admin status will be set /// @param _status Admin status function setAdminStatus(address _admin, AdminStatus _status) external override { require(msg.sender == metaAdmin, ERROR_UNAUTHORIZED); adminStatuses[_admin] = _status; emit SetAdminStatus(_admin, _status); } /// @notice Called by admin to set the address of the API3 Token /// @param _api3Token Address of the new API3 Token function setApi3Token(address _api3Token) external override { require( adminStatuses[msg.sender] == AdminStatus.Admin, ERROR_UNAUTHORIZED ); require(_api3Token != address(0), ERROR_ZERO_ADDRESS); api3Token = _api3Token; bool isBurner = IApi3Token(api3Token).getBurnerStatus(address(this)); if (!isBurner) { IApi3Token(api3Token).updateBurnerStatus(true); } emit SetApi3Token(api3Token); } /// @notice Called by owner to set the minimum locking time /// @param _minimumLockingTime The new minimum locking time function setMinimumLockingTime(uint256 _minimumLockingTime) external override onlyOwner { minimumLockingTime = _minimumLockingTime; emit SetMinimumLockingTime(_minimumLockingTime); } /// @notice Called by owner to set the locking amount /// @param _lockAmount The new lock amount function setLockAmount(uint256 _lockAmount) external override onlyOwner { require(_lockAmount != 0, ERROR_ZERO_AMOUNT); lockAmount = _lockAmount; emit SetLockAmount(_lockAmount); } /// @notice Called by owner to set the blacklist status of a client /// @param clientAddress Client address /// @param status Blacklist status to be set function setBlacklistStatus(address clientAddress, bool status) external override onlyOwner { clientAddressToBlacklistStatus[clientAddress] = status; emit SetBlacklistStatus(clientAddress, status, msg.sender); } /// @notice Locks API3 Tokens to gain access to Airnodes on a given chain. /// Airnode-client pair gets authorized as long as there is at least one token lock for given pair. /// @dev The amount to be locked is determined by a memory variable set by /// the owners of the contract. /// @param _chainId The chain id /// @param _airnodeId The airnode id /// @param _clientAddress The client address function lock( uint256 _chainId, bytes32 _airnodeId, address _clientAddress ) external override { AirnodeClient storage target = tokenLocks[_chainId][_airnodeId][ _clientAddress ]; require(target.lockAmountAt[msg.sender] == 0, ERROR_ALREADY_LOCKED); require( !clientAddressToBlacklistStatus[_clientAddress], ERROR_CLIENT_BLACKLISTED ); uint256 expirationTime = block.timestamp + minimumLockingTime; target.lockAmountAt[msg.sender] = lockAmount; target.canUnlockAt[msg.sender] = expirationTime; target.whitelistCount++; assert( IApi3Token(api3Token).transferFrom( msg.sender, address(this), lockAmount ) ); if (target.whitelistCount == 1) { emit Authorize( _chainId, _airnodeId, _clientAddress, type(uint256).max ); } emit Lock(_chainId, _airnodeId, _clientAddress, msg.sender, lockAmount); } /// @notice Unlocks the API3 tokens for a given airnode-client pair on a given chain. /// Airnode-client pair will be unauthorized if no token lock for the pair is found. /// @dev Checks whether the user (msg.sender) has already locked anything, /// if the locked period has expired and if the client address is blacklisted /// Transfers to msg.sender the locked amount. /// @param _chainId The chain id /// @param _airnodeId The airnode id /// @param _clientAddress The client address function unlock( uint256 _chainId, bytes32 _airnodeId, address _clientAddress ) external override { AirnodeClient storage target = tokenLocks[_chainId][_airnodeId][ _clientAddress ]; require(target.lockAmountAt[msg.sender] != 0, ERROR_NOT_LOCKED); require(target.canUnlockAt[msg.sender] != 0, ERROR_LOCK_PERIOD_ZERO); require( target.canUnlockAt[msg.sender] <= block.timestamp, ERROR_LOCK_PERIOD_NOT_EXPIRED ); require( !clientAddressToBlacklistStatus[_clientAddress], ERROR_CLIENT_BLACKLISTED ); uint256 amount = target.lockAmountAt[msg.sender]; target.lockAmountAt[msg.sender] = 0; target.canUnlockAt[msg.sender] = 0; target.whitelistCount--; if (target.whitelistCount == 0) { emit Authorize(_chainId, _airnodeId, _clientAddress, 0); } assert(IApi3Token(api3Token).transfer(msg.sender, amount)); emit Unlock(_chainId, _airnodeId, _clientAddress, msg.sender, amount); } /// @notice User calls this when the lock amount has been decreased and wants /// to withdraw the redundantly locked tokens /// @param _chainId The chain id /// @param _airnodeId The airnode id /// @param _clientAddress The client address function withdraw( uint256 _chainId, bytes32 _airnodeId, address _clientAddress ) external override { require( tokenLocks[_chainId][_airnodeId][_clientAddress].lockAmountAt[ msg.sender ] > lockAmount, ERROR_INSUFFICIENT_AMOUNT ); require( !clientAddressToBlacklistStatus[_clientAddress], ERROR_CLIENT_BLACKLISTED ); uint256 withdrawAmount = tokenLocks[_chainId][_airnodeId][ _clientAddress ] .lockAmountAt[msg.sender] - lockAmount; tokenLocks[_chainId][_airnodeId][_clientAddress].lockAmountAt[ msg.sender ] = lockAmount; assert(IApi3Token(api3Token).transfer(msg.sender, withdrawAmount)); emit Withdraw( _chainId, _airnodeId, _clientAddress, msg.sender, withdrawAmount ); } /// @notice Transfers the user's lock period and tokens to another client /// @param _chainId The chain id /// @param _airnodeId The airnode id /// @param _fromClientAddress The client from which the transfer will be done /// @param _toClientAddress The target client to which the transfer will be done function transfer( uint256 _chainId, bytes32 _airnodeId, address _fromClientAddress, address _toClientAddress ) external override { AirnodeClient storage from = tokenLocks[_chainId][_airnodeId][ _fromClientAddress ]; AirnodeClient storage to = tokenLocks[_chainId][_airnodeId][ _toClientAddress ]; require( from.lockAmountAt[msg.sender] != 0, "locked amount must be != 0" ); require(to.lockAmountAt[msg.sender] == 0, "locked amount must be 0"); require( !clientAddressToBlacklistStatus[_fromClientAddress], "From Client blacklisted" ); require( !clientAddressToBlacklistStatus[_toClientAddress], "To Client blacklisted" ); uint256 amount = from.lockAmountAt[msg.sender]; from.lockAmountAt[msg.sender] = 0; to.lockAmountAt[msg.sender] = amount; uint256 expirationTime = from.canUnlockAt[msg.sender]; from.canUnlockAt[msg.sender] = 0; to.canUnlockAt[msg.sender] = expirationTime; from.whitelistCount--; if (from.whitelistCount == 0) { emit Authorize(_chainId, _airnodeId, _fromClientAddress, 0); } to.whitelistCount++; if (to.whitelistCount == 1) { emit Authorize( _chainId, _airnodeId, _toClientAddress, type(uint256).max ); } emit Transfer( _chainId, _airnodeId, _fromClientAddress, _toClientAddress, msg.sender, amount, expirationTime ); } /// @notice Burns tokens for a user of an airnode-client pair. /// Can only be done when the client is blacklisted. /// @param _chainId The chain id /// @param _airnodeId The airnode id /// @param _clientAddress The client address /// @param _burnTarget The address of the user function burn( uint256 _chainId, bytes32 _airnodeId, address _clientAddress, address _burnTarget ) external override { AirnodeClient storage target = tokenLocks[_chainId][_airnodeId][ _clientAddress ]; require(target.lockAmountAt[_burnTarget] != 0, ERROR_ZERO_AMOUNT); require( clientAddressToBlacklistStatus[_clientAddress], ERROR_CLIENT_NOT_BLACKLISTED ); uint256 amount = target.lockAmountAt[_burnTarget]; target.canUnlockAt[_burnTarget] = 0; target.lockAmountAt[_burnTarget] = 0; target.whitelistCount--; if (target.whitelistCount == 0) { emit Authorize(_chainId, _airnodeId, _clientAddress, 0); } IApi3Token(api3Token).burn(amount); emit Burn(_chainId, _airnodeId, _clientAddress, _burnTarget); } /// @dev Returns the locked amount for a target address to a chainId-airnode-client /// @param _chainId The chain id /// @param _airnodeId The airnode id /// @param _clientAddress The client address /// @param _target The address of the user function lockAmountAt( uint256 _chainId, bytes32 _airnodeId, address _clientAddress, address _target ) public view returns (uint256) { return tokenLocks[_chainId][_airnodeId][_clientAddress].lockAmountAt[ _target ]; } /// @dev Returns the unlock period for a target address to a chainId-airnode-client /// @param _chainId The chain id /// @param _airnodeId The airnode id /// @param _clientAddress The client address /// @param _target The address of the user function canUnlockAt( uint256 _chainId, bytes32 _airnodeId, address _clientAddress, address _target ) public view returns (uint256) { return tokenLocks[_chainId][_airnodeId][_clientAddress].canUnlockAt[ _target ]; } }
@notice Burns tokens for a user of an airnode-client pair. Can only be done when the client is blacklisted. @param _chainId The chain id @param _airnodeId The airnode id @param _clientAddress The client address @param _burnTarget The address of the user
function burn( uint256 _chainId, bytes32 _airnodeId, address _clientAddress, address _burnTarget ) external override { AirnodeClient storage target = tokenLocks[_chainId][_airnodeId][ _clientAddress ]; require(target.lockAmountAt[_burnTarget] != 0, ERROR_ZERO_AMOUNT); require( clientAddressToBlacklistStatus[_clientAddress], ERROR_CLIENT_NOT_BLACKLISTED ); uint256 amount = target.lockAmountAt[_burnTarget]; target.canUnlockAt[_burnTarget] = 0; target.lockAmountAt[_burnTarget] = 0; target.whitelistCount--; if (target.whitelistCount == 0) { emit Authorize(_chainId, _airnodeId, _clientAddress, 0); } IApi3Token(api3Token).burn(amount); emit Burn(_chainId, _airnodeId, _clientAddress, _burnTarget); }
1,028,425
[ 1, 38, 321, 87, 2430, 364, 279, 729, 434, 392, 23350, 2159, 17, 2625, 3082, 18, 4480, 1338, 506, 2731, 1347, 326, 1004, 353, 25350, 18, 225, 389, 5639, 548, 1021, 2687, 612, 225, 389, 1826, 2159, 548, 1021, 23350, 2159, 612, 225, 389, 2625, 1887, 1021, 1004, 1758, 225, 389, 70, 321, 2326, 1021, 1758, 434, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 18305, 12, 203, 3639, 2254, 5034, 389, 5639, 548, 16, 203, 3639, 1731, 1578, 389, 1826, 2159, 548, 16, 203, 3639, 1758, 389, 2625, 1887, 16, 203, 3639, 1758, 389, 70, 321, 2326, 203, 565, 262, 3903, 3849, 288, 203, 3639, 432, 481, 2159, 1227, 2502, 1018, 273, 1147, 19159, 63, 67, 5639, 548, 6362, 67, 1826, 2159, 548, 6362, 203, 5411, 389, 2625, 1887, 203, 3639, 308, 31, 203, 3639, 2583, 12, 3299, 18, 739, 6275, 861, 63, 67, 70, 321, 2326, 65, 480, 374, 16, 5475, 67, 24968, 67, 2192, 51, 5321, 1769, 203, 3639, 2583, 12, 203, 5411, 1004, 1887, 774, 25811, 1482, 63, 67, 2625, 1887, 6487, 203, 5411, 5475, 67, 11935, 67, 4400, 67, 14618, 3649, 7085, 2056, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 3844, 273, 1018, 18, 739, 6275, 861, 63, 67, 70, 321, 2326, 15533, 203, 203, 3639, 1018, 18, 4169, 7087, 861, 63, 67, 70, 321, 2326, 65, 273, 374, 31, 203, 3639, 1018, 18, 739, 6275, 861, 63, 67, 70, 321, 2326, 65, 273, 374, 31, 203, 3639, 1018, 18, 20409, 1380, 413, 31, 203, 203, 3639, 309, 261, 3299, 18, 20409, 1380, 422, 374, 13, 288, 203, 5411, 3626, 23859, 24899, 5639, 548, 16, 389, 1826, 2159, 548, 16, 389, 2625, 1887, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 467, 3064, 23, 1345, 12, 2425, 23, 1345, 2934, 70, 321, 12, 8949, 1769, 203, 203, 3639, 3626, 605, 321, 24899, 5639, 548, 16, 389, 1826, 2159, 548, 16, 2 ]
./full_match/1/0xDd5097FC3f68958649cE70F42B7c1CF0067a3545/sources/cache/solpp-generated-contracts/ZkLink.sol
@notice Checks that signature is valid for pubkey change message salt from CREATE2 specification Address computation according to CREATE2 definition: https:eips.ethereum.org/EIPS/eip-1014 This type of change pubkey can be done only once(when the account is not active)
function verifyChangePubkeyCREATE2(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { address creatorAddress; bytes32 codeHash; (offset, creatorAddress) = Bytes.readAddress(_ethWitness, offset); (offset, saltArg) = Bytes.readBytes32(_ethWitness, offset); (offset, codeHash) = Bytes.readBytes32(_ethWitness, offset); bytes32 salt = keccak256(abi.encodePacked(saltArg, _changePk.pubKeyHash)); address recoveredAddress = address( uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), creatorAddress, salt, codeHash)))) ); return recoveredAddress == _changePk.owner && _changePk.nonce == 0; }
16,530,417
[ 1, 4081, 716, 3372, 353, 923, 364, 15649, 2549, 883, 4286, 628, 13278, 22, 7490, 5267, 16039, 4888, 358, 13278, 22, 2379, 30, 2333, 30, 73, 7146, 18, 546, 822, 379, 18, 3341, 19, 41, 2579, 55, 19, 73, 625, 17, 15168, 24, 1220, 618, 434, 2549, 15649, 848, 506, 2731, 1338, 3647, 12, 13723, 326, 2236, 353, 486, 2695, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 3929, 3043, 9581, 856, 9344, 22, 12, 3890, 3778, 389, 546, 24007, 16, 25938, 18, 3043, 17924, 3778, 389, 3427, 7789, 13, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 1758, 11784, 1887, 31, 203, 3639, 1731, 1578, 981, 2310, 31, 203, 3639, 261, 3348, 16, 11784, 1887, 13, 273, 5985, 18, 896, 1887, 24899, 546, 24007, 16, 1384, 1769, 203, 3639, 261, 3348, 16, 4286, 4117, 13, 273, 5985, 18, 896, 2160, 1578, 24899, 546, 24007, 16, 1384, 1769, 203, 3639, 261, 3348, 16, 981, 2310, 13, 273, 5985, 18, 896, 2160, 1578, 24899, 546, 24007, 16, 1384, 1769, 203, 3639, 1731, 1578, 4286, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 5759, 4117, 16, 389, 3427, 7789, 18, 10174, 653, 2310, 10019, 203, 3639, 1758, 24616, 1887, 273, 1758, 12, 203, 5411, 2254, 16874, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3890, 21, 12, 20, 5297, 3631, 11784, 1887, 16, 4286, 16, 981, 2310, 3719, 3719, 203, 3639, 11272, 203, 3639, 327, 24616, 1887, 422, 389, 3427, 7789, 18, 8443, 597, 389, 3427, 7789, 18, 12824, 422, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xB720f409d43b490F6aeE1D9048797B8C19A3Ac06/sources/contracts/BrewlabsAggregationRouter.sol
Explore options that connect the current path to the tokenOut
Offer memory newOffer = _cloneOffer(_queries);
4,474,640
[ 1, 2966, 383, 266, 702, 716, 3077, 326, 783, 589, 358, 326, 1147, 1182, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 25753, 3778, 394, 10513, 273, 389, 14056, 10513, 24899, 13748, 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 ]