file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./full_match/1/0x05099C7CAeD7A1aF46F946DC79b618285047D991/sources/contracts/Dopamine.sol
remove limits after token is stable
function removeLimits() external onlyOwner { limitsActive = false; }
9,737,928
[ 1, 4479, 8181, 1839, 1147, 353, 14114, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1206, 12768, 1435, 3903, 1338, 5541, 288, 203, 3639, 8181, 3896, 273, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Board.sol // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; /// @dev for tests only contract BoardGameStrategistTest { /// @dev structure used to store pawn's attribute struct PawnInfo { uint256 random; uint8 position; bool isOnBoard; bool isPropertyBought; bool isRentPaid; bool isRoundCompleted; bool isInJail; bool isChanceCard; bool isCommunityCard; } /// @dev structure used to store pawn's attribute struct BoardInfo { uint8 nbOfLands; uint8 rarityLevel; mapping(uint8 => bool) isPurchasable; mapping(uint256 => PawnInfo) pawns; uint16 nb_pawns_max; uint16 nb_pawns; } /// @dev number of board editions uint16 private editionMax; uint256 public pawnID; /// @dev store all boards by edition number mapping(uint16 => BoardInfo) public boards; constructor() { editionMax = 0; // Paris edition (0) BoardInfo storage b = boards[0]; b.nbOfLands = 40; b.nb_pawns_max = 1000; b.rarityLevel = 2; uint8[10] memory notPurchasableLands = [0, 2, 7, 10, 17, 20, 22, 30, 33, 36]; for (uint8 landID; landID < b.nbOfLands; landID++) { b.isPurchasable[landID] = true; for (uint8 n; n < notPurchasableLands.length; n++) { if (landID == notPurchasableLands[n]) { b.isPurchasable[landID] = false; break; } } } // Pawn initialization pawnID = uint256(0xd2ae2067bef5ced912dc3639bf77575813758210bc98a7f3fb3f9f29d852d39f); b.pawns[pawnID].isOnBoard = true; b.pawns[pawnID].isRoundCompleted = true; } /** @dev Game strategist * @param _edition board edition * @param _pawnID pawn ID*/ function gameStrategist(uint16 _edition, uint256 _pawnID, uint8 _position) external { // Purchasable lands if (boards[_edition].isPurchasable[_position]) { boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } // Go to jail if (_position == 30) { boards[_edition].pawns[_pawnID].isInJail = true; boards[_edition].pawns[_pawnID].position = 10; return; } // Free park if (_position == 20) { return; } // Jail simple visit if (_position == 10) { return; } // Chance card if (_position == 7 || _position == 22 || _position == 36 ) { boards[_edition].pawns[_pawnID].isChanceCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } // Community chest card if (_position == 2 || _position == 17 || _position == 33 ) { boards[_edition].pawns[_pawnID].isCommunityCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } // Go case // Nothing is implemented when a player pass over Go. } /** check if a land can be bought (PROP tokens available) * @param edition board edition * @param land cell number * @return true or false*/ function isPurchasable(uint16 edition, uint8 land) external view returns (bool) { return boards[edition].isPurchasable[land]; } /** get Pawn information on a board * @param _edition board edition * @param _pawnID pawn ID * @return p Pawn information*/ function getPawnInfo(uint16 _edition, uint256 _pawnID) external view returns (PawnInfo memory p) { return boards[_edition].pawns[_pawnID]; } /** set Pawn information on a board * @param _edition board edition * @param _pawnID pawn ID * @param _pawnInfo pawn information*/ function setPawnInfo( uint16 _edition, uint256 _pawnID, PawnInfo memory _pawnInfo ) external { boards[_edition].pawns[_pawnID] = _pawnInfo; } ///@dev for tests function setPosition( uint16 _edition, uint256 _pawnID, uint8 _position ) external { boards[_edition].pawns[_pawnID].position = _position; boards[_edition].pawns[_pawnID].isPropertyBought = false; boards[_edition].pawns[_pawnID].isRentPaid = false; boards[_edition].pawns[_pawnID].isInJail = false; boards[_edition].pawns[_pawnID].isChanceCard = false; boards[_edition].pawns[_pawnID].isCommunityCard = false; boards[_edition].pawns[_pawnID].isRoundCompleted = true; } }
@dev for tests only
contract BoardGameStrategistTest { pragma solidity 0.8.10; struct PawnInfo { uint256 random; uint8 position; bool isOnBoard; bool isPropertyBought; bool isRentPaid; bool isRoundCompleted; bool isInJail; bool isChanceCard; bool isCommunityCard; } struct BoardInfo { uint8 nbOfLands; uint8 rarityLevel; mapping(uint8 => bool) isPurchasable; mapping(uint256 => PawnInfo) pawns; uint16 nb_pawns_max; uint16 nb_pawns; } uint256 public pawnID; uint16 private editionMax; mapping(uint16 => BoardInfo) public boards; constructor() { editionMax = 0; BoardInfo storage b = boards[0]; b.nbOfLands = 40; b.nb_pawns_max = 1000; b.rarityLevel = 2; uint8[10] memory notPurchasableLands = [0, 2, 7, 10, 17, 20, 22, 30, 33, 36]; for (uint8 landID; landID < b.nbOfLands; landID++) { b.isPurchasable[landID] = true; for (uint8 n; n < notPurchasableLands.length; n++) { if (landID == notPurchasableLands[n]) { b.isPurchasable[landID] = false; break; } } } b.pawns[pawnID].isOnBoard = true; b.pawns[pawnID].isRoundCompleted = true; } constructor() { editionMax = 0; BoardInfo storage b = boards[0]; b.nbOfLands = 40; b.nb_pawns_max = 1000; b.rarityLevel = 2; uint8[10] memory notPurchasableLands = [0, 2, 7, 10, 17, 20, 22, 30, 33, 36]; for (uint8 landID; landID < b.nbOfLands; landID++) { b.isPurchasable[landID] = true; for (uint8 n; n < notPurchasableLands.length; n++) { if (landID == notPurchasableLands[n]) { b.isPurchasable[landID] = false; break; } } } b.pawns[pawnID].isOnBoard = true; b.pawns[pawnID].isRoundCompleted = true; } constructor() { editionMax = 0; BoardInfo storage b = boards[0]; b.nbOfLands = 40; b.nb_pawns_max = 1000; b.rarityLevel = 2; uint8[10] memory notPurchasableLands = [0, 2, 7, 10, 17, 20, 22, 30, 33, 36]; for (uint8 landID; landID < b.nbOfLands; landID++) { b.isPurchasable[landID] = true; for (uint8 n; n < notPurchasableLands.length; n++) { if (landID == notPurchasableLands[n]) { b.isPurchasable[landID] = false; break; } } } b.pawns[pawnID].isOnBoard = true; b.pawns[pawnID].isRoundCompleted = true; } constructor() { editionMax = 0; BoardInfo storage b = boards[0]; b.nbOfLands = 40; b.nb_pawns_max = 1000; b.rarityLevel = 2; uint8[10] memory notPurchasableLands = [0, 2, 7, 10, 17, 20, 22, 30, 33, 36]; for (uint8 landID; landID < b.nbOfLands; landID++) { b.isPurchasable[landID] = true; for (uint8 n; n < notPurchasableLands.length; n++) { if (landID == notPurchasableLands[n]) { b.isPurchasable[landID] = false; break; } } } b.pawns[pawnID].isOnBoard = true; b.pawns[pawnID].isRoundCompleted = true; } pawnID = uint256(0xd2ae2067bef5ced912dc3639bf77575813758210bc98a7f3fb3f9f29d852d39f); function gameStrategist(uint16 _edition, uint256 _pawnID, uint8 _position) external { if (boards[_edition].isPurchasable[_position]) { boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } if (_position == 30) { boards[_edition].pawns[_pawnID].isInJail = true; boards[_edition].pawns[_pawnID].position = 10; return; } if (_position == 20) { return; } if (_position == 10) { return; } _position == 22 || _position == 36 ) { boards[_edition].pawns[_pawnID].isChanceCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } _position == 17 || _position == 33 ) { boards[_edition].pawns[_pawnID].isCommunityCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } function gameStrategist(uint16 _edition, uint256 _pawnID, uint8 _position) external { if (boards[_edition].isPurchasable[_position]) { boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } if (_position == 30) { boards[_edition].pawns[_pawnID].isInJail = true; boards[_edition].pawns[_pawnID].position = 10; return; } if (_position == 20) { return; } if (_position == 10) { return; } _position == 22 || _position == 36 ) { boards[_edition].pawns[_pawnID].isChanceCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } _position == 17 || _position == 33 ) { boards[_edition].pawns[_pawnID].isCommunityCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } function gameStrategist(uint16 _edition, uint256 _pawnID, uint8 _position) external { if (boards[_edition].isPurchasable[_position]) { boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } if (_position == 30) { boards[_edition].pawns[_pawnID].isInJail = true; boards[_edition].pawns[_pawnID].position = 10; return; } if (_position == 20) { return; } if (_position == 10) { return; } _position == 22 || _position == 36 ) { boards[_edition].pawns[_pawnID].isChanceCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } _position == 17 || _position == 33 ) { boards[_edition].pawns[_pawnID].isCommunityCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } function gameStrategist(uint16 _edition, uint256 _pawnID, uint8 _position) external { if (boards[_edition].isPurchasable[_position]) { boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } if (_position == 30) { boards[_edition].pawns[_pawnID].isInJail = true; boards[_edition].pawns[_pawnID].position = 10; return; } if (_position == 20) { return; } if (_position == 10) { return; } _position == 22 || _position == 36 ) { boards[_edition].pawns[_pawnID].isChanceCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } _position == 17 || _position == 33 ) { boards[_edition].pawns[_pawnID].isCommunityCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } function gameStrategist(uint16 _edition, uint256 _pawnID, uint8 _position) external { if (boards[_edition].isPurchasable[_position]) { boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } if (_position == 30) { boards[_edition].pawns[_pawnID].isInJail = true; boards[_edition].pawns[_pawnID].position = 10; return; } if (_position == 20) { return; } if (_position == 10) { return; } _position == 22 || _position == 36 ) { boards[_edition].pawns[_pawnID].isChanceCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } _position == 17 || _position == 33 ) { boards[_edition].pawns[_pawnID].isCommunityCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } if (_position == 7 || function gameStrategist(uint16 _edition, uint256 _pawnID, uint8 _position) external { if (boards[_edition].isPurchasable[_position]) { boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } if (_position == 30) { boards[_edition].pawns[_pawnID].isInJail = true; boards[_edition].pawns[_pawnID].position = 10; return; } if (_position == 20) { return; } if (_position == 10) { return; } _position == 22 || _position == 36 ) { boards[_edition].pawns[_pawnID].isChanceCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } _position == 17 || _position == 33 ) { boards[_edition].pawns[_pawnID].isCommunityCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } if (_position == 2 || function gameStrategist(uint16 _edition, uint256 _pawnID, uint8 _position) external { if (boards[_edition].isPurchasable[_position]) { boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } if (_position == 30) { boards[_edition].pawns[_pawnID].isInJail = true; boards[_edition].pawns[_pawnID].position = 10; return; } if (_position == 20) { return; } if (_position == 10) { return; } _position == 22 || _position == 36 ) { boards[_edition].pawns[_pawnID].isChanceCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } _position == 17 || _position == 33 ) { boards[_edition].pawns[_pawnID].isCommunityCard = true; boards[_edition].pawns[_pawnID].isRoundCompleted = false; return; } } function isPurchasable(uint16 edition, uint8 land) external view returns (bool) { return boards[edition].isPurchasable[land]; } function getPawnInfo(uint16 _edition, uint256 _pawnID) external view returns (PawnInfo memory p) { return boards[_edition].pawns[_pawnID]; } function setPawnInfo( uint16 _edition, uint256 _pawnID, PawnInfo memory _pawnInfo ) external { boards[_edition].pawns[_pawnID] = _pawnInfo; } function setPosition( uint16 _edition, uint256 _pawnID, uint8 _position ) external { boards[_edition].pawns[_pawnID].position = _position; boards[_edition].pawns[_pawnID].isPropertyBought = false; boards[_edition].pawns[_pawnID].isRentPaid = false; boards[_edition].pawns[_pawnID].isInJail = false; boards[_edition].pawns[_pawnID].isChanceCard = false; boards[_edition].pawns[_pawnID].isCommunityCard = false; boards[_edition].pawns[_pawnID].isRoundCompleted = true; } }
5,526,119
[ 1, 1884, 7434, 1338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 17980, 1060, 12496, 1585, 1287, 376, 4709, 288, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 2163, 31, 203, 202, 1697, 453, 9533, 966, 288, 203, 202, 202, 11890, 5034, 2744, 31, 203, 202, 202, 11890, 28, 1754, 31, 203, 202, 202, 6430, 28181, 22233, 31, 203, 202, 202, 6430, 353, 1396, 13809, 9540, 31, 203, 202, 202, 6430, 353, 54, 319, 16507, 350, 31, 203, 202, 202, 6430, 353, 11066, 9556, 31, 203, 202, 202, 6430, 8048, 46, 671, 31, 203, 202, 202, 6430, 353, 782, 1359, 6415, 31, 203, 202, 202, 6430, 353, 12136, 13352, 6415, 31, 203, 202, 97, 203, 203, 202, 1697, 17980, 1060, 966, 288, 203, 202, 202, 11890, 28, 4264, 951, 48, 5708, 31, 203, 202, 202, 11890, 28, 436, 20498, 2355, 31, 203, 202, 202, 6770, 12, 11890, 28, 516, 1426, 13, 353, 10262, 343, 345, 429, 31, 203, 202, 202, 6770, 12, 11890, 5034, 516, 453, 9533, 966, 13, 293, 2219, 2387, 31, 203, 202, 202, 11890, 2313, 4264, 67, 84, 2219, 2387, 67, 1896, 31, 203, 202, 202, 11890, 2313, 4264, 67, 84, 2219, 2387, 31, 203, 202, 97, 203, 203, 203, 202, 11890, 5034, 1071, 293, 9533, 734, 31, 203, 203, 203, 202, 11890, 2313, 3238, 28432, 2747, 31, 203, 202, 6770, 12, 11890, 2313, 516, 17980, 1060, 966, 13, 1071, 11094, 87, 31, 203, 202, 12316, 1435, 288, 203, 202, 202, 329, 608, 2747, 273, 374, 31, 203, 203, 202, 202, 22233, 966, 2502, 324, 273, 11094, 87, 63, 20, 15533, 2 ]
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; // Inheritance import "./Owned.sol"; import "./MixinResolver.sol"; import "./MixinSystemSettings.sol"; import "./interfaces/ISynthetixBridgeToBase.sol"; // Internal references import "./interfaces/ISynthetix.sol"; import "./interfaces/IRewardEscrowV2.sol"; import "./interfaces/ISynthetixBridgeToOptimism.sol"; // solhint-disable indent import "@eth-optimism/contracts/build/contracts/iOVM/bridge/iOVM_BaseCrossDomainMessenger.sol"; contract SynthetixBridgeToBase is Owned, MixinSystemSettings, ISynthetixBridgeToBase { /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_EXT_MESSENGER = "ext:Messenger"; bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix"; bytes32 private constant CONTRACT_REWARDESCROW = "RewardEscrowV2"; bytes32 private constant CONTRACT_BASE_SYNTHETIXBRIDGETOOPTIMISM = "base:SynthetixBridgeToOptimism"; // ========== CONSTRUCTOR ========== constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} // // ========== INTERNALS ============ function messenger() internal view returns (iOVM_BaseCrossDomainMessenger) { return iOVM_BaseCrossDomainMessenger(requireAndGetAddress(CONTRACT_EXT_MESSENGER)); } function synthetix() internal view returns (ISynthetix) { return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX)); } function rewardEscrowV2() internal view returns (IRewardEscrowV2) { return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW)); } function synthetixBridgeToOptimism() internal view returns (address) { return requireAndGetAddress(CONTRACT_BASE_SYNTHETIXBRIDGETOOPTIMISM); } function onlyAllowFromOptimism() internal view { // ensure function only callable from the L2 bridge via messenger (aka relayer) iOVM_BaseCrossDomainMessenger _messenger = messenger(); require(msg.sender == address(_messenger), "Only the relayer can call this"); require(_messenger.xDomainMessageSender() == synthetixBridgeToOptimism(), "Only the L1 bridge can invoke"); } modifier onlyOptimismBridge() { onlyAllowFromOptimism(); _; } // ========== VIEWS ========== function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](4); newAddresses[0] = CONTRACT_EXT_MESSENGER; newAddresses[1] = CONTRACT_SYNTHETIX; newAddresses[2] = CONTRACT_BASE_SYNTHETIXBRIDGETOOPTIMISM; newAddresses[3] = CONTRACT_REWARDESCROW; addresses = combineArrays(existingAddresses, newAddresses); } // ========== PUBLIC FUNCTIONS ========= // invoked by user on L2 function initiateWithdrawal(uint amount) external { require(synthetix().transferableSynthetix(msg.sender) >= amount, "Not enough transferable SNX"); // instruct L2 Synthetix to burn this supply synthetix().burnSecondary(msg.sender, amount); // create message payload for L1 ISynthetixBridgeToOptimism bridgeToOptimism; bytes memory messageData = abi.encodeWithSelector(bridgeToOptimism.completeWithdrawal.selector, msg.sender, amount); // relay the message to Bridge on L1 via L2 Messenger messenger().sendMessage( synthetixBridgeToOptimism(), messageData, uint32(getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits.Withdrawal)) ); emit WithdrawalInitiated(msg.sender, amount); } // ========= RESTRICTED FUNCTIONS ============== function completeEscrowMigration( address account, uint256 escrowedAmount, VestingEntries.VestingEntry[] calldata vestingEntries ) external onlyOptimismBridge { IRewardEscrowV2 rewardEscrow = rewardEscrowV2(); // First, mint the escrowed SNX that are being migrated synthetix().mintSecondary(address(rewardEscrow), escrowedAmount); rewardEscrow.importVestingEntries(account, escrowedAmount, vestingEntries); emit ImportedVestingEntries(account, escrowedAmount, vestingEntries); } // invoked by Messenger on L2 function completeDeposit(address account, uint256 depositAmount) external onlyOptimismBridge { // now tell Synthetix to mint these tokens, deposited in L1, into the same account for L2 synthetix().mintSecondary(account, depositAmount); emit MintedSecondary(account, depositAmount); } // invoked by Messenger on L2 function completeRewardDeposit(uint256 amount) external onlyOptimismBridge { // now tell Synthetix to mint these tokens, deposited in L1, into reward escrow on L2 synthetix().mintSecondaryRewards(amount); emit MintedSecondaryRewards(amount); } // ========== EVENTS ========== event ImportedVestingEntries( address indexed account, uint256 escrowedAmount, VestingEntries.VestingEntry[] vestingEntries ); event MintedSecondary(address indexed account, uint256 amount); event MintedSecondaryRewards(uint256 amount); event WithdrawalInitiated(address indexed account, uint256 amount); }
invoked by user on L2 instruct L2 Synthetix to burn this supply create message payload for L1 relay the message to Bridge on L1 via L2 Messenger
function initiateWithdrawal(uint amount) external { require(synthetix().transferableSynthetix(msg.sender) >= amount, "Not enough transferable SNX"); synthetix().burnSecondary(msg.sender, amount); ISynthetixBridgeToOptimism bridgeToOptimism; bytes memory messageData = abi.encodeWithSelector(bridgeToOptimism.completeWithdrawal.selector, msg.sender, amount); messenger().sendMessage( synthetixBridgeToOptimism(), messageData, uint32(getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits.Withdrawal)) ); emit WithdrawalInitiated(msg.sender, amount); }
12,621,241
[ 1, 5768, 14276, 635, 729, 603, 511, 22, 316, 1697, 511, 22, 16091, 451, 278, 697, 358, 18305, 333, 14467, 752, 883, 2385, 364, 511, 21, 18874, 326, 883, 358, 24219, 603, 511, 21, 3970, 511, 22, 490, 18912, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 18711, 1190, 9446, 287, 12, 11890, 3844, 13, 3903, 288, 203, 3639, 2583, 12, 11982, 451, 278, 697, 7675, 13866, 429, 10503, 451, 278, 697, 12, 3576, 18, 15330, 13, 1545, 3844, 16, 315, 1248, 7304, 7412, 429, 14204, 60, 8863, 203, 203, 3639, 6194, 451, 278, 697, 7675, 70, 321, 14893, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 203, 3639, 4437, 878, 451, 278, 697, 13691, 774, 13930, 6228, 10105, 774, 13930, 6228, 31, 203, 3639, 1731, 3778, 883, 751, 273, 24126, 18, 3015, 1190, 4320, 12, 18337, 774, 13930, 6228, 18, 6226, 1190, 9446, 287, 18, 9663, 16, 1234, 18, 15330, 16, 3844, 1769, 203, 203, 3639, 31086, 7675, 4661, 1079, 12, 203, 5411, 6194, 451, 278, 697, 13691, 774, 13930, 6228, 9334, 203, 5411, 883, 751, 16, 203, 5411, 2254, 1578, 12, 588, 13941, 3748, 1079, 27998, 3039, 12, 13941, 3748, 1079, 27998, 12768, 18, 1190, 9446, 287, 3719, 203, 3639, 11272, 203, 203, 3639, 3626, 3423, 9446, 287, 2570, 10206, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(a <= c); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(a >= b); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } } contract ContractReceiver { function tokenFallback(address from, uint256 value, bytes data) public; } contract AuctusToken { function transfer(address to, uint256 value) public returns (bool); function transfer(address to, uint256 value, bytes data) public returns (bool); function burn(uint256 value) public returns (bool); function setTokenSaleFinished() public; } contract AuctusWhitelist { function getAllowedAmountToContribute(address addr) view public returns(uint256); } contract AuctusTokenSale is ContractReceiver { using SafeMath for uint256; address public auctusTokenAddress = 0xc12d099be31567add4e4e4d0D45691C3F58f5663; address public auctusWhiteListAddress = 0xA6e728E524c1D7A65fE5193cA1636265DE9Bc982; uint256 public startTime = 1522159200; //2018-03-27 2 PM UTC uint256 public endTime; uint256 public basicPricePerEth = 2000; address public owner; uint256 public softCap; uint256 public remainingTokens; uint256 public weiRaised; mapping(address => uint256) public invested; bool public saleWasSet; bool public tokenSaleHalted; event Buy(address indexed buyer, uint256 tokenAmount); event Revoke(address indexed buyer, uint256 investedAmount); function AuctusTokenSale(uint256 minimumCap, uint256 endSaleTime) public { owner = msg.sender; softCap = minimumCap; endTime = endSaleTime; saleWasSet = false; tokenSaleHalted = false; } modifier onlyOwner() { require(owner == msg.sender); _; } modifier openSale() { require(saleWasSet && !tokenSaleHalted && now >= startTime && now <= endTime && remainingTokens > 0); _; } modifier saleCompletedSuccessfully() { require(weiRaised >= softCap && (now > endTime || remainingTokens == 0)); _; } modifier saleFailed() { require(weiRaised < softCap && now > endTime); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } function setTokenSaleHalt(bool halted) onlyOwner public { tokenSaleHalted = halted; } function setSoftCap(uint256 minimumCap) onlyOwner public { require(now < startTime); softCap = minimumCap; } function setEndSaleTime(uint256 endSaleTime) onlyOwner public { require(now < endTime); endTime = endSaleTime; } function tokenFallback(address, uint256 value, bytes) public { require(msg.sender == auctusTokenAddress); require(!saleWasSet); setTokenSaleDistribution(value); } function() payable openSale public { uint256 weiToInvest; uint256 weiRemaining; (weiToInvest, weiRemaining) = getValueToInvest(); require(weiToInvest > 0); uint256 tokensToReceive = weiToInvest.mul(basicPricePerEth); remainingTokens = remainingTokens.sub(tokensToReceive); weiRaised = weiRaised.add(weiToInvest); invested[msg.sender] = invested[msg.sender].add(weiToInvest); if (weiRemaining > 0) { msg.sender.transfer(weiRemaining); } assert(AuctusToken(auctusTokenAddress).transfer(msg.sender, tokensToReceive)); emit Buy(msg.sender, tokensToReceive); } function revoke() saleFailed public { uint256 investedValue = invested[msg.sender]; require(investedValue > 0); invested[msg.sender] = 0; msg.sender.transfer(investedValue); emit Revoke(msg.sender, investedValue); } function finish() onlyOwner saleCompletedSuccessfully public { //40% of the ethers are unvested uint256 freeEthers = address(this).balance * 40 / 100; uint256 vestedEthers = address(this).balance - freeEthers; address(0xd1B10607921C78D9a00529294C4b99f1bd250E1c).transfer(freeEthers); //Owner assert(address(0xb3cc085B5a56Fdd47545A66EBd3DBd2a903D4565).call.value(vestedEthers)()); //AuctusEtherVesting SC AuctusToken token = AuctusToken(auctusTokenAddress); token.setTokenSaleFinished(); if (remainingTokens > 0) { token.burn(remainingTokens); remainingTokens = 0; } } function getValueToInvest() view private returns (uint256, uint256) { uint256 allowedValue = AuctusWhitelist(auctusWhiteListAddress).getAllowedAmountToContribute(msg.sender); uint256 weiToInvest; if (allowedValue == 0) { weiToInvest = 0; } else if (allowedValue >= invested[msg.sender].add(msg.value)) { weiToInvest = getAllowedAmount(msg.value); } else { weiToInvest = getAllowedAmount(allowedValue.sub(invested[msg.sender])); } return (weiToInvest, msg.value.sub(weiToInvest)); } function getAllowedAmount(uint256 value) view private returns (uint256) { uint256 maximumValue = remainingTokens / basicPricePerEth; if (value > maximumValue) { return maximumValue; } else { return value; } } function setTokenSaleDistribution(uint256 totalAmount) private { //Auctus core team 20% uint256 auctusCoreTeam = totalAmount * 20 / 100; //Bounty 2% uint256 bounty = totalAmount * 2 / 100; //Reserve for Future 18% uint256 reserveForFuture = totalAmount * 18 / 100; //Partnerships and Advisory free amount 1.8% uint256 partnershipsAdvisoryFree = totalAmount * 18 / 1000; //Partnerships and Advisory vested amount 7.2% uint256 partnershipsAdvisoryVested = totalAmount * 72 / 1000; uint256 privateSales = 6836048000000000000000000; uint256 preSale = 2397307557007329968290000; transferTokens(auctusCoreTeam, bounty, reserveForFuture, preSale, partnershipsAdvisoryVested, partnershipsAdvisoryFree, privateSales); remainingTokens = totalAmount - auctusCoreTeam - bounty - reserveForFuture - preSale - partnershipsAdvisoryVested - partnershipsAdvisoryFree - privateSales; saleWasSet = true; } function transferTokens( uint256 auctusCoreTeam, uint256 bounty, uint256 reserveForFuture, uint256 preSale, uint256 partnershipsAdvisoryVested, uint256 partnershipsAdvisoryFree, uint256 privateSales ) private { AuctusToken token = AuctusToken(auctusTokenAddress); bytes memory empty; assert(token.transfer(0x8592Ec038ACBA05BC467C6bC17aA855880d490E4, auctusCoreTeam, empty)); //AuctusTokenVesting SC assert(token.transfer(0x389E93aC36Dd8c8E04FB1952B37c4aa4b320b6FF, bounty, empty)); //AuctusBountyDistribution SC assert(token.transfer(0xc83847FCbd217FB8Ec4bc79DbA7DB672d3aB2602, reserveForFuture, empty)); //AuctusTokenVesting SC assert(token.transfer(0xA39cA2768A7B76Aa3bCab68c4d4DEBF9A32c5434, preSale, empty)); //AuctusPreSaleDistribution SC assert(token.transfer(0x8Cb9626BBc5Ec60c386eeEde50ac74f173FBD8a8, partnershipsAdvisoryVested, empty)); //AuctusTokenVesting SC assert(token.transfer(0x6c89Cc03036193d52e9b8386413b545184BDAb99, partnershipsAdvisoryFree)); assert(token.transfer(0xd1B10607921C78D9a00529294C4b99f1bd250E1c, privateSales)); } }
AuctusBountyDistribution SC
assert(token.transfer(0x389E93aC36Dd8c8E04FB1952B37c4aa4b320b6FF, bounty, empty));
1,092,761
[ 1, 37, 853, 407, 38, 592, 93, 9003, 8795, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 11231, 12, 2316, 18, 13866, 12, 20, 92, 23, 6675, 41, 11180, 69, 39, 5718, 40, 72, 28, 71, 28, 41, 3028, 22201, 3657, 9401, 38, 6418, 71, 24, 7598, 24, 70, 31273, 70, 26, 2246, 16, 324, 592, 93, 16, 1008, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x11EFec7acaAC5D0CEcc9C16bf2508e37047E6d2F/sources/contracts/TestUniswapOptimal.sol
Ropsten address private constant USDC = 0x07865c6e87b9f70255377e024ace6630c1eaa37f address private constant DAI = 0xad6d458402f60fd3bd25163575031acdce07538d address private constant UNI = 0x1f9840a85d5af5bf1d1762f925bdaddc4201f984 import "@uniswap/lib/contracts/libraries/Babylonian.sol";
contract TestUniswapOptimal { using SafeMath for uint; address private constant FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address private constant ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private constant MATIC = 0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0; address private constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address private constant DAI = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; pragma solidity ^0.7; function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } z = 1; } r = amount of reserve for token a a = amount of token a the user currently has (not added to reserve yet) f = swap fee percent s = (sqrt(((2 - f)r)^2 + 4(1 - f)ar) - (2 - f)r) / (2(1 - f)) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } z = 1; } r = amount of reserve for token a a = amount of token a the user currently has (not added to reserve yet) f = swap fee percent s = (sqrt(((2 - f)r)^2 + 4(1 - f)ar) - (2 - f)r) / (2(1 - f)) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } z = 1; } r = amount of reserve for token a a = amount of token a the user currently has (not added to reserve yet) f = swap fee percent s = (sqrt(((2 - f)r)^2 + 4(1 - f)ar) - (2 - f)r) / (2(1 - f)) } else if (y != 0) { } s = optimal swap amount function getSwapAmount(uint r, uint a) public pure returns (uint) { return (sqrt(r.mul(r.mul(3988009) + a.mul(3988000))).sub(r.mul(1997))) / 1994; } function getEstimatedETHforToken(uint amountsOut,address token) public view returns (uint[] memory) { address[] memory path = new address[](2); path[0] = IUniswapV2Router(ROUTER).WETH(); path[1] = token; return IUniswapV2Router(ROUTER).getAmountsIn(amountsOut, path); } function getEstimatedTokenforToken(uint amountsOut,address fromToken, address toToken) public view returns (uint[] memory) { address[] memory path = new address[](2); path[0] = fromToken; path[1] = toToken; return IUniswapV2Router(ROUTER).getAmountsIn(amountsOut, path); } function convertEthToToken(uint amountOutMin,address toToken) public payable { address[] memory path = new address[](2); path[0] = IUniswapV2Router(ROUTER).WETH(); path[1] = toToken; require(success, "refund failed"); } IUniswapV2Router(ROUTER).swapETHForExactTokens{ value: msg.value }(amountOutMin, path, msg.sender, deadline); (bool success,) = msg.sender.call{ value: address(this).balance }(""); function convertTokenToToken(uint amountInMin, uint amountOutMin, address fromToken, address toToken) public payable { address[] memory path = new address[](2); path[0] = fromToken; path[1] = toToken; IUniswapV2Router(ROUTER).swapTokensForExactTokens(amountInMin, amountOutMin, path, msg.sender, deadline); require(success, "refund failed"); } 2. add liquidity (bool success,) = msg.sender.call{ value: address(this).balance }(""); 1. swap optimal amount from token A to token B function zap( address _tokenA, address _tokenB, uint _amountA ) external { require(_tokenA == WETH || _tokenB == WETH, "!weth"); IERC20(_tokenA).transferFrom(msg.sender, address(this), _amountA); address pair = IUniswapV2Factory(FACTORY).getPair(_tokenA, _tokenB); (uint reserve0, uint reserve1, ) = IUniswapV2Pair(pair).getReserves(); uint swapAmount; if (IUniswapV2Pair(pair).token0() == _tokenA) { swapAmount = getSwapAmount(reserve0, _amountA); swapAmount = getSwapAmount(reserve1, _amountA); } _swapTokens(_tokenA, _tokenB, swapAmount); _addLiquidity(_tokenA, _tokenB); } function zap( address _tokenA, address _tokenB, uint _amountA ) external { require(_tokenA == WETH || _tokenB == WETH, "!weth"); IERC20(_tokenA).transferFrom(msg.sender, address(this), _amountA); address pair = IUniswapV2Factory(FACTORY).getPair(_tokenA, _tokenB); (uint reserve0, uint reserve1, ) = IUniswapV2Pair(pair).getReserves(); uint swapAmount; if (IUniswapV2Pair(pair).token0() == _tokenA) { swapAmount = getSwapAmount(reserve0, _amountA); swapAmount = getSwapAmount(reserve1, _amountA); } _swapTokens(_tokenA, _tokenB, swapAmount); _addLiquidity(_tokenA, _tokenB); } } else { function _swapTokens( address _from, address _to, uint _amount ) public { IERC20(_from).approve(ROUTER, _amount); address[] memory path = new address[](2); path = new address[](2); path[0] = _from; path[1] = _to; IUniswapV2Router(ROUTER).swapExactTokensForTokens( _amount, uint(-1), path, address(this), block.timestamp ); } function _addLiquidity(address _tokenA, address _tokenB) internal { uint balA = IERC20(_tokenA).balanceOf(address(this)); uint balB = IERC20(_tokenB).balanceOf(address(this)); IERC20(_tokenA).approve(ROUTER, balA); IERC20(_tokenB).approve(ROUTER, balB); IUniswapV2Router(ROUTER).addLiquidity( _tokenA, _tokenB, balA, balB, 0, 0, address(this), block.timestamp ); } function getPair(address _tokenA, address _tokenB) external view returns (address) { return IUniswapV2Factory(FACTORY).getPair(_tokenA, _tokenB); } }
8,200,494
[ 1, 54, 556, 334, 275, 282, 1758, 3238, 5381, 11836, 5528, 273, 374, 92, 8642, 5292, 25, 71, 26, 73, 11035, 70, 29, 74, 27, 3103, 2539, 23, 4700, 73, 3103, 24, 623, 26, 4449, 20, 71, 21, 73, 7598, 6418, 74, 282, 1758, 3238, 5381, 463, 18194, 273, 374, 92, 361, 26, 72, 7950, 5193, 3103, 74, 4848, 8313, 23, 16410, 2947, 2313, 4763, 27, 3361, 6938, 1077, 72, 311, 20, 5877, 7414, 72, 282, 1758, 3238, 5381, 19462, 273, 374, 92, 21, 74, 29, 28585, 69, 7140, 72, 25, 1727, 25, 17156, 21, 72, 4033, 8898, 74, 29, 2947, 16410, 1289, 71, 24, 6734, 74, 29, 5193, 1930, 8787, 318, 291, 91, 438, 19, 2941, 19, 16351, 87, 19, 31417, 19, 38, 24383, 9379, 2779, 18, 18281, 14432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7766, 984, 291, 91, 438, 6179, 2840, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 225, 1758, 3238, 5381, 26724, 3964, 273, 374, 92, 25, 39, 8148, 70, 41, 73, 27, 1611, 10241, 28, 3461, 69, 22, 38, 26, 69, 23, 2056, 40, 24, 38, 2313, 9401, 8876, 29, 952, 25, 69, 37, 26, 74, 31, 203, 225, 1758, 3238, 5381, 534, 5069, 654, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 203, 225, 1758, 3238, 5381, 678, 1584, 44, 273, 374, 14626, 3103, 7598, 37, 5520, 70, 3787, 23, 8090, 28, 40, 20, 37, 20, 73, 25, 39, 24, 42, 5324, 73, 1880, 29, 6840, 23, 39, 27, 4313, 39, 71, 22, 31, 203, 225, 1758, 3238, 5381, 490, 11781, 273, 374, 92, 27, 40, 21, 12664, 37, 27, 38, 27, 2643, 19192, 6675, 23, 72, 38, 5082, 37, 23, 69, 38, 71, 20, 39, 7142, 4848, 28, 37, 69, 39, 3030, 9676, 20, 31, 203, 225, 1758, 3238, 5381, 11836, 5528, 273, 374, 21703, 20, 70, 5292, 2733, 21, 71, 8898, 2643, 70, 5718, 71, 21, 72, 3657, 40, 24, 69, 22, 73, 29, 41, 70, 20, 71, 41, 29751, 26, 73, 38, 8875, 31, 203, 225, 1758, 3238, 5381, 463, 18194, 273, 374, 21703, 20, 70, 5292, 2733, 21, 71, 8898, 2643, 70, 5718, 71, 21, 72, 3657, 40, 24, 2 ]
pragma solidity ^0.4.13; contract SafeMath { function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } } contract PrivateCityToken { function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } contract PrivateCityCrowdsale is SafeMath{ uint256 public totalSupply; // Deposit address of account controlled by the creators address public ethFundDeposit = 0x4574C2A0a1C39114Fe794dD1A3D1A5F90C92AD90; address public tokenExchangeAddress = 0xD9fc693CA2C5CF060D10E182a078a0A4CFF1F4d6; address public tokenAccountAddress = 0xdca42D3220681C3beaF3dD0631D06536c39beB67; //Access to token contract for tokens exchange PrivateCityToken public tokenExchange; // Fundraising parameters enum ContractState { Fundraising } ContractState public state; uint256 public constant decimals = 18; //start date: 11/24/2017 @ 00:00 (GMT-8) uint public startDate = 1511510400; //start date: 1/01/2018 @ 00:00 (GMT-8) uint public endDate = 1514793600; uint256 public constant TOKEN_MIN = 1 * 10**decimals; // 1 PCT // We need to keep track of how much ether have been contributed, since we have a cap for ETH too uint256 public totalReceivedEth = 0; // Constructor function PrivateCityCrowdsale() { // Contract state state = ContractState.Fundraising; tokenExchange = PrivateCityToken(tokenExchangeAddress); totalSupply = 0; } function () payable external { require(now >= startDate); require(now <= endDate); require(msg.value > 0); // First we check the ETH cap, as it's easier to calculate, return // the contribution if the cap has been reached already uint256 checkedReceivedEth = safeAdd(totalReceivedEth, msg.value); // If all is fine with the ETH cap, we continue to check the // minimum amount of tokens uint256 tokens = safeMult(msg.value, getCurrentTokenPrice()); require(tokens >= TOKEN_MIN); totalReceivedEth = checkedReceivedEth; totalSupply = safeAdd(totalSupply, tokens); ethFundDeposit.transfer(msg.value); if(!tokenExchange.transferFrom(tokenAccountAddress, msg.sender, tokens)) revert(); } /// @dev Returns the current token price function getCurrentTokenPrice() private constant returns (uint256 currentPrice) { return 6000;//bonuses are not implied! } }
bonuses are not implied!
return 6000;
2,485,359
[ 1, 18688, 6117, 854, 486, 23547, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 327, 1666, 3784, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; // SPDX-License-Identifier: UNLICENSED /** * @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; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() public virtual view returns (uint); function balanceOf(address tokenOwner) public virtual view returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // 'ezgamers' token AND staking contract // Symbol : ezgamers // Name : ezg // Total supply: 5,000,000 (5 million) // Decimals : 18 // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract EZG_STAKE is ERC20Interface, Owned { using SafeMath for uint256; string public symbol = "EZG"; string public name = "Ezgamers"; uint256 public decimals = 18; uint256 _totalSupply = 5e6 * 10 ** (decimals); uint256 deployTime; uint256 private totalDividentPoints; uint256 private unclaimedDividendPoints; uint256 pointMultiplier = 1000000000000000000; uint256 public stakedCoins; uint256 public icoTokens; uint256 private icoEndDate; uint256 public totalStakes; uint256 public totalRewardsClaimed; struct Account { uint256 balance; uint256 lastDividentPoints; uint256 timeInvest; uint256 lastClaimed; uint256 rewardsClaimed; uint256 totalStakes; } mapping(address => Account) accounts; mapping(address => bool) isInvertor; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { owner = 0x833Cfb9D53cb5dC97F53F715f1555998Cf1251b9; icoEndDate = block.timestamp.add(4 weeks); balances[address(this)] = 1e6 * 10 ** (18); // 1 million emit Transfer(address(0), address(this), 1e6 * 10 ** (18)); icoTokens = 1e6 * 10 ** (18); balances[address(owner)] = 4e6 * 10 ** (18); // 4 million emit Transfer(address(0), address(owner), 4e6 * 10 ** (18)); deployTime = block.timestamp; } receive() external payable{ require(block.timestamp <= icoEndDate && balanceOf(address(this)) > 0, "pre sale is finished"); // receive ethers uint tokens = getTokenAmount(msg.value); _transfer(msg.sender, tokens, true); // send received funds to the owner owner.transfer(msg.value); } function getUnSoldTokens() external onlyOwner{ // sale is over require(block.timestamp > icoEndDate && icoTokens > 0, "No tokens in contract to withdraw"); _transfer(owner, icoTokens, false); // send all the unsold tokens to the owner } function getTokenAmount(uint256 amount) internal pure returns(uint256){ return amount * 12000; //12000 per ethers } function _transfer(address to, uint256 tokens, bool purchased) internal { // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[address(this)] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[address(this)] = balances[address(this)].sub(tokens); balances[to] = balances[to].add(tokens); if(purchased) icoTokens = icoTokens.sub(tokens); emit Transfer(address(this),to,tokens); } function STAKE(uint256 _tokens) external returns(bool){ require(isInvertor[msg.sender] == false, "Sorry!, Already an Investor"); require(transfer(address(this), _tokens), "Insufficient Funds!"); isInvertor[msg.sender] = true; stakedCoins = stakedCoins.add(_tokens); accounts[msg.sender].balance = _tokens; accounts[msg.sender].lastDividentPoints = totalDividentPoints; accounts[msg.sender].timeInvest = now; accounts[msg.sender].lastClaimed = now; accounts[msg.sender].totalStakes = accounts[msg.sender].totalStakes.add(_tokens); totalStakes = totalStakes.add(_tokens); return true; } function pendingReward(address _user) external view returns(uint256){ uint256 owing = dividendsOwing(_user); return owing; } function updateDividend(address investor) internal returns(uint256){ uint256 owing = dividendsOwing(investor); if (owing > 0){ unclaimedDividendPoints = unclaimedDividendPoints.sub(owing); accounts[investor].lastDividentPoints = totalDividentPoints; } return owing; } function activeStake(address _user) external view returns (uint256){ return accounts[_user].balance; } function totalStakesTillToday(address _user) external view returns (uint256){ return accounts[_user].totalStakes; } function UNSTAKE() external returns (bool){ require(isInvertor[msg.sender] == true, "Sorry!, Not investor"); require(stakedCoins > 0); stakedCoins = stakedCoins.sub(accounts[msg.sender].balance); uint256 owing = updateDividend(msg.sender); require(_transfer(msg.sender, owing.add(accounts[msg.sender].balance))); isInvertor[msg.sender] = false; accounts[msg.sender].balance = 0; return true; } function disburse(uint256 amount) internal{ uint256 unnormalized = amount.mul(pointMultiplier); totalDividentPoints = totalDividentPoints.add(unnormalized.div(stakedCoins)); unclaimedDividendPoints = unclaimedDividendPoints.add(amount); } function dividendsOwing(address investor) internal view returns (uint256){ uint256 newDividendPoints = totalDividentPoints.sub(accounts[investor].lastDividentPoints); return ((accounts[investor].balance).mul(newDividendPoints)).div(pointMultiplier); } function claimReward() external returns(bool){ require(isInvertor[msg.sender] == true, "Sorry!, Not an investor"); require(accounts[msg.sender].balance > 0); uint256 owing = updateDividend(msg.sender); require(_transfer(msg.sender, owing)); accounts[msg.sender].rewardsClaimed = accounts[msg.sender].rewardsClaimed.add(owing); totalRewardsClaimed = totalRewardsClaimed.add(owing); return true; } function rewardsClaimed(address _user) external view returns(uint256 rewardClaimed){ return accounts[_user].rewardsClaimed; } /** ERC20Interface function's implementation **/ function totalSupply() public override view returns (uint256){ return _totalSupply; } // ------------------------------------------------------------------------ // Calculates onePercent of the uint256 amount sent // ------------------------------------------------------------------------ function onePercent(uint256 _tokens) internal pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[msg.sender] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); uint256 deduction = 0; uint256 minSupply = 10000 * 10 ** (18); if(_totalSupply > minSupply){ deduction = onePercent(tokens).mul(6); if(_totalSupply.sub(deduction) < minSupply) deduction = _totalSupply.sub(minSupply); if (stakedCoins == 0){ burnTokens(deduction); } else{ burnTokens(onePercent(deduction).mul(3)); disburse(onePercent(deduction).mul(3)); } } balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(msg.sender, to, tokens.sub(deduction)); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender,spender,tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); uint256 deduction = 0; uint256 minSupply = 10000 * 10 ** (18); if(_totalSupply > minSupply){ deduction = onePercent(tokens).mul(6); if(_totalSupply.sub(deduction) < minSupply) deduction = _totalSupply.sub(minSupply); if (stakedCoins == 0){ burnTokens(deduction); } else{ burnTokens(onePercent(deduction).mul(3)); disburse(onePercent(deduction).mul(3)); } } balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(from, to, tokens.sub(tokens)); return true; } function _transfer(address to, uint256 tokens) internal returns(bool){ // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[address(this)] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[address(this)] = balances[address(this)].sub(tokens); uint256 deduction = 0; uint256 minSupply = 10000 * 10 ** (18); if(_totalSupply > minSupply){ deduction = onePercent(tokens).mul(6); if(_totalSupply.sub(deduction) < minSupply) deduction = _totalSupply.sub(minSupply); if (stakedCoins == 0){ burnTokens(deduction); } else{ burnTokens(onePercent(deduction).mul(3)); disburse(onePercent(deduction).mul(3)); } } balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(address(this),to,tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Burn the ``value` amount of tokens from the `account` // ------------------------------------------------------------------------ function burnTokens(uint256 value) internal{ require(_totalSupply >= value); // burn only unsold tokens _totalSupply = _totalSupply.sub(value); emit Transfer(msg.sender, address(0), value); } }
prevent transfer to 0x0, use burn instead
function _transfer(address to, uint256 tokens) internal returns(bool){ require(address(to) != address(0)); require(balances[address(this)] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[address(this)] = balances[address(this)].sub(tokens); uint256 deduction = 0; uint256 minSupply = 10000 * 10 ** (18); if(_totalSupply > minSupply){ deduction = onePercent(tokens).mul(6); if(_totalSupply.sub(deduction) < minSupply) deduction = _totalSupply.sub(minSupply); if (stakedCoins == 0){ burnTokens(deduction); } else{ burnTokens(onePercent(deduction).mul(3)); disburse(onePercent(deduction).mul(3)); } } balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(address(this),to,tokens); return true; }
521,516
[ 1, 29150, 7412, 358, 374, 92, 20, 16, 999, 18305, 3560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13866, 12, 2867, 358, 16, 2254, 5034, 2430, 13, 2713, 1135, 12, 6430, 15329, 203, 3639, 2583, 12, 2867, 12, 869, 13, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 70, 26488, 63, 2867, 12, 2211, 25887, 1545, 2430, 11272, 203, 3639, 2583, 12, 70, 26488, 63, 869, 65, 397, 2430, 1545, 324, 26488, 63, 869, 19226, 203, 540, 203, 1850, 203, 3639, 324, 26488, 63, 2867, 12, 2211, 25887, 273, 324, 26488, 63, 2867, 12, 2211, 13, 8009, 1717, 12, 7860, 1769, 203, 540, 203, 3639, 2254, 5034, 11140, 4062, 273, 374, 31, 203, 3639, 2254, 5034, 1131, 3088, 1283, 273, 12619, 380, 1728, 2826, 261, 2643, 1769, 203, 3639, 309, 24899, 4963, 3088, 1283, 405, 1131, 3088, 1283, 15329, 203, 540, 203, 5411, 11140, 4062, 273, 1245, 8410, 12, 7860, 2934, 16411, 12, 26, 1769, 203, 540, 203, 5411, 309, 24899, 4963, 3088, 1283, 18, 1717, 12, 785, 4062, 13, 411, 1131, 3088, 1283, 13, 203, 7734, 11140, 4062, 273, 389, 4963, 3088, 1283, 18, 1717, 12, 1154, 3088, 1283, 1769, 203, 540, 203, 5411, 309, 261, 334, 9477, 39, 9896, 422, 374, 15329, 203, 7734, 18305, 5157, 12, 785, 4062, 1769, 203, 5411, 289, 203, 5411, 469, 95, 203, 7734, 18305, 5157, 12, 476, 8410, 12, 785, 4062, 2934, 16411, 12, 23, 10019, 203, 7734, 1015, 70, 295, 307, 12, 476, 8410, 12, 785, 4062, 2934, 16411, 12, 23, 10019, 203, 5411, 289, 203, 3639, 289, 203, 540, 203, 540, 203, 3639, 324, 26488, 63, 869, 65, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-04-19 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract BlazeInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exclude from fees, transfers and max transaction amount mapping(address => bool) private _blacklist; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event SetBlacklistedWallet(address indexed blacklistedWallet); 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("BlazeInu", "BLAZE") { 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 = 5; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 15; uint256 _sellLiquidityFee = 6; uint256 _sellDevFee = 4; uint256 totalSupply = 1000000000000 * 1e18; maxTransactionAmount = totalSupply * 20 / 1000; // 2% maxTransactionAmountTxn maxWallet = totalSupply * 25 / 1000; // 2.5% maxWallet swapTokensAtAmount = totalSupply * 25 / 10000; // 0.25% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = 0x07091C5e63f04D38EcB821aecee578794Ca2FC5C; // set as marketing wallet devWallet = 0x9CE40aD0BCAcd05ebB619B321a018298681031FA; // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function toggleBlacklistedWallet(address blacklistedWallet) external onlyOwner { emit SetBlacklistedWallet(blacklistedWallet); _blacklist[blacklistedWallet] = !_blacklist[blacklistedWallet]; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[from], "Sender blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
set as marketing wallet
marketingWallet = 0x07091C5e63f04D38EcB821aecee578794Ca2FC5C;
10,644,128
[ 1, 542, 487, 13667, 310, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 13667, 310, 16936, 273, 374, 92, 8642, 5908, 21, 39, 25, 73, 4449, 74, 3028, 40, 7414, 23057, 38, 28, 5340, 8906, 311, 73, 25, 8285, 7235, 24, 23508, 22, 4488, 25, 39, 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 ]
./full_match/80001/0xd55660D297eFAE59522f3d4b0d621510d7A748A5/sources/contracts/LegacyERC20v1.sol
* @dev Returns the name of the token./
function name() public view virtual override returns (string memory) { return _name; }
853,818
[ 1, 1356, 326, 508, 434, 326, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 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 ]
pragma solidity 0.4.24; /** * @author James Spivey <[email protected]> * @title Migration * @dev * This is the standard migration contract from Truffle. */ contract Migrations { address public owner; uint public last_completed_migration; /** @dev Owner of this contract is who first calls it */ constructor() public { owner = msg.sender; } /** @dev Ensures a reservation exists in map */ modifier restricted() { if (msg.sender == owner) _; } /** @dev Set complete on migration * @param completed Migration completed date */ function setCompleted(uint completed) public restricted { last_completed_migration = completed; } /** @dev Upgrade a previous deployed contract * @param new_address New address of the upgraded contract */ function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }
* @dev Ensures a reservation exists in map */
modifier restricted() { if (msg.sender == owner) _; }
1,033,059
[ 1, 19869, 279, 18438, 1704, 316, 852, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 15693, 1435, 288, 203, 565, 309, 261, 3576, 18, 15330, 422, 3410, 13, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.11; /** @title A contract for issuing, redeeming and transfering SilaUSD StableCoin * * @author www.silamoney.com * Email: [email protected] * */ /**Run * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath{ /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } } /** * @title Arrays * @dev overload array operations */ library Arrays{ function arr(address _a) internal pure returns (address[] memory _arr) { _arr = new address[](1); _arr[0] = _a; } function arr(address _a, address _b) internal pure returns (address[] memory _arr) { _arr = new address[](2); _arr[0] = _a; _arr[1] = _b; } function arr(address _a, address _b, address _c) internal pure returns (address[] memory _arr) { _arr = new address[](3); _arr[0] = _a; _arr[1] = _b; _arr[2] = _c; } } /** * @title Ownable * @dev The Ownable contract hotOwner and ColdOwner, and provides authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable{ // hot and cold wallet addresses address public hotOwner = 0xCd39203A332Ff477a35dA3AD2AD7761cDBEAb7F0; address public coldOwner = 0x1Ba688e70bb4F3CB266b8D721b5597bFbCCFF957; // event for ownership transfer event OwnershipTransferred(address indexed _newHotOwner, address indexed _newColdOwner, address indexed _oldColdOwner); /** * @dev Reverts if called by any account other than the hotOwner. */ modifier onlyHotOwner() { require(msg.sender == hotOwner); _; } /** * @dev Reverts if called by any account other than the coldOwner. */ modifier onlyColdOwner() { require(msg.sender == coldOwner); _; } /** * @dev Assigns new hotowner and coldOwner * @param _newHotOwner address The address which is a new hot owner. * @param _newColdOwner address The address which can change the hotOwner. */ function transferOwnership(address _newHotOwner, address _newColdOwner) public onlyColdOwner { require(_newHotOwner != address(0)); require(_newColdOwner!= address(0)); hotOwner = _newHotOwner; coldOwner = _newColdOwner; emit OwnershipTransferred(_newHotOwner, _newColdOwner, msg.sender); } } /** * @title EmergencyToggle * @dev The EmergencyToggle contract provides a way to pause the contract in emergency */ contract EmergencyToggle is Ownable{ // pause the entire contract if true bool public emergencyFlag; // constructor constructor () public{ emergencyFlag = false; } /** * @dev onlyHotOwner can can pause the usage of issue,redeem, transfer functions */ function emergencyToggle() external onlyHotOwner { emergencyFlag = !emergencyFlag; } } /** * @title Authorizable * @dev The Authorizable contract can be used to authorize addresses to control silausd main * functions, this will provide more flexibility in terms of signing trasactions */ contract Authorizable is Ownable, EmergencyToggle { using SafeMath for uint256; // map to check if the address is authorized to issue, redeem and betalist sila mapping(address => bool) authorized; // events for when address is added or removed event AuthorityAdded(address indexed _toAdd); event AuthorityRemoved(address indexed _toRemove); // modifier allowing only authorized addresses and hotOwner to call certain functions modifier onlyAuthorized() { require(authorized[msg.sender] || hotOwner == msg.sender); _; } /** * @dev Function addAuthorized adds addresses that can betalist, transfer, issue and redeem * @param _toAdd address of the added authority */ function addAuthorized(address _toAdd) public onlyHotOwner { require (!emergencyFlag); require(_toAdd != address(0)); require(!authorized[_toAdd]); authorized[_toAdd] = true; emit AuthorityAdded(_toAdd); } /** * @dev Function RemoveAuthorized removes addresses that can betalist and transfer * @param _toRemove address of the added authority */ function removeAuthorized(address _toRemove) public onlyHotOwner { require (!emergencyFlag); require(_toRemove != address(0)); require(authorized[_toRemove]); authorized[_toRemove] = false; emit AuthorityRemoved(_toRemove); } /** * @dev check the specified address is authorized to do sila transactions * @param _authorized The address to be checked for authority */ function isAuthorized(address _authorized) external view returns(bool _isauthorized) { return authorized[_authorized]; } } /** * @title Token is Betalist,Blacklist */ contract Betalist is Authorizable { // maps for betalisted and blacklisted addresses mapping(address => bool) betalisted; mapping(address => bool) blacklisted; // events for betalist and blacklist event BetalistedAddress (address indexed _betalisted); event BlacklistedAddress (address indexed _blacklisted); event RemovedAddressFromBlacklist(address indexed _toRemoveBlacklist); event RemovedAddressFromBetalist(address indexed _toRemoveBetalist); // variable to check if betalist is required when calling several functions on smart contract bool public requireBetalisted; // constructor constructor () public { requireBetalisted = true; } // modifier to check acceptableTransactor addresses modifier acceptableTransactors(address[] memory addresses) { require(!emergencyFlag); if (requireBetalisted){ for(uint i = 0; i < addresses.length; i++) require( betalisted[addresses[i]] ); } for(uint i = 0; i < addresses.length; i++) { address addr = addresses[i]; require(addr != address(0)); require(!blacklisted[addr]); } _; } /** * @dev betaList the specified address * @param _toBetalist The address to betalist */ function betalistAddress(address _toBetalist) public onlyAuthorized returns(bool) { require(!emergencyFlag); require(_toBetalist != address(0)); require(!blacklisted[_toBetalist]); require(!betalisted[_toBetalist]); betalisted[_toBetalist] = true; emit BetalistedAddress(_toBetalist); return true; } /** * @dev remove from betaList the specified address * @param _toRemoveBetalist The address to be removed */ function removeAddressFromBetalist(address _toRemoveBetalist) public onlyAuthorized { require(!emergencyFlag); require(_toRemoveBetalist != address(0)); require(betalisted[_toRemoveBetalist]); betalisted[_toRemoveBetalist] = false; emit RemovedAddressFromBetalist(_toRemoveBetalist); } /** * @dev blackList the specified address * @param _toBlacklist The address to blacklist */ function blacklistAddress(address _toBlacklist) public onlyAuthorized returns(bool) { require(!emergencyFlag); require(_toBlacklist != address(0)); require(!blacklisted[_toBlacklist]); blacklisted[_toBlacklist] = true; emit BlacklistedAddress(_toBlacklist); return true; } /** * @dev remove from blackList the specified address * @param _toRemoveBlacklist The address to blacklist */ function removeAddressFromBlacklist(address _toRemoveBlacklist) public onlyAuthorized { require(!emergencyFlag); require(_toRemoveBlacklist != address(0)); require(blacklisted[_toRemoveBlacklist]); blacklisted[_toRemoveBlacklist] = false; emit RemovedAddressFromBlacklist(_toRemoveBlacklist); } /** * @dev BlackList addresses in batches * @param _toBlacklistAddresses array of addresses to be blacklisted */ function batchBlacklistAddresses(address[] memory _toBlacklistAddresses) public onlyAuthorized returns(bool) { for(uint i = 0; i < _toBlacklistAddresses.length; i++) { bool check = blacklistAddress(_toBlacklistAddresses[i]); require(check); } return true; } /** * @dev Betalist addresses in batches * @param _toBetalistAddresses array of addresses to be betalisted */ function batchBetalistAddresses(address[] memory _toBetalistAddresses) public onlyAuthorized returns(bool) { for(uint i = 0; i < _toBetalistAddresses.length; i++) { bool check = betalistAddress(_toBetalistAddresses[i]); require(check); } return true; } /** * @dev check the specified address if isBetaListed * @param _betalisted The address to be checked for betalisting */ function isBetalisted(address _betalisted) external view returns(bool) { return (betalisted[_betalisted]); } /** * @dev check the specified address isBlackListed * @param _blacklisted The address to be checked for blacklisting */ function isBlacklisted(address _blacklisted) external view returns(bool) { return (blacklisted[_blacklisted]); } } /** * @title Token is token Interface */ contract Token{ function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** *@title StandardToken *@dev Implementation of the basic standard token. */ contract StandardToken is Token, Betalist{ using SafeMath for uint256; // maps to store balances and allowances mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; /** * @dev Gets the balance of the specified address. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner,address _spender)public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public acceptableTransactors(Arrays.arr(_to, msg.sender)) returns (bool) { 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 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: * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public acceptableTransactors(Arrays.arr(_spender, msg.sender)) returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public acceptableTransactors(Arrays.arr(_from, _to, msg.sender)) returns (bool) { 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; } } /** *@title AuthroizeDeveloper *@dev Implementation of the authorize developer contract to authorize developers * to control the users sila balance registered under an app */ contract AuthorizeDeveloper is StandardToken{ // mapping to store authorization for DeveloperTransfer mapping(address => mapping(address => bool)) isAuthorizedDeveloper; // Events event SilaAuthorizedDeveloper (address indexed _developer, address indexed _user); event DeveloperTransfer (address indexed _developer, address indexed _from, address indexed _to, uint _amount); event SilaRemovedDeveloper (address indexed _developer, address indexed _user); event UserAuthorizedDeveloper (address indexed _developer, address indexed _user); event UserRemovedDeveloper (address indexed _developer, address indexed _user); /** * @dev silaAuthorizeDeveloper to transfer tokens on users behalf * @param _developer address The address which is allowed to transfer tokens on users behalf * @param _user address The address which developer want to transfer from */ function silaAuthorizeDeveloper(address _developer, address _user) public acceptableTransactors(Arrays.arr(_developer, _user)) onlyAuthorized { require(!isAuthorizedDeveloper[_developer][_user]); isAuthorizedDeveloper[_developer][_user] = true; emit SilaAuthorizedDeveloper(_developer,_user); } /** * @dev user can Authorize Developer to transfer tokens on their behalf * @param _developer address The address which is allowed to transfer tokens on users behalf */ function userAuthorizeDeveloper(address _developer) public acceptableTransactors(Arrays.arr(_developer, msg.sender)) { require(!isAuthorizedDeveloper[_developer][msg.sender]); isAuthorizedDeveloper[_developer][msg.sender] = true; emit UserAuthorizedDeveloper(_developer, msg.sender); } /** * @dev RemoveDeveloper allowed to transfer tokens on users behalf * @param _developer address The address which is allowed to transfer tokens on users behalf * @param _user address The address which developer want to transfer from */ function silaRemoveDeveloper(address _developer, address _user) public onlyAuthorized { require(!emergencyFlag); require(_developer != address(0)); require(_user != address(0)); require(isAuthorizedDeveloper[_developer][_user]); isAuthorizedDeveloper[_developer][_user] = false; emit SilaRemovedDeveloper(_developer, _user); } /** * @dev userRemovDeveloper to remove the developer allowed to transfer sila * @param _developer, The address which is allowed to transfer tokens on users behalf */ function userRemoveDeveloper(address _developer) public { require(!emergencyFlag); require(_developer != address(0)); require(isAuthorizedDeveloper[_developer][msg.sender]); isAuthorizedDeveloper[_developer][msg.sender] = false; emit UserRemovedDeveloper(_developer,msg.sender); } /** * @dev developerTransfer for developer to transfer tokens on users behalf without requiring ethers in managed ethereum accounts * @param _from address the address to transfer tokens from * @param _to address The address which developer want to transfer to * @param _amount the amount of tokens user wants to transfer */ function developerTransfer(address _from, address _to, uint _amount) public acceptableTransactors(Arrays.arr(_from, _to, msg.sender)) { require(isAuthorizedDeveloper[msg.sender][_from]); require(_amount <= balances[_from]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); emit DeveloperTransfer(msg.sender, _from, _to, _amount); emit Transfer(_from, _to, _amount); } /** * @dev check if developer is allowed to transfer tokens on users behalf * @param _developer the address allowed to transfer tokens * @param _for address The user address which developer want to transfer from */ function checkIsAuthorizedDeveloper(address _developer, address _for) external view returns (bool) { return (isAuthorizedDeveloper[_developer][_for]); } } /** *@title SilaUsd *@dev Implementation for sila issue,redeem,protectedTransfer and batch functions */ contract SilaUsd is AuthorizeDeveloper{ using SafeMath for uint256; // parameters for silatoken string public constant name = "SILAUSD"; string public constant symbol = "SILA"; uint256 public constant decimals = 18; string public constant version = "2.0"; // Events fired during successfull execution of main silatoken functions event Issued(address indexed _to, uint256 _value); event Redeemed(address indexed _from, uint256 _amount); event ProtectedTransfer(address indexed _from, address indexed _to, uint256 _amount); event GlobalLaunchSila(address indexed _launcher); event DestroyedBlackFunds(address _blackListedUser, uint _dirtyFunds); /** * @dev issue tokens from sila to _to address * @dev only authorized addresses are allowed to call this function * @param _to address The address which you want to transfer to * @param _amount uint256 the amount of tokens to be issued */ function issue(address _to, uint256 _amount) public acceptableTransactors(Arrays.arr(_to)) onlyAuthorized returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Issued(_to, _amount); return true; } /** * @dev redeem tokens from _from address * @dev onlyAuthorized addresses can call this function * @param _from address is the address from which tokens are burnt * @param _amount uint256 the amount of tokens to be burnt */ function redeem(address _from, uint256 _amount) public acceptableTransactors(Arrays.arr(_from)) onlyAuthorized returns(bool) { require(_amount <= balances[_from]); balances[_from] = balances[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); emit Redeemed(_from, _amount); return true; } /** * @dev Transfer tokens from one address to another * @dev onlyAuthorized addresses can call this function * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _amount uint256 the amount of tokens to be transferred */ function protectedTransfer(address _from, address _to, uint256 _amount) public acceptableTransactors(Arrays.arr(_from, _to)) onlyAuthorized returns(bool) { require(_amount <= balances[_from]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); emit ProtectedTransfer(_from, _to, _amount); emit Transfer(_from, _to, _amount); return true; } /** * @dev destroy the funds of a blacklisted address * @param _blackListedUser the blacklisted user address for which the funds need to be destroyed */ function destroyBlackFunds(address _blackListedUser) public onlyAuthorized { require(blacklisted[_blackListedUser]); uint dirtyFunds = balanceOf(_blackListedUser); balances[_blackListedUser] = 0; totalSupply = totalSupply.sub(dirtyFunds); emit DestroyedBlackFunds(_blackListedUser, dirtyFunds); } /** * @dev Launch sila for global transfer function to work as standard */ function globalLaunchSila() public onlyHotOwner { require(!emergencyFlag); require(requireBetalisted); requireBetalisted = false; emit GlobalLaunchSila(msg.sender); } /** * @dev batchissue , isuue tokens in batches to multiple addresses at a time * @param _amounts The amount of tokens to be issued. * @param _toAddresses tokens to be issued to these addresses respectively */ function batchIssue(address[] memory _toAddresses, uint256[] memory _amounts) public onlyAuthorized returns(bool) { require(_toAddresses.length == _amounts.length); for(uint i = 0; i < _toAddresses.length; i++) { bool check = issue(_toAddresses[i],_amounts[i]); require(check); } return true; } /** * @dev batchredeem , redeem tokens in batches from multiple addresses at a time * @param _amounts array of amount of tokens to be redeemed. * @param _fromAddresses array of addresses from which tokens to be redeemed respectively */ function batchRedeem(address[] memory _fromAddresses, uint256[] memory _amounts) public onlyAuthorized returns(bool) { require(_fromAddresses.length == _amounts.length); for(uint i = 0; i < _fromAddresses.length; i++) { bool check = redeem(_fromAddresses[i],_amounts[i]); require(check); } return true; } /** * @dev batchTransfer, transfer tokens in batches between multiple addresses at a time * @param _fromAddresses tokens to be transfered to these addresses respectively * @param _toAddresses tokens to be transfered to these addresses respectively * @param _amounts The amount of tokens to be transfered */ function protectedBatchTransfer(address[] memory _fromAddresses, address[] memory _toAddresses, uint256[] memory _amounts) public onlyAuthorized returns(bool) { require(_fromAddresses.length == _amounts.length); require(_toAddresses.length == _amounts.length); require(_fromAddresses.length == _toAddresses.length); for(uint i = 0; i < _fromAddresses.length; i++) { bool check = protectedTransfer(_fromAddresses[i], _toAddresses[i], _amounts[i]); require(check); } return true; } }
maps for betalisted and blacklisted addresses events for betalist and blacklist variable to check if betalist is required when calling several functions on smart contract constructor
contract Betalist is Authorizable { mapping(address => bool) betalisted; mapping(address => bool) blacklisted; event BetalistedAddress (address indexed _betalisted); event BlacklistedAddress (address indexed _blacklisted); event RemovedAddressFromBlacklist(address indexed _toRemoveBlacklist); event RemovedAddressFromBetalist(address indexed _toRemoveBetalist); bool public requireBetalisted; constructor () public { requireBetalisted = true; } modifier acceptableTransactors(address[] memory addresses) { require(!emergencyFlag); if (requireBetalisted){ for(uint i = 0; i < addresses.length; i++) require( betalisted[addresses[i]] ); } for(uint i = 0; i < addresses.length; i++) { address addr = addresses[i]; require(addr != address(0)); require(!blacklisted[addr]); } _; } modifier acceptableTransactors(address[] memory addresses) { require(!emergencyFlag); if (requireBetalisted){ for(uint i = 0; i < addresses.length; i++) require( betalisted[addresses[i]] ); } for(uint i = 0; i < addresses.length; i++) { address addr = addresses[i]; require(addr != address(0)); require(!blacklisted[addr]); } _; } modifier acceptableTransactors(address[] memory addresses) { require(!emergencyFlag); if (requireBetalisted){ for(uint i = 0; i < addresses.length; i++) require( betalisted[addresses[i]] ); } for(uint i = 0; i < addresses.length; i++) { address addr = addresses[i]; require(addr != address(0)); require(!blacklisted[addr]); } _; } function betalistAddress(address _toBetalist) public onlyAuthorized returns(bool) { require(!emergencyFlag); require(_toBetalist != address(0)); require(!blacklisted[_toBetalist]); require(!betalisted[_toBetalist]); betalisted[_toBetalist] = true; emit BetalistedAddress(_toBetalist); return true; } function removeAddressFromBetalist(address _toRemoveBetalist) public onlyAuthorized { require(!emergencyFlag); require(_toRemoveBetalist != address(0)); require(betalisted[_toRemoveBetalist]); betalisted[_toRemoveBetalist] = false; emit RemovedAddressFromBetalist(_toRemoveBetalist); } function blacklistAddress(address _toBlacklist) public onlyAuthorized returns(bool) { require(!emergencyFlag); require(_toBlacklist != address(0)); require(!blacklisted[_toBlacklist]); blacklisted[_toBlacklist] = true; emit BlacklistedAddress(_toBlacklist); return true; } function removeAddressFromBlacklist(address _toRemoveBlacklist) public onlyAuthorized { require(!emergencyFlag); require(_toRemoveBlacklist != address(0)); require(blacklisted[_toRemoveBlacklist]); blacklisted[_toRemoveBlacklist] = false; emit RemovedAddressFromBlacklist(_toRemoveBlacklist); } function batchBlacklistAddresses(address[] memory _toBlacklistAddresses) public onlyAuthorized returns(bool) { for(uint i = 0; i < _toBlacklistAddresses.length; i++) { bool check = blacklistAddress(_toBlacklistAddresses[i]); require(check); } return true; } function batchBlacklistAddresses(address[] memory _toBlacklistAddresses) public onlyAuthorized returns(bool) { for(uint i = 0; i < _toBlacklistAddresses.length; i++) { bool check = blacklistAddress(_toBlacklistAddresses[i]); require(check); } return true; } function batchBetalistAddresses(address[] memory _toBetalistAddresses) public onlyAuthorized returns(bool) { for(uint i = 0; i < _toBetalistAddresses.length; i++) { bool check = betalistAddress(_toBetalistAddresses[i]); require(check); } return true; } function batchBetalistAddresses(address[] memory _toBetalistAddresses) public onlyAuthorized returns(bool) { for(uint i = 0; i < _toBetalistAddresses.length; i++) { bool check = betalistAddress(_toBetalistAddresses[i]); require(check); } return true; } function isBetalisted(address _betalisted) external view returns(bool) { return (betalisted[_betalisted]); } function isBlacklisted(address _blacklisted) external view returns(bool) { return (blacklisted[_blacklisted]); } }
988,491
[ 1, 10711, 364, 2701, 287, 25444, 471, 25350, 6138, 2641, 364, 2701, 287, 376, 471, 11709, 2190, 358, 866, 309, 2701, 287, 376, 353, 1931, 1347, 4440, 11392, 4186, 603, 13706, 6835, 3885, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6835, 605, 278, 287, 376, 353, 3123, 5331, 429, 288, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 2701, 287, 25444, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 25350, 31, 203, 203, 565, 871, 605, 278, 287, 25444, 1887, 261, 2867, 8808, 389, 70, 278, 287, 25444, 1769, 203, 565, 871, 22467, 18647, 1887, 261, 2867, 8808, 389, 11223, 18647, 1769, 203, 565, 871, 2663, 9952, 1887, 1265, 25811, 12, 2867, 8808, 389, 869, 3288, 25811, 1769, 203, 565, 871, 2663, 9952, 1887, 1265, 38, 278, 287, 376, 12, 2867, 8808, 389, 869, 3288, 38, 278, 287, 376, 1769, 203, 203, 565, 1426, 1071, 2583, 38, 278, 287, 25444, 31, 203, 7010, 7010, 565, 3885, 1832, 1071, 288, 203, 3639, 2583, 38, 278, 287, 25444, 273, 638, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 9606, 14206, 1429, 621, 1383, 12, 2867, 8526, 3778, 6138, 13, 288, 203, 3639, 2583, 12, 5, 351, 24530, 4678, 1769, 203, 3639, 309, 261, 6528, 38, 278, 287, 25444, 15329, 203, 1850, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 6138, 18, 2469, 31, 277, 27245, 2583, 12, 2701, 287, 25444, 63, 13277, 63, 77, 13563, 11272, 203, 3639, 289, 203, 3639, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 6138, 18, 2469, 31, 277, 27245, 288, 203, 1850, 1758, 3091, 273, 6138, 63, 77, 15533, 203, 1850, 2583, 12, 4793, 480, 1758, 12, 20, 10019, 203, 1850, 2583, 12, 5, 11223, 18647, 63, 4793, 19226, 203, 3639, 289, 203, 3639, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-08-31 */ /** *Submitted for verification at Etherscan.io on 2020-08-25 */ pragma solidity >= 0.5.0 < 0.7.0; /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain /// @author Richard Meissner - <[email protected]> interface IProxy { function masterCopy() external view returns (address); } /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract GnosisSafeProxy { // masterCopy always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt` address internal masterCopy; /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. constructor(address _masterCopy) public { require(_masterCopy != address(0), "Invalid master copy address provided"); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function () external payable { // solium-disable-next-line security/no-inline-assembly assembly { let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) { mstore(0, masterCopy) return(0, 0x20) } calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } } interface IProxyCreationCallback { function proxyCreated(GnosisSafeProxy proxy, address _mastercopy, bytes calldata initializer, uint256 saltNonce) external; } /// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @author Stefan George - <[email protected]> contract GnosisSafeProxyFactory { event ProxyCreation(GnosisSafeProxy proxy); /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param masterCopy Address of master copy. /// @param data Payload for message call sent to new proxy contract. function createProxy(address masterCopy, bytes memory data) public returns (GnosisSafeProxy proxy) { proxy = new GnosisSafeProxy(masterCopy); if (data.length > 0) // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit ProxyCreation(proxy); } /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed. function proxyRuntimeCode() public pure returns (bytes memory) { return type(GnosisSafeProxy).runtimeCode; } /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address. function proxyCreationCode() public pure returns (bytes memory) { return type(GnosisSafeProxy).creationCode; } /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer. /// This method is only meant as an utility to be called from other methods /// @param _mastercopy Address of master copy. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function deployProxyWithNonce(address _mastercopy, bytes memory initializer, uint256 saltNonce) internal returns (GnosisSafeProxy proxy) { // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce)); bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(_mastercopy)); // solium-disable-next-line security/no-inline-assembly assembly { proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt) } require(address(proxy) != address(0), "Create2 call failed"); } /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param _mastercopy Address of master copy. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function createProxyWithNonce(address _mastercopy, bytes memory initializer, uint256 saltNonce) public returns (GnosisSafeProxy proxy) { proxy = deployProxyWithNonce(_mastercopy, initializer, saltNonce); if (initializer.length > 0) // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) { revert(0,0) } } emit ProxyCreation(proxy); } /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction /// @param _mastercopy Address of master copy. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized. function createProxyWithCallback(address _mastercopy, bytes memory initializer, uint256 saltNonce, IProxyCreationCallback callback) public returns (GnosisSafeProxy proxy) { uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback))); proxy = createProxyWithNonce(_mastercopy, initializer, saltNonceWithCallback); if (address(callback) != address(0)) callback.proxyCreated(proxy, _mastercopy, initializer, saltNonce); } /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce` /// This method is only meant for address calculation purpose when you use an initializer that would revert, /// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory. /// @param _mastercopy Address of master copy. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function calculateCreateProxyWithNonceAddress(address _mastercopy, bytes calldata initializer, uint256 saltNonce) external returns (GnosisSafeProxy proxy) { proxy = deployProxyWithNonce(_mastercopy, initializer, saltNonce); revert(string(abi.encodePacked(proxy))); } } /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation { Call, DelegateCall } } /// @title SelfAuthorized - authorizes current contract to perform actions /// @author Richard Meissner - <[email protected]> contract SelfAuthorized { modifier authorized() { require(msg.sender == address(this), "Method can only be called from this contract"); _; } } /// @title Executor - A contract that can execute transactions /// @author Richard Meissner - <[email protected]> contract Executor { function execute(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txGas) internal returns (bool success) { if (operation == Enum.Operation.Call) success = executeCall(to, value, data, txGas); else if (operation == Enum.Operation.DelegateCall) success = executeDelegateCall(to, data, txGas); else success = false; } function executeCall(address to, uint256 value, bytes memory data, uint256 txGas) internal returns (bool success) { // solium-disable-next-line security/no-inline-assembly assembly { success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) } } function executeDelegateCall(address to, bytes memory data, uint256 txGas) internal returns (bool success) { // solium-disable-next-line security/no-inline-assembly assembly { success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0) } } } /// @title MasterCopy - Base for master copy contracts (should always be first super contract) /// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`) /// @author Richard Meissner - <[email protected]> contract MasterCopy is SelfAuthorized { event ChangedMasterCopy(address masterCopy); // masterCopy always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract. // It should also always be ensured that the address is stored alone (uses a full word) address private masterCopy; /// @dev Allows to upgrade the contract. This can only be done via a Safe transaction. /// @param _masterCopy New contract address. function changeMasterCopy(address _masterCopy) public authorized { // Master copy address cannot be null. require(_masterCopy != address(0), "Invalid master copy address provided"); masterCopy = _masterCopy; emit ChangedMasterCopy(_masterCopy); } } /// @title Module Manager - A contract that manages modules that can execute transactions via this contract /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract ModuleManager is SelfAuthorized, Executor { event EnabledModule(Module module); event DisabledModule(Module module); event ExecutionFromModuleSuccess(address indexed module); event ExecutionFromModuleFailure(address indexed module); address internal constant SENTINEL_MODULES = address(0x1); mapping (address => address) internal modules; function setupModules(address to, bytes memory data) internal { require(modules[SENTINEL_MODULES] == address(0), "Modules have already been initialized"); modules[SENTINEL_MODULES] = SENTINEL_MODULES; if (to != address(0)) // Setup has to complete successfully or transaction fails. require(executeDelegateCall(to, data, gasleft()), "Could not finish initialization"); } /// @dev Allows to add a module to the whitelist. /// This can only be done via a Safe transaction. /// @param module Module to be whitelisted. function enableModule(Module module) public authorized { // Module address cannot be null or sentinel. require(address(module) != address(0) && address(module) != SENTINEL_MODULES, "Invalid module address provided"); // Module cannot be added twice. require(modules[address(module)] == address(0), "Module has already been added"); modules[address(module)] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = address(module); emit EnabledModule(module); } /// @dev Allows to remove a module from the whitelist. /// This can only be done via a Safe transaction. /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(Module prevModule, Module module) public authorized { // Validate module address and check that it corresponds to module index. require(address(module) != address(0) && address(module) != SENTINEL_MODULES, "Invalid module address provided"); require(modules[address(prevModule)] == address(module), "Invalid prevModule, module pair provided"); modules[address(prevModule)] = modules[address(module)]; modules[address(module)] = address(0); emit DisabledModule(module); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule(address to, uint256 value, bytes memory data, Enum.Operation operation) public returns (bool success) { // Only whitelisted modules are allowed. require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "Method can only be called from an enabled module"); // Execute transaction without further confirmations. success = execute(to, value, data, operation, gasleft()); if (success) emit ExecutionFromModuleSuccess(msg.sender); else emit ExecutionFromModuleFailure(msg.sender); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModuleReturnData(address to, uint256 value, bytes memory data, Enum.Operation operation) public returns (bool success, bytes memory returnData) { success = execTransactionFromModule(to, value, data, operation); // solium-disable-next-line security/no-inline-assembly assembly { // Load free memory location let ptr := mload(0x40) // We allocate memory for the return data by setting the free memory location to // current free memory location + data size + 32 bytes for data size value mstore(0x40, add(ptr, add(returndatasize(), 0x20))) // Store the size mstore(ptr, returndatasize()) // Store the data returndatacopy(add(ptr, 0x20), 0, returndatasize()) // Point the return data to the correct memory location returnData := ptr } } /// @dev Returns array of first 10 modules. /// @return Array of modules. function getModules() public view returns (address[] memory) { (address[] memory array,) = getModulesPaginated(SENTINEL_MODULES, 10); return array; } /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return Array of modules. function getModulesPaginated(address start, uint256 pageSize) public view returns (address[] memory array, address next) { // Init array with max page size array = new address[](pageSize); // Populate return array uint256 moduleCount = 0; address currentModule = modules[start]; while(currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount++; } next = currentModule; // Set correct size of returned array // solium-disable-next-line security/no-inline-assembly assembly { mstore(array, moduleCount) } } } /// @title Module - Base class for modules. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract Module is MasterCopy { ModuleManager public manager; modifier authorized() { require(msg.sender == address(manager), "Method can only be called from manager"); _; } function setManager() internal { // manager can only be 0 at initalization of contract. // Check ensures that setup function can only be called once. require(address(manager) == address(0), "Manager has already been set"); manager = ModuleManager(msg.sender); } } /// @title OwnerManager - Manages a set of owners and a threshold to perform actions. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract OwnerManager is SelfAuthorized { event AddedOwner(address owner); event RemovedOwner(address owner); event ChangedThreshold(uint256 threshold); address internal constant SENTINEL_OWNERS = address(0x1); mapping(address => address) internal owners; uint256 ownerCount; uint256 internal threshold; /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. function setupOwners(address[] memory _owners, uint256 _threshold) internal { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "Owners have already been setup"); // Validate that threshold is smaller than number of added owners. require(_threshold <= _owners.length, "Threshold cannot exceed owner count"); // There has to be at least one Safe owner. require(_threshold >= 1, "Threshold needs to be greater than 0"); // Initializing Safe owners. address currentOwner = SENTINEL_OWNERS; for (uint256 i = 0; i < _owners.length; i++) { // Owner address cannot be null. address owner = _owners[i]; require(owner != address(0) && owner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[owner] == address(0), "Duplicate owner address provided"); owners[currentOwner] = owner; currentOwner = owner; } owners[currentOwner] = SENTINEL_OWNERS; ownerCount = _owners.length; threshold = _threshold; } /// @dev Allows to add a new owner to the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @param owner New owner address. /// @param _threshold New threshold. function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized { // Owner address cannot be null. require(owner != address(0) && owner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[owner] == address(0), "Address is already an owner"); owners[owner] = owners[SENTINEL_OWNERS]; owners[SENTINEL_OWNERS] = owner; ownerCount++; emit AddedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to remove an owner from the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @param prevOwner Owner that pointed to the owner to be removed in the linked list /// @param owner Owner address to be removed. /// @param _threshold New threshold. function removeOwner(address prevOwner, address owner, uint256 _threshold) public authorized { // Only allow to remove an owner, if threshold can still be reached. require(ownerCount - 1 >= _threshold, "New owner count needs to be larger than new threshold"); // Validate owner address and check that it corresponds to owner index. require(owner != address(0) && owner != SENTINEL_OWNERS, "Invalid owner address provided"); require(owners[prevOwner] == owner, "Invalid prevOwner, owner pair provided"); owners[prevOwner] = owners[owner]; owners[owner] = address(0); ownerCount--; emit RemovedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to swap/replace an owner from the Safe with another address. /// This can only be done via a Safe transaction. /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list /// @param oldOwner Owner address to be replaced. /// @param newOwner New owner address. function swapOwner(address prevOwner, address oldOwner, address newOwner) public authorized { // Owner address cannot be null. require(newOwner != address(0) && newOwner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[newOwner] == address(0), "Address is already an owner"); // Validate oldOwner address and check that it corresponds to owner index. require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "Invalid owner address provided"); require(owners[prevOwner] == oldOwner, "Invalid prevOwner, owner pair provided"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = address(0); emit RemovedOwner(oldOwner); emit AddedOwner(newOwner); } /// @dev Allows to update the number of required confirmations by Safe owners. /// This can only be done via a Safe transaction. /// @param _threshold New threshold. function changeThreshold(uint256 _threshold) public authorized { // Validate that threshold is smaller than number of owners. require(_threshold <= ownerCount, "Threshold cannot exceed owner count"); // There has to be at least one Safe owner. require(_threshold >= 1, "Threshold needs to be greater than 0"); threshold = _threshold; emit ChangedThreshold(threshold); } function getThreshold() public view returns (uint256) { return threshold; } function isOwner(address owner) public view returns (bool) { return owner != SENTINEL_OWNERS && owners[owner] != address(0); } /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() public view returns (address[] memory) { address[] memory array = new address[](ownerCount); // populate return array uint256 index = 0; address currentOwner = owners[SENTINEL_OWNERS]; while(currentOwner != SENTINEL_OWNERS) { array[index] = currentOwner; currentOwner = owners[currentOwner]; index ++; } return array; } } /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract FallbackManager is SelfAuthorized { // keccak256("fallback_manager.handler.address") bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5; function internalSetFallbackHandler(address handler) internal { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solium-disable-next-line security/no-inline-assembly assembly { sstore(slot, handler) } } /// @dev Allows to add a contract to handle fallback calls. /// Only fallback calls without value and with data will be forwarded. /// This can only be done via a Safe transaction. /// @param handler contract to handle fallbacks calls. function setFallbackHandler(address handler) public authorized { internalSetFallbackHandler(handler); } function () external payable { // Only calls without value and with data will be forwarded if (msg.value > 0 || msg.data.length == 0) { return; } bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; address handler; // solium-disable-next-line security/no-inline-assembly assembly { handler := sload(slot) } if (handler != address(0)) { // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let success := call(gas, handler, 0, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } } } /// @title SignatureDecoder - Decodes signatures that a encoded as bytes /// @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) /// @author Richard Meissner - <[email protected]> contract SignatureDecoder { /// @dev Recovers address who signed the message /// @param messageHash operation ethereum signed message hash /// @param messageSignature message `txHash` signature /// @param pos which signature to read function recoverKey ( bytes32 messageHash, bytes memory messageSignature, uint256 pos ) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = signatureSplit(messageSignature, pos); return ecrecover(messageHash, v, r, s); } /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`. /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access /// @param signatures concatenated rsv signatures function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns (uint8 v, bytes32 r, bytes32 s) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. // solium-disable-next-line security/no-inline-assembly assembly { let signaturePos := mul(0x41, pos) r := mload(add(signatures, add(signaturePos, 0x20))) s := mload(add(signatures, add(signaturePos, 0x40))) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff) } } } /// @title SecuredTokenTransfer - Secure token transfer /// @author Richard Meissner - <[email protected]> contract SecuredTokenTransfer { /// @dev Transfers a token and returns if it was a success /// @param token Token that should be transferred /// @param receiver Receiver to whom the token should be transferred /// @param amount The amount of tokens that should be transferred function transferToken ( address token, address receiver, uint256 amount ) internal returns (bool transferred) { bytes memory data = abi.encodeWithSignature("transfer(address,uint256)", receiver, amount); // solium-disable-next-line security/no-inline-assembly assembly { let success := call(sub(gas, 10000), token, 0, add(data, 0x20), mload(data), 0, 0) let ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize())) returndatacopy(ptr, 0, returndatasize()) switch returndatasize() case 0 { transferred := success } case 0x20 { transferred := iszero(or(iszero(success), iszero(mload(ptr)))) } default { transferred := 0 } } } } contract ISignatureValidatorConstants { // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 constant internal EIP1271_MAGIC_VALUE = 0x20c13b0b; } contract ISignatureValidator is ISignatureValidatorConstants { /** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x20c13b0b when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature( bytes memory _data, bytes memory _signature) public view returns (bytes4); } /** * @title GnosisSafeMath * @dev Math operations with safety checks that revert on error * Renamed from SafeMath to GnosisSafeMath to avoid conflicts * TODO: remove once open zeppelin update to solc 0.5.0 */ library GnosisSafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> /// @author Ricardo Guilherme Schmidt - (Status Research & Development GmbH) - Gas Token Payment contract GnosisSafe is MasterCopy, ModuleManager, OwnerManager, SignatureDecoder, SecuredTokenTransfer, ISignatureValidatorConstants, FallbackManager { using GnosisSafeMath for uint256; string public constant NAME = "Gnosis Safe"; string public constant VERSION = "1.1.1"; //keccak256( // "EIP712Domain(address verifyingContract)" //); bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x035aff83d86937d35b32e04f0ddc6ff469290eef2f1b692d8a815c89404d4749; //keccak256( // "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)" //); bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8; //keccak256( // "SafeMessage(bytes message)" //); bytes32 private constant SAFE_MSG_TYPEHASH = 0x60b3cbf8b4a223d68d641b3b6ddf9a298e7f33710cf3d3a9d1146b5a6150fbca; event ApproveHash( bytes32 indexed approvedHash, address indexed owner ); event SignMsg( bytes32 indexed msgHash ); event ExecutionFailure( bytes32 txHash, uint256 payment ); event ExecutionSuccess( bytes32 txHash, uint256 payment ); uint256 public nonce; bytes32 public domainSeparator; // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners mapping(bytes32 => uint256) public signedMessages; // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners mapping(address => mapping(bytes32 => uint256)) public approvedHashes; // This constructor ensures that this contract can only be used as a master copy for Proxy contracts constructor() public { // By setting the threshold it is not possible to call setup anymore, // so we create a Safe with 0 owners and threshold 1. // This is an unusable Safe, perfect for the mastercopy threshold = 1; } /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. /// @param to Contract address for optional delegate call. /// @param data Data payload for optional delegate call. /// @param fallbackHandler Handler for fallback calls to this contract /// @param paymentToken Token that should be used for the payment (0 is ETH) /// @param payment Value that should be paid /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin) function setup( address[] calldata _owners, uint256 _threshold, address to, bytes calldata data, address fallbackHandler, address paymentToken, uint256 payment, address payable paymentReceiver ) external { require(domainSeparator == 0, "Domain Separator already set!"); domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, this)); setupOwners(_owners, _threshold); if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler); // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules setupModules(to, data); if (payment > 0) { // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself) // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment handlePayment(payment, 0, 1, paymentToken, paymentReceiver); } } /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. /// Note: The fees are always transfered, even if the user transaction fails. /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @param safeTxGas Gas that should be used for the Safe transaction. /// @param baseGas Gas costs for that are indipendent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Gas price that should be used for the payment calculation. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) function execTransaction( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes calldata signatures ) external returns (bool success) { bytes32 txHash; // Use scope here to limit variable lifetime and prevent `stack too deep` errors { bytes memory txHashData = encodeTransactionData( to, value, data, operation, // Transaction info safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, // Payment info nonce ); // Increase nonce and execute transaction. nonce++; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures, true); } require(gasleft() >= safeTxGas, "Not enough gas to execute safe transaction"); // Use scope here to limit variable lifetime and prevent `stack too deep` errors { uint256 gasUsed = gasleft(); // If no safeTxGas has been set and the gasPrice is 0 we assume that all available gas can be used success = execute(to, value, data, operation, safeTxGas == 0 && gasPrice == 0 ? gasleft() : safeTxGas); gasUsed = gasUsed.sub(gasleft()); // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls uint256 payment = 0; if (gasPrice > 0) { payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver); } if (success) emit ExecutionSuccess(txHash, payment); else emit ExecutionFailure(txHash, payment); } } function handlePayment( uint256 gasUsed, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver ) private returns (uint256 payment) { // solium-disable-next-line security/no-tx-origin address payable receiver = refundReceiver == address(0) ? tx.origin : refundReceiver; if (gasToken == address(0)) { // For ETH we will only adjust the gas price to not be higher than the actual used gas price payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice); // solium-disable-next-line security/no-send require(receiver.send(payment), "Could not pay gas costs with ether"); } else { payment = gasUsed.add(baseGas).mul(gasPrice); require(transferToken(gasToken, receiver, payment), "Could not pay gas costs with token"); } } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. * @param consumeHash Indicates that in case of an approved hash the storage can be freed to save gas */ function checkSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures, bool consumeHash) internal { // Load threshold to avoid multiple storage loads uint256 _threshold = threshold; // Check that a threshold is set require(_threshold > 0, "Threshold needs to be defined!"); // Check that the provided signature data is not too short require(signatures.length >= _threshold.mul(65), "Signatures data too short"); // There cannot be an owner with address 0. address lastOwner = address(0); address currentOwner; uint8 v; bytes32 r; bytes32 s; uint256 i; for (i = 0; i < _threshold; i++) { (v, r, s) = signatureSplit(signatures, i); // If v is 0 then it is a contract signature if (v == 0) { // When handling contract signatures the address of the contract is encoded into r currentOwner = address(uint256(r)); // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes // This check is not completely accurate, since it is possible that more signatures than the threshold are send. // Here we only check that the pointer is not pointing inside the part that is being processed require(uint256(s) >= _threshold.mul(65), "Invalid contract signature location: inside static part"); // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes) require(uint256(s).add(32) <= signatures.length, "Invalid contract signature location: length not present"); // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length uint256 contractSignatureLen; // solium-disable-next-line security/no-inline-assembly assembly { contractSignatureLen := mload(add(add(signatures, s), 0x20)) } require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "Invalid contract signature location: data not complete"); // Check signature bytes memory contractSignature; // solium-disable-next-line security/no-inline-assembly assembly { // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s contractSignature := add(add(signatures, s), 0x20) } require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "Invalid contract signature provided"); // If v is 1 then it is an approved hash } else if (v == 1) { // When handling approved hashes the address of the approver is encoded into r currentOwner = address(uint256(r)); // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "Hash has not been approved"); // Hash has been marked for consumption. If this hash was pre-approved free storage if (consumeHash && msg.sender != currentOwner) { approvedHashes[currentOwner][dataHash] = 0; } } else if (v > 30) { // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover currentOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s); } else { // Use ecrecover with the messageHash for EOA signatures currentOwner = ecrecover(dataHash, v, r, s); } require ( currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "Invalid owner provided" ); lastOwner = currentOwner; } } /// @dev Allows to estimate a Safe transaction. /// This method is only meant for estimation purpose, therefore two different protection mechanism against execution in a transaction have been made: /// 1.) The method can only be called from the safe itself /// 2.) The response is returned with a revert /// When estimating set `from` to the address of the safe. /// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction` /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs). function requiredTxGas(address to, uint256 value, bytes calldata data, Enum.Operation operation) external authorized returns (uint256) { uint256 startGas = gasleft(); // We don't provide an error message here, as we use it to return the estimate // solium-disable-next-line error-reason require(execute(to, value, data, operation, gasleft())); uint256 requiredGas = startGas - gasleft(); // Convert response to string and return via error message revert(string(abi.encodePacked(requiredGas))); } /** * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature. * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract. */ function approveHash(bytes32 hashToApprove) external { require(owners[msg.sender] != address(0), "Only owners can approve a hash"); approvedHashes[msg.sender][hashToApprove] = 1; emit ApproveHash(hashToApprove, msg.sender); } /** * @dev Marks a message as signed * @param _data Arbitrary length data that should be marked as signed on the behalf of address(this) */ function signMessage(bytes calldata _data) external authorized { bytes32 msgHash = getMessageHash(_data); signedMessages[msgHash] = 1; emit SignMsg(msgHash); } /** * Implementation of ISignatureValidator (see `interfaces/ISignatureValidator.sol`) * @dev Should return whether the signature provided is valid for the provided data. * The save does not implement the interface since `checkSignatures` is not a view method. * The method will not perform any state changes (see parameters of `checkSignatures`) * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return a bool upon valid or invalid signature with corresponding _data */ function isValidSignature(bytes calldata _data, bytes calldata _signature) external returns (bytes4) { bytes32 messageHash = getMessageHash(_data); if (_signature.length == 0) { require(signedMessages[messageHash] != 0, "Hash not approved"); } else { // consumeHash needs to be false, as the state should not be changed checkSignatures(messageHash, _data, _signature, false); } return EIP1271_MAGIC_VALUE; } /// @dev Returns hash of a message that can be signed by owners. /// @param message Message that should be hashed /// @return Message hash. function getMessageHash( bytes memory message ) public view returns (bytes32) { bytes32 safeMessageHash = keccak256( abi.encode(SAFE_MSG_TYPEHASH, keccak256(message)) ); return keccak256( abi.encodePacked(byte(0x19), byte(0x01), domainSeparator, safeMessageHash) ); } /// @dev Returns the bytes that are hashed to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Fas that should be used for the safe transaction. /// @param baseGas Gas costs for data used to trigger the safe transaction. /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash bytes. function encodeTransactionData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes memory) { bytes32 safeTxHash = keccak256( abi.encode(SAFE_TX_TYPEHASH, to, value, keccak256(data), operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce) ); return abi.encodePacked(byte(0x19), byte(0x01), domainSeparator, safeTxHash); } /// @dev Returns hash to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Fas that should be used for the safe transaction. /// @param baseGas Gas costs for data used to trigger the safe transaction. /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash. function getTransactionHash( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes32) { return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce)); } } contract FleetFactoryDeterministic { GnosisSafeProxyFactory public proxyFactory; event FleetDeployed(address indexed owner, address[] fleet); constructor(GnosisSafeProxyFactory _proxyFactory) public { proxyFactory = _proxyFactory; } function deployFleetWithNonce(address owner, uint256 size, address template, uint256 saltNonce) external { GnosisSafeProxyFactory _proxyFactory = proxyFactory; address[] memory fleet = new address[](size); address[] memory ownerList = new address[](1); ownerList[0] = owner; for (uint i = 0; i < size; i++) { address payable proxy = address( _proxyFactory.createProxyWithNonce( template, "", uint256( keccak256( abi.encodePacked(saltNonce, i) ) ) ) ); fleet[i] = proxy; require(fleet[i] != address(0), "fleet deployment failed"); GnosisSafe safe = GnosisSafe(proxy); // safe is set up to have a single owner safe.setup( ownerList, 1, address(0), "", address(0), address(0), 0, address(0) ); } emit FleetDeployed(owner, fleet); } }
@dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. @param _mastercopy Address of master copy. @param initializer Payload for message call sent to new proxy contract. @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. solium-disable-next-line security/no-inline-assembly
function createProxyWithNonce(address _mastercopy, bytes memory initializer, uint256 saltNonce) public returns (GnosisSafeProxy proxy) { proxy = deployProxyWithNonce(_mastercopy, initializer, saltNonce); if (initializer.length > 0) assembly { } emit ProxyCreation(proxy); }
330,429
[ 1, 19132, 358, 752, 394, 2889, 5388, 471, 1836, 279, 883, 745, 358, 326, 394, 2889, 3470, 1245, 2492, 18, 225, 389, 7525, 3530, 5267, 434, 4171, 1610, 18, 225, 12562, 11320, 364, 883, 745, 3271, 358, 394, 2889, 6835, 18, 225, 4286, 13611, 25261, 716, 903, 506, 1399, 358, 2103, 326, 4286, 358, 4604, 326, 1758, 434, 326, 394, 2889, 6835, 18, 3704, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 3886, 1190, 13611, 12, 2867, 389, 7525, 3530, 16, 1731, 3778, 12562, 16, 2254, 5034, 4286, 13611, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 43, 18050, 291, 9890, 3886, 2889, 13, 203, 565, 288, 203, 3639, 2889, 273, 7286, 3886, 1190, 13611, 24899, 7525, 3530, 16, 12562, 16, 4286, 13611, 1769, 203, 3639, 309, 261, 22181, 18, 2469, 405, 374, 13, 203, 5411, 19931, 288, 203, 5411, 289, 203, 3639, 3626, 7659, 9906, 12, 5656, 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 ]
pragma solidity ^0.4.20; contract CDP { /* DECLARING VARIABLES */ address public owner; /* MAPPING */ /* EVENTS */ event logDeposit (uint id); /* MODIFIERS */ // validate the CDP id exists modifier CDPExists(uint _id) { require( oraclize() ) } /* STRUCTS */ /* CONSTRUCTUR */ cunstructor() public { owner = msg.sender; } /* VIEWS */ /* METHODS */ function addCDP(uint _id) public { // 1. validate id requested is less than total id's available // 2. validate that for the id requested, the message sender is the same // as the CDP owner address. } }
STRUCTS */ CONSTRUCTUR */
cunstructor() public { owner = msg.sender; }
12,672,406
[ 1, 13915, 55, 342, 3492, 13915, 1099, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 276, 318, 2732, 1435, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-15 */ pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/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. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/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; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be 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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/ownership/Secondary.sol pragma solidity ^0.5.0; /** * @dev A Secondary contract can only be used by its primary account (the one that created it). */ contract Secondary is Context { address private _primary; /** * @dev Emitted when the primary contract changes. */ event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () internal { address msgSender = _msgSender(); _primary = msgSender; emit PrimaryTransferred(msgSender); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(_msgSender() == _primary, "Secondary: caller is not the primary account"); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0), "Secondary: new primary is the zero address"); _primary = recipient; emit PrimaryTransferred(recipient); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/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; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/Crowdsale.sol pragma solidity ^0.5.0; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/validation/CappedCrowdsale.sol pragma solidity ^0.5.0; /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param cap Max amount of wei to be contributed */ constructor (uint256 cap) public { require(cap > 0, "CappedCrowdsale: cap is 0"); _cap = cap; } /** * @return the cap of the crowdsale. */ function cap() public view returns (uint256) { return _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised() >= _cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= _cap, "CappedCrowdsale: cap exceeded"); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/validation/PausableCrowdsale.sol pragma solidity ^0.5.0; /** * @title PausableCrowdsale * @dev Extension of Crowdsale contract where purchases can be paused and unpaused by the pauser role. */ contract PausableCrowdsale is Crowdsale, Pausable { /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use super to concatenate validations. * Adds the validation that the crowdsale must not be paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view whenNotPaused { return super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/validation/TimedCrowdsale.sol pragma solidity ^0.5.0; /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; // EDIT: changed from private to internal uint256 internal _openingTime; uint256 internal _closingTime; /** * Event for crowdsale extending * @param newClosingTime new closing time * @param prevClosingTime old closing time */ event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen(), "TimedCrowdsale: not open"); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor (uint256 openingTime, uint256 closingTime) public { // EDIT: removed requirement to open in future // solhint-disable-next-line not-rely-on-time // require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time"); // solhint-disable-next-line max-line-length require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time"); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns (uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Extend crowdsale. * @param newClosingTime Crowdsale closing time */ function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsale: already closed"); // solhint-disable-next-line max-line-length require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time"); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol pragma solidity ^0.5.0; /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) private _balances; __unstable__TokenVault private _vault; constructor() public { _vault = new __unstable__TokenVault(); } /** * @dev Withdraw tokens only after crowdsale ends. * @param beneficiary Whose tokens will be withdrawn. */ function withdrawTokens(address beneficiary) public { require(hasClosed(), "PostDeliveryCrowdsale: not closed"); uint256 amount = _balances[beneficiary]; require(amount > 0, "PostDeliveryCrowdsale: beneficiary is not due any tokens"); _balances[beneficiary] = 0; _vault.transfer(token(), beneficiary, amount); } /** * @return the balance of an account. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev Overrides parent by storing due balances, and delivering tokens to the vault instead of the end user. This * ensures that the tokens will be available by the time they are withdrawn (which may not be the case if * `_deliverTokens` was called later). * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _balances[beneficiary] = _balances[beneficiary].add(tokenAmount); _deliverTokens(address(_vault), tokenAmount); } } /** * @title __unstable__TokenVault * @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit. * This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context. */ // solhint-disable-next-line contract-name-camelcase contract __unstable__TokenVault is Secondary { function transfer(IERC20 token, address to, uint256 amount) public onlyPrimary { token.transfer(to, amount); } } // File: contracts/CapPurchases.sol pragma solidity ^0.5.0; contract CapPurchases is Crowdsale { uint256 public contributionCap; mapping(address => uint256) private _contributions; constructor(uint256 cap) public { contributionCap = cap; } // override this to add a personal cap function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); // solhint-disable-next-line max-line-length require(_contributions[beneficiary].add(weiAmount) <= contributionCap, "personal cap exceeded"); } // override this to track contributions function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { super._updatePurchasingState(beneficiary, weiAmount); _contributions[beneficiary] = _contributions[beneficiary].add(weiAmount); } } // File: contracts/presale.sol pragma solidity ^0.5.0; contract Presale is Crowdsale, TimedCrowdsale, PostDeliveryCrowdsale, Ownable, PausableCrowdsale, CapPurchases { constructor( uint256 rate, // rate, in TKNbits address payable wallet, // wallet to send Ether IERC20 token, // the token uint256 openingTime, // opening time in unix epoch seconds uint256 closingTime // closing time in unix epoch seconds ) public PostDeliveryCrowdsale() TimedCrowdsale(openingTime, closingTime) CapPurchases(100 * 1e18) Crowdsale(rate, wallet, token) { // nice! this Crowdsale will keep all of the tokens until the end of the crowdsale // and then users can `withdrawTokens()` to get the tokens they're owed } function extend(uint256 _closing) public onlyOwner() { _extendTime(_closing); } function updateTimers(uint256 _opening, uint256 _closing) public onlyOwner() { require(_closing > _opening, "closeing time must be greater than closing time"); _openingTime = _opening; _closingTime = _closing; } function openPresale() public onlyOwner() { _openingTime = block.timestamp; } function closePresale() public onlyOwner() { _closingTime = block.timestamp; } function freeTrappedEther(uint256 _withdraw) public onlyOwner() { msg.sender.transfer(_withdraw); } function reclaimUnsoldTokens(uint256 amount) public onlyOwner() { // sold coins are held int the token vault. and cannot be withdrawn token().transfer(msg.sender, amount); } /*********************/ /*** for promotion ***/ /*********************/ mapping(address => uint256) promotion_map; address[] promoter_list; function getPromoterList() external view returns (address[] memory) { address[] memory r = new address[](promoter_list.length); for (uint256 i = 0; i < promoter_list.length; i++) { r[i] = promoter_list[i]; } return r; } function getPromoterCounter(address promoter_address) public view returns(uint256) { return promotion_map[promoter_address]; } function buTokenByRecommendation(address promoter_address) payable public { if (promotion_map[promoter_address] == 0) { // new promoter // add to promoter list promoter_list.push(promoter_address); } // calculate token amount to be created uint256 tokens = _getTokenAmount(msg.value); promotion_map[promoter_address] += tokens; buyTokens(msg.sender); } }
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. @param beneficiary Address receiving the tokens @param tokenAmount Number of tokens to be purchased/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); }
10,977,051
[ 1, 23839, 1347, 279, 23701, 711, 2118, 10266, 471, 353, 5695, 358, 506, 7120, 18, 9637, 82, 1404, 23848, 3626, 19, 4661, 2430, 18, 225, 27641, 74, 14463, 814, 5267, 15847, 326, 2430, 225, 1147, 6275, 3588, 434, 2430, 358, 506, 5405, 343, 8905, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 202, 915, 389, 2567, 23164, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 1147, 6275, 13, 2713, 288, 203, 202, 202, 67, 26672, 5157, 12, 70, 4009, 74, 14463, 814, 16, 1147, 6275, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /// @title KtonVoter /// @dev Voting and support specific proposal validator by deposit KTON /// Vote will be cancel after KTON get withdrawd /// 1 KTON means one vote contract KtonVoter { address public KTON; struct VoterItem { // mapping (address => mapping (address => uint256)) public votes; mapping (address => uint256) votes; // mapping (address => uint256) public depositBalances; uint256 balance; // TODO: address[] candidates; } struct CandidateItem { uint256 voteCount; // contract address uint256 sortedIndex; // index of the item in the list of sortedCandidate bool isRegistered; // used to tell if the mapping element is defined // TODO: address[] voters; } mapping (address => VoterItem) public voterItems; mapping (address => CandidateItem) public cadidateItems; // descending address[] public sortedCandidates; function vote(address _candidate, uint _amount) public { require(cadidateItems[_candidate].isRegistered); require(ERC20(KTON).transferFrom(msg.sender, address(this), _amount)); voterItems[msg.sender].votes[_candidate] += _amount; voterItems[msg.sender].balance += _amount; cadidateItems[_candidate].voteCount += _amount; // TODO: update sortedIndex quickSort(0, cadidateItems[_candidate].sortedIndex); } function withdrawFrom(address _candidate, uint _amount) public { require(voterItems[msg.sender].votes[_candidate] >= _amount); voterItems[msg.sender].votes[_candidate] -= _amount; voterItems[msg.sender].balance -= _amount; cadidateItems[_candidate].voteCount -= _amount; require(ERC20(KTON).transfer(msg.sender, _amount)); // TODO: update sortedIndex quickSort(cadidateItems[_candidate].sortedIndex, sortedCandidates.length - 1); } function getCandidate(uint _num) public view returns (address candidate){ require(_num < sortedCandidates.length); candidate = sortedCandidates[_num]; } function registerCandidate() public { // require(ERC20(KTON).transferFrom(msg.sender, address(this), 1000000000000000000000)); require(!cadidateItems[msg.sender].isRegistered); cadidateItems[msg.sender].isRegistered = true; sortedCandidates.push(msg.sender); cadidateItems[msg.sender].sortedIndex = sortedCandidates.length - 1; } // http://www.etherdevops.com/content/sorting-array-integer-ethereum function quickSort(uint left, uint right) internal { uint i = left; uint j = right; uint pivot = cadidateItems[sortedCandidates[left + (right - left) / 2]].voteCount; while (i <= j) { while (cadidateItems[sortedCandidates[i]].voteCount < pivot) i++; while (pivot < cadidateItems[sortedCandidates[j]].voteCount) j--; if (i <= j) { (sortedCandidates[i], sortedCandidates[j]) = (sortedCandidates[j], sortedCandidates[i]); cadidateItems[sortedCandidates[i]].sortedIndex = i; cadidateItems[sortedCandidates[j]].sortedIndex = j; i++; j--; } } if (left < j) quickSort(left, j); if (i < right) quickSort(i, right); } }
TODO: update sortedIndex
function vote(address _candidate, uint _amount) public { require(cadidateItems[_candidate].isRegistered); require(ERC20(KTON).transferFrom(msg.sender, address(this), _amount)); voterItems[msg.sender].votes[_candidate] += _amount; voterItems[msg.sender].balance += _amount; cadidateItems[_candidate].voteCount += _amount; quickSort(0, cadidateItems[_candidate].sortedIndex); }
912,350
[ 1, 6241, 30, 1089, 3115, 1016, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12501, 12, 2867, 389, 19188, 16, 2254, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 12, 71, 361, 350, 340, 3126, 63, 67, 19188, 8009, 291, 10868, 1769, 203, 3639, 2583, 12, 654, 39, 3462, 12, 47, 56, 673, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 10019, 203, 203, 3639, 331, 20005, 3126, 63, 3576, 18, 15330, 8009, 27800, 63, 67, 19188, 65, 1011, 389, 8949, 31, 203, 3639, 331, 20005, 3126, 63, 3576, 18, 15330, 8009, 12296, 1011, 389, 8949, 31, 203, 203, 3639, 28451, 350, 340, 3126, 63, 67, 19188, 8009, 25911, 1380, 1011, 389, 8949, 31, 203, 203, 3639, 9549, 4416, 12, 20, 16, 28451, 350, 340, 3126, 63, 67, 19188, 8009, 10350, 1016, 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 ]
./full_match/11155111/0x5461D48556B94e7fdD8ED5A8f865Ba4F1A3b5454/sources/contracts/upgrades/GraphProxy.sol
* @notice Admin function for new implementation to accept its role as implementation./
function acceptUpgrade() external override ifAdminOrPendingImpl { _acceptUpgrade(); }
3,828,407
[ 1, 4446, 445, 364, 394, 4471, 358, 2791, 2097, 2478, 487, 4471, 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, 2791, 10784, 1435, 3903, 3849, 309, 4446, 1162, 8579, 2828, 288, 203, 3639, 389, 9436, 10784, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IGovernance.sol"; import "./lib/AccessControlEnumerable.sol"; import "./lib/BytesLib.sol"; /** * @title DistributorGovernance * @dev Add or remove block producers from the network and set rewards collectors */ contract DistributorGovernance is AccessControlEnumerable, IGovernance { using BytesLib for bytes; /// @notice Admin governance role bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE"); /// @notice Admin delegator role bytes32 public constant DELEGATOR_ROLE = keccak256("DELEGATOR_ROLE"); /// @notice Mapping of block producer to reward collector mapping (address => address) public override rewardCollector; /// @notice Whitelisted block producers mapping (address => bool) public override blockProducer; /// @dev Packed struct containing rewards distribution details bytes private _rewardSchedule; /// @notice Length of single rewards schedule entry uint256 public constant REWARD_SCHEDULE_ENTRY_LENGTH = 32; /// @notice Only Governance modifier modifier onlyGov() { require(hasRole(GOV_ROLE, msg.sender), "must be gov"); _; } /// @notice Only addresses with delegator role modifier onlyDelegator() { require(hasRole(DELEGATOR_ROLE, msg.sender), "must be delegator"); _; } /// @notice Only addresses with delegator role or block producer modifier onlyDelegatorOrProducer(address producer) { require(hasRole(DELEGATOR_ROLE, msg.sender) || msg.sender == producer, "must be producer or delegator"); _; } /** * @notice Construct a new DistributorGovernance contract * @param _admin Governance admin * @param _blockProducers Initial whitelist of block producers * @param _collectors Initial reward collectors for block producers */ constructor( address _admin, address[] memory _blockProducers, address[] memory _collectors ) { require(_blockProducers.length == _collectors.length, "length mismatch"); _setupRole(GOV_ROLE, _admin); _setupRole(DELEGATOR_ROLE, _admin); _setupRole(DEFAULT_ADMIN_ROLE, _admin); for(uint i; i< _blockProducers.length; i++) { blockProducer[_blockProducers[i]] = true; emit BlockProducerAdded(_blockProducers[i]); rewardCollector[_blockProducers[i]] = _collectors[i]; emit BlockProducerRewardCollectorChanged(_blockProducers[i], _collectors[i]); } } /** * @notice Add block producer to the network * @dev Only governance can call * @param producer Block producer address */ function add(address producer) external onlyGov { require(blockProducer[producer] == false, "already block producer"); blockProducer[producer] = true; emit BlockProducerAdded(producer); } /** * @notice Add batch of block producers to network * @dev Only governance can call * @param producers List of block producers */ function addBatch(address[] memory producers) external onlyGov { for(uint i; i< producers.length; i++) { require(blockProducer[producers[i]] == false, "already block producer"); blockProducer[producers[i]] = true; emit BlockProducerAdded(producers[i]); } } /** * @notice Remove block producer from network * @dev Only governance can call * @param producer Block producer address */ function remove(address producer) external onlyGov { require(blockProducer[producer] == true, "not block producer"); blockProducer[producer] = false; emit BlockProducerRemoved(producer); } /** * @notice Remove batch of block producers from network * @dev Only governance can call * @param producers List of block producers */ function removeBatch(address[] memory producers) external onlyGov { for(uint i; i< producers.length; i++) { require(blockProducer[producers[i]] == true, "not block producer"); blockProducer[producers[i]] = false; emit BlockProducerRemoved(producers[i]); } } /** * @notice Delegate a collector address that can claim rewards on behalf of a block producer * @dev Only delegator admin or block producer can call * @param producer Block producer address * @param collector Collector address */ function delegate(address producer, address collector) external onlyDelegatorOrProducer(producer) { rewardCollector[producer] = collector; emit BlockProducerRewardCollectorChanged(producer, collector); } /** * @notice Delegate collector addresses that can claim rewards on behalf of block producers in batch * @dev Only delegator admin can call * @param producers Block producer addresses * @param collectors Collector addresses */ function delegateBatch(address[] memory producers, address[] memory collectors) external onlyDelegator { require(producers.length == collectors.length, "length mismatch"); for(uint i; i< producers.length; i++) { rewardCollector[producers[i]] = collectors[i]; emit BlockProducerRewardCollectorChanged(producers[i], collectors[i]); } } /** * @notice Set reward schedule * @dev Only governance can call * @param set Packed bytes representing reward schedule */ function setRewardSchedule(bytes memory set) onlyGov public { _rewardSchedule = set; emit RewardScheduleChanged(); } /** * @notice Get reward schedule entry * @param index Index location * @return Rewards schedule entry */ function rewardScheduleEntry(uint256 index) public override view returns (RewardScheduleEntry memory) { RewardScheduleEntry memory entry; uint256 start = index * REWARD_SCHEDULE_ENTRY_LENGTH; entry.startTime = _rewardSchedule.toUint64(start); entry.epochDuration = _rewardSchedule.toUint64(start + 8); entry.rewardsPerEpoch = _rewardSchedule.toUint128(start + 16); return entry; } /** * @notice Get all reward schedule entries * @return Number of rewards schedule entries */ function rewardScheduleEntries() public override view returns (uint256) { return _rewardSchedule.length / REWARD_SCHEDULE_ENTRY_LENGTH; } }
* @notice Remove batch of block producers from network @dev Only governance can call @param producers List of block producers/
function removeBatch(address[] memory producers) external onlyGov { for(uint i; i< producers.length; i++) { require(blockProducer[producers[i]] == true, "not block producer"); blockProducer[producers[i]] = false; emit BlockProducerRemoved(producers[i]); } }
15,842,689
[ 1, 3288, 2581, 434, 1203, 4810, 13062, 628, 2483, 225, 5098, 314, 1643, 82, 1359, 848, 745, 225, 4810, 13062, 987, 434, 1203, 4810, 13062, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 4497, 12, 2867, 8526, 3778, 4810, 13062, 13, 3903, 1338, 43, 1527, 288, 203, 3639, 364, 12, 11890, 277, 31, 277, 32, 4810, 13062, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 2629, 12140, 63, 11776, 13062, 63, 77, 13563, 422, 638, 16, 315, 902, 1203, 12608, 8863, 203, 5411, 1203, 12140, 63, 11776, 13062, 63, 77, 13563, 273, 629, 31, 203, 5411, 3626, 3914, 12140, 10026, 12, 11776, 13062, 63, 77, 19226, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; import {IDepositZap} from "../../interfaces/curve/IDepositZap.sol"; import {IERC20Detailed} from "../../interfaces/IERC20Detailed.sol"; import {ICurveDeposit_4token} from "../../interfaces/curve/ICurveDeposit_4token.sol"; import {ConvexFactoryMetaPoolStrategy} from "./ConvexFactoryMetaPoolStrategy.sol"; import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; contract ConvexStrategyMetaBTC is ConvexFactoryMetaPoolStrategy { using SafeERC20 for IERC20Detailed; /// @notice curve N_COINS for the pool uint256 public constant CURVE_UNDERLYINGS_SIZE = 4; /// @notice curve sBTC deposit zap address public constant META_BTC_DEPOSIT_ZAP = address(0x7AbDBAf29929e7F8621B757D2a7c04d78d633834); /// @return size of the curve deposit array function _curveUnderlyingsSize() internal pure override returns (uint256) { return CURVE_UNDERLYINGS_SIZE; } /// @notice Deposits in Curve for metapools based on sbtc function _depositInCurve(uint256 _minLpTokens) internal override { IERC20Detailed _deposit = IERC20Detailed(curveDeposit); uint256 _balance = _deposit.balanceOf(address(this)); address _pool = curveLpToken; _deposit.safeApprove(META_BTC_DEPOSIT_ZAP, 0); _deposit.safeApprove(META_BTC_DEPOSIT_ZAP, _balance); // we can accept 0 as minimum, this will be called only by trusted roles // we also use the zap to deploy funds into a meta pool uint256[4] memory _depositArray; _depositArray[depositPosition] = _balance; IDepositZap(META_BTC_DEPOSIT_ZAP).add_liquidity( _pool, _depositArray, _minLpTokens ); } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IDepositZap { /// @notice Wraps underlying coins and deposit them into _pool. /// Returns the amount of LP tokens that were minted in the deposit. function add_liquidity( address _pool, uint256[4] memory _deposit_amounts, uint256 _min_mint_amount ) external returns (uint256); function add_liquidity( uint256[4] memory _deposit_amounts, uint256 _min_mint_amount ) external returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IERC20Detailed is IERC20Upgradeable { function name() external view returns(string memory); function symbol() external view returns(string memory); function decimals() external view returns(uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface ICurveDeposit_4token { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function calc_token_amount(uint256[4] calldata amounts, bool deposit) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; import {ConvexBaseStrategy} from "./ConvexBaseStrategy.sol"; import {IMetaPoolRegistry} from "../../interfaces/curve/IMetaPoolRegistry.sol"; abstract contract ConvexFactoryMetaPoolStrategy is ConvexBaseStrategy { /// @notice curve metapool factory address public constant METAPOOL_FACTORY = address(0xB9fC157394Af804a3578134A6585C0dc9cc990d4); /// @dev This method queries the Metapool Factory to get the underlying coins of a /// plain pool created with the factory (no wrapped assets). function _curveUnderlyingCoins(address _curveLpToken, uint256 _position) internal view override returns (address) { address[4] memory _coins = IMetaPoolRegistry(METAPOOL_FACTORY).get_underlying_coins(_curveLpToken); return _coins[_position]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "../../interfaces/IIdleCDOStrategy.sol"; import "../../interfaces/IERC20Detailed.sol"; import "../../interfaces/convex/IBooster.sol"; import "../../interfaces/convex/IBaseRewardPool.sol"; import "../../interfaces/curve/IMainRegistry.sol"; /// @author @dantop114 /// @title ConvexStrategy /// @notice IIdleCDOStrategy to deploy funds in Convex Finance /// @dev This contract should not have any funds at the end of each tx. /// The contract is upgradable, to add storage slots, add them after the last `###### End of storage VXX` abstract contract ConvexBaseStrategy is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable, ERC20Upgradeable, IIdleCDOStrategy { using SafeERC20Upgradeable for IERC20Detailed; /// ###### Storage V1 /// @notice one curve lp token /// @dev we use this as base unit of the strategy token too uint256 public ONE_CURVE_LP_TOKEN; /// @notice convex rewards pool id for the underlying curve lp token uint256 public poolID; /// @notice curve lp token to deposit in convex address public curveLpToken; /// @notice deposit token address to deposit into curve pool address public curveDeposit; /// @notice depositor contract used to deposit underlyings address public depositor; /// @notice deposit token array position uint256 public depositPosition; /// @notice convex crv rewards pool address address public rewardPool; /// @notice decimals of the underlying asset uint256 public curveLpDecimals; /// @notice Curve main registry address public constant MAIN_REGISTRY = address(0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5); /// @notice convex booster address address public constant BOOSTER = address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); /// @notice weth token address address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /// @notice curve ETH mock address address public constant ETH = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /// @notice whitelisted CDO for this strategy address public whitelistedCDO; /// @notice convex rewards for this specific lp token (cvx should be included in this list) address[] public convexRewards; /// @notice WETH to deposit token path address[] public weth2DepositPath; /// @notice univ2 router for weth to deposit swap address public weth2DepositRouter; /// @notice reward liquidation to WETH path mapping(address => address[]) public reward2WethPath; /// @notice univ2-like router for each reward mapping(address => address) public rewardRouter; /// @notice total LP tokens staked uint256 public totalLpTokensStaked; /// @notice total LP tokens locked uint256 public totalLpTokensLocked; /// @notice harvested LP tokens release delay uint256 public releaseBlocksPeriod; /// @notice latest harvest uint256 public latestHarvestBlock; /// ###### End of storage V1 /// ###### Storage V2 /// @notice blocks per year uint256 public BLOCKS_PER_YEAR; /// @notice latest harvest price gain in LP tokens uint256 public latestPriceIncrease; /// @notice latest estimated harvest interval uint256 public latestHarvestInterval; // ################### // Modifiers // ################### modifier onlyWhitelistedCDO() { require(msg.sender == whitelistedCDO, "Not whitelisted CDO"); _; } // Used to prevent initialization of the implementation contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { curveLpToken = address(1); } // ################### // Initializer // ################### // Struct used to set Curve deposits struct CurveArgs { address deposit; address depositor; uint256 depositPosition; } // Struct used to initialize rewards swaps struct Reward { address reward; address router; address[] path; } // Struct used to initialize WETH -> deposit swaps struct Weth2Deposit { address router; address[] path; } /// @notice can only be called once /// @dev Initialize the upgradable contract. If `_deposit` equals WETH address, _weth2Deposit is ignored as param. /// @param _poolID convex pool id /// @param _owner owner address /// @param _curveArgs curve addresses and deposit details /// @param _rewards initial rewards (with paths and routers) /// @param _weth2Deposit initial WETH -> deposit paths and routers function initialize( uint256 _poolID, address _owner, uint256 _releasePeriod, CurveArgs memory _curveArgs, Reward[] memory _rewards, Weth2Deposit memory _weth2Deposit ) public initializer { // Sanity checks require(curveLpToken == address(0), "Initialized"); require(_curveArgs.depositPosition < _curveUnderlyingsSize(), "Deposit token position invalid"); // Initialize contracts OwnableUpgradeable.__Ownable_init(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); // Check Curve LP Token and Convex PoolID (address _crvLp, , , address _rewardPool, , bool shutdown) = IBooster(BOOSTER).poolInfo(_poolID); curveLpToken = _crvLp; // Pool and deposit asset checks address _deposit = _curveArgs.deposit == WETH ? ETH : _curveArgs.deposit; require(!shutdown, "Convex Pool is not active"); require(_deposit == _curveUnderlyingCoins(_crvLp, _curveArgs.depositPosition), "Deposit token invalid"); ERC20Upgradeable.__ERC20_init( string(abi.encodePacked("Idle ", IERC20Detailed(_crvLp).name(), " Convex Strategy")), string(abi.encodePacked("idleCvx", IERC20Detailed(_crvLp).symbol())) ); // Set basic parameters poolID = _poolID; rewardPool = _rewardPool; curveLpDecimals = IERC20Detailed(_crvLp).decimals(); ONE_CURVE_LP_TOKEN = 10**(curveLpDecimals); curveDeposit = _curveArgs.deposit; depositor = _curveArgs.depositor; depositPosition = _curveArgs.depositPosition; releaseBlocksPeriod = _releasePeriod; setBlocksPerYear(2465437); // given that blocks are mined at a 13.15s/block rate // set approval for curveLpToken IERC20Detailed(_crvLp).approve(BOOSTER, type(uint256).max); // set initial rewards for (uint256 i = 0; i < _rewards.length; i++) { addReward(_rewards[i].reward, _rewards[i].router, _rewards[i].path); } if (_curveArgs.deposit != WETH) setWeth2Deposit(_weth2Deposit.router, _weth2Deposit.path); // transfer ownership transferOwnership(_owner); } // ################### // Interface implementation // ################### function strategyToken() external view override returns (address) { return address(this); } function oneToken() external view override returns (uint256) { return ONE_CURVE_LP_TOKEN; } // @notice Underlying token function token() external view override returns (address) { return curveLpToken; } // @notice Underlying token decimals function tokenDecimals() external view override returns (uint256) { return curveLpDecimals; } function decimals() public view override returns (uint8) { return uint8(curveLpDecimals); // should be safe } // ################### // Public methods // ################### /// @dev msg.sender should approve this contract first to spend `_amount` of `token` /// @param _amount amount of `token` to deposit /// @return minted amount of strategy tokens minted function deposit(uint256 _amount) external override onlyWhitelistedCDO returns (uint256 minted) { if (_amount > 0) { /// get `tokens` from msg.sender IERC20Detailed(curveLpToken).safeTransferFrom(msg.sender, address(this), _amount); minted = _depositAndMint(msg.sender, _amount, price()); } } /// @dev msg.sender doesn't need to approve the spending of strategy token /// @param _amount amount of strategyTokens to redeem /// @return redeemed amount of underlyings redeemed function redeem(uint256 _amount) external onlyWhitelistedCDO override returns (uint256 redeemed) { if(_amount > 0) { redeemed = _redeem(msg.sender, _amount, price()); } } /// @dev msg.sender should approve this contract first /// to spend `_amount * ONE_IDLE_TOKEN / price()` of `strategyToken` /// @param _amount amount of underlying tokens to redeem /// @return redeemed amount of underlyings redeemed function redeemUnderlying(uint256 _amount) external override onlyWhitelistedCDO returns (uint256 redeemed) { if (_amount > 0) { uint256 _cachedPrice = price(); uint256 _shares = (_amount * ONE_CURVE_LP_TOKEN) / _cachedPrice; redeemed = _redeem(msg.sender, _shares, _cachedPrice); } } /// @notice Anyone can call this because this contract holds no strategy tokens and so no 'old' rewards /// @dev msg.sender should approve this contract first to spend `_amount` of `strategyToken`. /// redeem rewards and transfer them to msg.sender /// @param _extraData extra data to be used when selling rewards for min amounts /// @return _balances array of minAmounts to use for swapping rewards to WETH, then weth to depositToken, then depositToken to curveLpToken function redeemRewards(bytes calldata _extraData) external override onlyWhitelistedCDO returns (uint256[] memory _balances) { address[] memory _convexRewards = convexRewards; // +2 for converting rewards to depositToken and then Curve LP Token _balances = new uint256[](_convexRewards.length + 2); // decode params from _extraData to get the min amount for each convexRewards uint256[] memory _minAmountsWETH = new uint256[](_convexRewards.length); bool[] memory _skipSell = new bool[](_convexRewards.length); uint256 _minDepositToken; uint256 _minLpToken; (_minAmountsWETH, _skipSell, _minDepositToken, _minLpToken) = abi.decode(_extraData, (uint256[], bool[], uint256, uint256)); IBaseRewardPool(rewardPool).getReward(); address _reward; IERC20Detailed _rewardToken; uint256 _rewardBalance; IUniswapV2Router02 _router; for (uint256 i = 0; i < _convexRewards.length; i++) { if (_skipSell[i]) continue; _reward = _convexRewards[i]; // get reward balance and safety check _rewardToken = IERC20Detailed(_reward); _rewardBalance = _rewardToken.balanceOf(address(this)); if (_rewardBalance == 0) continue; _router = IUniswapV2Router02( rewardRouter[_reward] ); // approve to v2 router _rewardToken.safeApprove(address(_router), 0); _rewardToken.safeApprove(address(_router), _rewardBalance); address[] memory _reward2WethPath = reward2WethPath[_reward]; uint256[] memory _res = new uint256[](_reward2WethPath.length); _res = _router.swapExactTokensForTokens( _rewardBalance, _minAmountsWETH[i], _reward2WethPath, address(this), block.timestamp ); // save in returned value the amount of weth receive to use off-chain _balances[i] = _res[_res.length - 1]; } if (curveDeposit != WETH) { IERC20Detailed _weth = IERC20Detailed(WETH); IUniswapV2Router02 _wethRouter = IUniswapV2Router02( weth2DepositRouter ); uint256 _wethBalance = _weth.balanceOf(address(this)); _weth.safeApprove(address(_wethRouter), 0); _weth.safeApprove(address(_wethRouter), _wethBalance); address[] memory _weth2DepositPath = weth2DepositPath; uint256[] memory _res = new uint256[](_weth2DepositPath.length); _res = _wethRouter.swapExactTokensForTokens( _wethBalance, _minDepositToken, _weth2DepositPath, address(this), block.timestamp ); // save in _balances the amount of depositToken to use off-chain _balances[_convexRewards.length] = _res[_res.length - 1]; } IERC20Detailed _curveLpToken = IERC20Detailed(curveLpToken); uint256 _curveLpBalanceBefore = _curveLpToken.balanceOf(address(this)); _depositInCurve(_minLpToken); uint256 _curveLpBalanceAfter = _curveLpToken.balanceOf(address(this)); uint256 _gainedLpTokens = (_curveLpBalanceAfter - _curveLpBalanceBefore); // save in _balances the amount of curveLpTokens received to use off-chain _balances[_convexRewards.length + 1] = _gainedLpTokens; if (_curveLpBalanceAfter > 0) { // deposit in curve and stake on convex _stakeConvex(_curveLpBalanceAfter); // update locked lp tokens and apr computation variables latestHarvestInterval = (block.number - latestHarvestBlock); latestHarvestBlock = block.number; totalLpTokensLocked = _gainedLpTokens; // inline price increase calculation latestPriceIncrease = (_gainedLpTokens * ONE_CURVE_LP_TOKEN) / totalSupply(); } } // ################### // Views // ################### /// @return _price net price in underlyings of 1 strategyToken function price() public view override returns (uint256 _price) { uint256 _totalSupply = totalSupply(); if (_totalSupply == 0) { _price = ONE_CURVE_LP_TOKEN; } else { _price = ((totalLpTokensStaked - _lockedLpTokens()) * ONE_CURVE_LP_TOKEN) / _totalSupply; } } /// @return returns an APR estimation. /// @dev values returned by this method should be taken as an imprecise estimation. /// For client integration something more complex should be done to have a more precise /// estimate (eg. computing APR using historical APR data). /// Also it does not take into account compounding (APY). function getApr() external view override returns (uint256) { // apr = rate * blocks in a year / harvest interval return latestPriceIncrease * (BLOCKS_PER_YEAR / latestHarvestInterval) * 100; } /// @return rewardTokens tokens array of reward token addresses function getRewardTokens() external view override returns (address[] memory rewardTokens) {} // ################### // Protected // ################### /// @notice Allow the CDO to pull stkAAVE rewards. Anyone can call this /// @return 0, this function is a noop in this strategy function pullStkAAVE() external pure override returns (uint256) { return 0; } /// @notice This contract should not have funds at the end of each tx (except for stkAAVE), this method is just for leftovers /// @dev Emergency method /// @param _token address of the token to transfer /// @param value amount of `_token` to transfer /// @param _to receiver address function transferToken( address _token, uint256 value, address _to ) external onlyOwner nonReentrant { IERC20Detailed(_token).safeTransfer(_to, value); } /// @notice This method can be used to change the value of BLOCKS_PER_YEAR /// @param blocksPerYear the new blocks per year value function setBlocksPerYear(uint256 blocksPerYear) public onlyOwner { require(blocksPerYear != 0, "Blocks per year cannot be zero"); BLOCKS_PER_YEAR = blocksPerYear; } function setRouterForReward(address _reward, address _newRouter) external onlyOwner { require(_newRouter != address(0), "Router is address zero"); rewardRouter[_reward] = _newRouter; } function setPathForReward(address _reward, address[] memory _newPath) external onlyOwner { _validPath(_newPath, WETH); reward2WethPath[_reward] = _newPath; } function setWeth2Deposit(address _router, address[] memory _path) public onlyOwner { address _curveDeposit = curveDeposit; require(_curveDeposit != WETH, "Deposit asset is WETH"); _validPath(_path, _curveDeposit); weth2DepositRouter = _router; weth2DepositPath = _path; } function addReward( address _reward, address _router, address[] memory _path ) public onlyOwner { _validPath(_path, WETH); convexRewards.push(_reward); rewardRouter[_reward] = _router; reward2WethPath[_reward] = _path; } function removeReward(address _reward) external onlyOwner { address[] memory _newConvexRewards = new address[]( convexRewards.length - 1 ); uint256 currentI = 0; for (uint256 i = 0; i < convexRewards.length; i++) { if (convexRewards[i] == _reward) continue; _newConvexRewards[currentI] = convexRewards[i]; currentI += 1; } convexRewards = _newConvexRewards; delete rewardRouter[_reward]; delete reward2WethPath[_reward]; } /// @notice allow to update whitelisted address function setWhitelistedCDO(address _cdo) external onlyOwner { require(_cdo != address(0), "IS_0"); whitelistedCDO = _cdo; } function setReleaseBlocksPeriod(uint256 _period) external onlyOwner { releaseBlocksPeriod = _period; } // ################### // Internal // ################### /// @dev Virtual method to override in specific pool implementation. /// @return number of underlying coins depending on Curve pool function _curveUnderlyingsSize() internal pure virtual returns (uint256); /// @dev Virtual method to override in specific pool implementation. /// This method should implement the deposit in the curve pool. function _depositInCurve(uint256 _minLpTokens) internal virtual; /// @dev Virtual method to override if needed (eg. pool address is equal to lp token address) /// @return address of pool from LP token function _curvePool(address _curveLpToken) internal view virtual returns (address) { return IMainRegistry(MAIN_REGISTRY).get_pool_from_lp_token(_curveLpToken); } /// @dev Virtual method to override if needed (eg. pool is not in the main registry) /// @return address of the nth underlying coin for _curveLpToken function _curveUnderlyingCoins(address _curveLpToken, uint256 _position) internal view virtual returns (address) { address[8] memory _coins = IMainRegistry(MAIN_REGISTRY).get_underlying_coins(_curvePool(_curveLpToken)); return _coins[_position]; } /// @notice Internal helper function to deposit in convex and update total LP tokens staked /// @param _lpTokens number of LP tokens to stake function _stakeConvex(uint256 _lpTokens) internal { // update total staked lp tokens and deposit in convex totalLpTokensStaked += _lpTokens; IBooster(BOOSTER).depositAll(poolID, true); } /// @notice Internal function to deposit in the Convex Booster and mint shares /// @dev Used for deposit and during an harvest /// @param _lpTokens amount to mint /// @param _price we give the price as input to save on gas when calculating price function _depositAndMint( address _account, uint256 _lpTokens, uint256 _price ) internal returns (uint256 minted) { // deposit in convex _stakeConvex(_lpTokens); // mint strategy tokens to msg.sender minted = (_lpTokens * ONE_CURVE_LP_TOKEN) / _price; _mint(_account, minted); } /// @dev msg.sender does not need to approve this contract to spend `_amount` of `strategyToken` /// @param _shares amount of strategyTokens to redeem /// @param _price we give the price as input to save on gas when calculating price /// @return redeemed amount of underlyings redeemed function _redeem( address _account, uint256 _shares, uint256 _price ) internal returns (uint256 redeemed) { // update total staked lp tokens redeemed = (_shares * _price) / ONE_CURVE_LP_TOKEN; totalLpTokensStaked -= redeemed; IERC20Detailed _curveLpToken = IERC20Detailed(curveLpToken); // burn strategy tokens for the msg.sender _burn(_account, _shares); // exit reward pool (without claiming) and unwrap staking position IBaseRewardPool(rewardPool).withdraw(redeemed, false); IBooster(BOOSTER).withdraw(poolID, redeemed); // transfer underlying lp tokens to msg.sender _curveLpToken.safeTransfer(_account, redeemed); } function _lockedLpTokens() internal view returns (uint256 _locked) { uint256 _releaseBlocksPeriod = releaseBlocksPeriod; uint256 _blocksSinceLastHarvest = block.number - latestHarvestBlock; uint256 _totalLockedLpTokens = totalLpTokensLocked; if (_totalLockedLpTokens > 0 && _blocksSinceLastHarvest < _releaseBlocksPeriod) { // progressively release harvested rewards _locked = _totalLockedLpTokens * (_releaseBlocksPeriod - _blocksSinceLastHarvest) / _releaseBlocksPeriod; } } function _validPath(address[] memory _path, address _out) internal pure { require(_path.length >= 2, "Path length less than 2"); require(_path[_path.length - 1] == _out, "Last asset should be WETH"); } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IMetaPoolRegistry { function get_coins(address) external view returns (address[4] memory); function get_underlying_coins(address) external view returns(address[4] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; interface IIdleCDOStrategy { function strategyToken() external view returns(address); function token() external view returns(address); function tokenDecimals() external view returns(uint256); function oneToken() external view returns(uint256); function redeemRewards(bytes calldata _extraData) external returns(uint256[] memory); function pullStkAAVE() external returns(uint256); function price() external view returns(uint256); function getRewardTokens() external view returns(address[] memory); function deposit(uint256 _amount) external returns(uint256); // _amount in `strategyToken` function redeem(uint256 _amount) external returns(uint256); // _amount in `token` function redeemUnderlying(uint256 _amount) external returns(uint256); function getApr() external view returns(uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IBooster { function deposit(uint256 _pid, uint256 _amount, bool _stake) external; function depositAll(uint256 _pid, bool _stake) external; function withdraw(uint256 _pid, uint256 _amount) external; function withdrawAll(uint256 _pid) external; function poolInfo(uint256 _pid) external view returns (address lpToken, address, address, address, address, bool); function earmarkRewards(uint256 _pid) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IBaseRewardPool { function balanceOf(address account) external view returns(uint256 amount); function pid() external view returns (uint256 _pid); function stakingToken() external view returns (address _stakingToken); function extraRewardsLength() external view returns (uint256 _length); function rewardToken() external view returns(address _rewardToken); function extraRewards() external view returns(address[] memory _extraRewards); function getReward() external; function stake(uint256 _amount) external; function stakeAll() external; function withdraw(uint256 amount, bool claim) external; function withdrawAll(bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function withdrawAllAndUnwrap(bool claim) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IMainRegistry { function get_pool_from_lp_token(address lp_token) external view returns (address); function get_underlying_coins(address pool) external view returns (address[8] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version 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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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); } } } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
@return returns an APR estimation. @dev values returned by this method should be taken as an imprecise estimation. For client integration something more complex should be done to have a more precise estimate (eg. computing APR using historical APR data). Also it does not take into account compounding (APY). apr = rate * blocks in a year / harvest interval
function getApr() external view override returns (uint256) { return latestPriceIncrease * (BLOCKS_PER_YEAR / latestHarvestInterval) * 100; }
532,862
[ 1, 2463, 1135, 392, 432, 8025, 29284, 18, 225, 924, 2106, 635, 333, 707, 1410, 506, 9830, 487, 392, 709, 4036, 784, 29284, 18, 1377, 2457, 1004, 12040, 5943, 1898, 7233, 1410, 506, 2731, 358, 1240, 279, 1898, 31293, 1377, 11108, 261, 1332, 18, 20303, 432, 8025, 1450, 23922, 432, 8025, 501, 2934, 1377, 8080, 518, 1552, 486, 4862, 1368, 2236, 11360, 310, 261, 2203, 61, 2934, 513, 86, 273, 4993, 225, 4398, 316, 279, 3286, 342, 17895, 26923, 3673, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4506, 683, 1435, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 4891, 5147, 382, 11908, 380, 261, 11403, 55, 67, 3194, 67, 15137, 342, 4891, 44, 297, 26923, 4006, 13, 380, 2130, 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 ]
pragma solidity ^0.5.0; contract CogScience_project { int public max_score; int public min_score; uint public totalNum_transactions; // it's used as transaction's ID too. uint public totalNum_proposals; uint public lecture_tokens; // it keeps a fixed number of tokens. uint public current_lecture_number; address public owner; mapping (uint => Pair) public valid_student_num; mapping (uint => Proposal) public proposals; mapping (address => bool) public valid_student_addr; mapping (address => bool) public valid_admins; mapping (address => uint) public student_token_balance; mapping (address => uint) public totalNumOf_tokens_traded; // keeps track of total tokens sent/recived by each student. mapping (address => int) public reputations; // mapping (address reciver => int score) mapping (uint => Transaction) public transactions; // mapping (uint transaction id/counter => Transaction) mapping (uint => bytes2) public hash_lectureID; // lecture number => hash(lecture ID). mapping (address => uint) public attended; mapping (uint => uint) public total_participants;// (uint lecture_number => uint number_of_students_claimed_tokens) total_participants-- It stores total number of students participated in a session/lecture struct Pair{ bool validStudent_num; bool token_assigned; } struct Proposal{ uint numOf_tokens; address creator_address; string creator_emailAdress;// this is needed because the student that makes an offer may want to send token. // in this case, the student who is interested can email and send to it, its public key. Then, the student who // has made the offer can call send_token() and uses the other student's address as the recipient. string reason; uint proposal_ID; bool active; } struct Transaction{ address sender; address reciever; string reason; int TokenSender_feedback; // feedback provided by the sender to tokens. int TokenReciever_feedback; // feedback provided by the reciever of tokens. uint transaction_ID; uint numOf_tokens; // number of tokens sent in this transaction. string creation_time; } constructor(address admin) public{ owner = msg.sender; valid_admins[admin] = true; valid_admins[msg.sender] = true; // so the deployer can be admin too. max_score = 5; min_score = -5; lecture_tokens = 5; } modifier only_admin(){ require(valid_admins[msg.sender] == true); _; } modifier only_owner(){ require(msg.sender == owner); _; } function add_admin(address new_admin) external only_owner{ valid_admins[new_admin] = true; } function remove_admin(address admin) external only_owner{ valid_admins[admin] = false; } // Allows a valid admin to send some tokens to students. function distribute_token(address std_addr, uint numOf_tokens) external only_admin{ require(valid_student_addr[std_addr] == true); student_token_balance[std_addr] += numOf_tokens; } function register_std_num(uint std_num) external only_admin{ // this is done when a list of students enroled for the course is finalised. valid_student_num[std_num].validStudent_num = true; } function register_std_addr(address std_addr, uint std_num) external only_admin{ require(valid_student_num[std_num].validStudent_num == true); // check if the student has enroled the course require(valid_student_num[std_num].token_assigned == false); // ensures a student cannot registers itself with multiple public keys valid_student_num[std_num].token_assigned = true; valid_student_addr[std_addr] = true; student_token_balance[std_addr] = 10; // it allocates 10 tokens to the regitered student. } function register_lectureID(uint lecture_number, string calldata lec_ID) external only_admin{ hash_lectureID[lecture_number] = bytes2(keccak256(bytes(lec_ID)));// a hash value of the lecture is stored in the contract. } function set_currentlecture_number(uint num) external only_admin{ current_lecture_number = num; } // This function allows a student to claim a fixed number of tokens (lecture_tokens), if it could prove its attentance in a lecture (e.g. by uploading a QR code in the UI). If approved // (in the UI) then UI calls this function. function claim_token(string calldata input_) external{ require(valid_student_addr[msg.sender] == true);// checks if it's a valid student require(hash_lectureID[current_lecture_number] == bytes2(keccak256(bytes(input_))));//checks if the student has sent a valid id require(attended[msg.sender] != current_lecture_number);// ensures the student has not already claimed any tokens for this lecture yet. attended[msg.sender] = current_lecture_number; student_token_balance[msg.sender] += lecture_tokens; total_participants[current_lecture_number]++; } // in the UI, each student should be able to see a list of active offers he/she has made. This allows the student // to fetch specific offer ID used in send_token. // // This function allows a student to post an offer on the UI. It can offer to engage in an actitivy and specify how many tokens it is willing to send or recieve. function makeProposal(uint numOf_tokens_, string calldata reason_, string calldata email_address_) external{ require(valid_student_addr[msg.sender] == true, "Not a valid sender"); require(student_token_balance[msg.sender] >= numOf_tokens_,"Not enough token"); Proposal memory proposal_; proposal_.numOf_tokens = numOf_tokens_; proposal_.creator_address = msg.sender; proposal_.creator_emailAdress = email_address_; proposal_.reason = reason_; totalNum_proposals++; proposal_.proposal_ID = totalNum_proposals; proposal_.active = true; proposals[totalNum_proposals] = proposal_; } function send_token(uint amount, address recipient_address, string calldata _reason,string calldata time_, uint offer_ID_) external{ require(msg.sender!=recipient_address); // the sender should not be able to send token to itself and make a transaction. require(valid_student_addr[msg.sender] == true, "Not a valid sender"); // checks if the sender is a valid student require(valid_student_addr[recipient_address] == true, "Not a valid recipient"); // checks if the recipient is a valid student require(student_token_balance[msg.sender] >= amount,"Not enough token"); // check if the sender has enough token. require(proposals[offer_ID_].active == true, "Not an active offer");//check of the offer is active yet. require(amount > 0); //either the token recipient or the token sender should be in the creator of the offer_ID. require(msg.sender == proposals[offer_ID_].creator_address || recipient_address == proposals[offer_ID_].creator_address); proposals[offer_ID_].active = false;// recall only active offers should be desplayed on the UI. student_token_balance[msg.sender] -= amount; student_token_balance[recipient_address] += amount; totalNumOf_tokens_traded[msg.sender] += amount; totalNumOf_tokens_traded[recipient_address] += amount; Transaction memory trans; // stores each transaction's details in "transactions". totalNum_transactions += 1; trans.sender = msg.sender; trans.reciever = recipient_address; trans.reason = _reason; trans.numOf_tokens = amount; trans.creation_time = time_; trans.transaction_ID = totalNum_transactions; trans.TokenSender_feedback = -10; // we allocate -10 to show no feedback has been provided. Note that 0 is among valid scores and it's also a default value for uint types. trans.TokenReciever_feedback = -10; // see above transactions[totalNum_transactions] = trans; } function canLeave_feedback(address feedback_sender, uint transaction_id) internal returns (bool can, uint res){ // checks if the person who wants to leave the feedback is sender of tokens AND has not left any feedback for the transaction. if(transactions[transaction_id].sender == feedback_sender && transactions[transaction_id].TokenSender_feedback == -10){ res = 1; can = true; } // checks if the person who wants to leave the feedback is reciever of tokens AND has not left any feedback for the transaction. else if(transactions[transaction_id].reciever == feedback_sender && transactions[transaction_id].TokenReciever_feedback == -10){ res = 2; can = true; } } // the sender of the feedback needs to first check the list of the transactions and see which transaction it wants to leave feedback // then it needs to read the transaction ID. function leave_feedback(uint transaction_id, int score) external{ require (min_score <= score && score <= max_score); // check if the score is valid: min_score <= score <= max_score (bool can, uint res) = canLeave_feedback(msg.sender, transaction_id); // check if the the sender of the feedback is one of the parties involded in the transaction and has not already left any feedback yet. require(can); if (res == 1){ transactions[transaction_id].TokenSender_feedback = score; reputations[transactions[transaction_id].reciever] += score; } else if (res == 2){ transactions[transaction_id].TokenReciever_feedback = score; reputations[transactions[transaction_id].sender] += score; } } }
recall only active offers should be desplayed on the UI.
proposals[offer_ID_].active = false;
12,760,862
[ 1, 266, 1991, 1338, 2695, 28641, 1410, 506, 2832, 1601, 329, 603, 326, 6484, 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, 450, 22536, 63, 23322, 67, 734, 67, 8009, 3535, 273, 629, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0x734E02893A75B1afD3984634888fdC8411ACd877/sources/contracts/3_Ballot.sol
@title Entry point for an AAVE v1 -> v2 position migration
contract AaveMigrationTaker is ProxyPermission { uint16 public constant AAVE_REFERRAL_CODE = 64; address public constant AAVE_V1_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; address public constant AAVE_V1_SUBSCRIPTION_ADDR = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_V2_SUBSCRIPTION_ADDR = 0x6B25043BF08182d8e86056C6548847aF607cd7CD; address public constant AAVE_V1_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; address public constant AAVE_V2_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; struct FlMigrationData { address market; address[] collTokens; uint256[] modes; bool[] isColl; } function migrateV1Position( address _market, address[] memory _collTokens, bool[] memory _isColl, address[] memory _borrowTokens, uint256[] memory _flModes, address _aaveMigrationReceiverAddr ) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); (address[] memory assets, uint256[] memory amounts, uint256[] memory modes) = getUserBorrows(userProxy, _borrowTokens); FlMigrationData memory flData = FlMigrationData({ market: _market, collTokens: _collTokens, modes: modes, isColl: _isColl }); bytes memory data = abi.encode(flData); ILendingPoolV2(lendingPool).flashLoan( _aaveMigrationReceiverAddr, assets, amounts, _flModes, address(this), data, AAVE_REFERRAL_CODE ); removePermission(_aaveMigrationReceiverAddr); logger.Log( address(this), msg.sender, "AaveMigration", abi.encode(_collTokens, _borrowTokens) ); } function migrateV1Position( address _market, address[] memory _collTokens, bool[] memory _isColl, address[] memory _borrowTokens, uint256[] memory _flModes, address _aaveMigrationReceiverAddr ) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); (address[] memory assets, uint256[] memory amounts, uint256[] memory modes) = getUserBorrows(userProxy, _borrowTokens); FlMigrationData memory flData = FlMigrationData({ market: _market, collTokens: _collTokens, modes: modes, isColl: _isColl }); bytes memory data = abi.encode(flData); ILendingPoolV2(lendingPool).flashLoan( _aaveMigrationReceiverAddr, assets, amounts, _flModes, address(this), data, AAVE_REFERRAL_CODE ); removePermission(_aaveMigrationReceiverAddr); logger.Log( address(this), msg.sender, "AaveMigration", abi.encode(_collTokens, _borrowTokens) ); } givePermission(_aaveMigrationReceiverAddr); function getUserBorrows(address _user, address[] memory _borrowTokens) public view returns ( address[] memory borrowAddr, uint256[] memory borrowAmounts, uint256[] memory borrowRateModes ) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_V1_LENDING_POOL_ADDRESSES).getLendingPool(); borrowAddr = new address[](_borrowTokens.length); borrowAmounts = new uint256[](_borrowTokens.length); borrowRateModes = new uint256[](_borrowTokens.length); for (uint256 i = 0; i < _borrowTokens.length; i++) { address reserve = _borrowTokens[i]; (, uint256 borrowBalance, , uint256 borrowRateMode, , , uint256 originationFee, , , ) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); if (reserve == ETH_ADDR) { reserve = WETH_ADDRESS; } borrowAddr[i] = reserve; borrowAmounts[i] = borrowBalance + originationFee; borrowRateModes[i] = borrowRateMode; } } function getUserBorrows(address _user, address[] memory _borrowTokens) public view returns ( address[] memory borrowAddr, uint256[] memory borrowAmounts, uint256[] memory borrowRateModes ) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_V1_LENDING_POOL_ADDRESSES).getLendingPool(); borrowAddr = new address[](_borrowTokens.length); borrowAmounts = new uint256[](_borrowTokens.length); borrowRateModes = new uint256[](_borrowTokens.length); for (uint256 i = 0; i < _borrowTokens.length; i++) { address reserve = _borrowTokens[i]; (, uint256 borrowBalance, , uint256 borrowRateMode, , , uint256 originationFee, , , ) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); if (reserve == ETH_ADDR) { reserve = WETH_ADDRESS; } borrowAddr[i] = reserve; borrowAmounts[i] = borrowBalance + originationFee; borrowRateModes[i] = borrowRateMode; } } function getUserBorrows(address _user, address[] memory _borrowTokens) public view returns ( address[] memory borrowAddr, uint256[] memory borrowAmounts, uint256[] memory borrowRateModes ) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_V1_LENDING_POOL_ADDRESSES).getLendingPool(); borrowAddr = new address[](_borrowTokens.length); borrowAmounts = new uint256[](_borrowTokens.length); borrowRateModes = new uint256[](_borrowTokens.length); for (uint256 i = 0; i < _borrowTokens.length; i++) { address reserve = _borrowTokens[i]; (, uint256 borrowBalance, , uint256 borrowRateMode, , , uint256 originationFee, , , ) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); if (reserve == ETH_ADDR) { reserve = WETH_ADDRESS; } borrowAddr[i] = reserve; borrowAmounts[i] = borrowBalance + originationFee; borrowRateModes[i] = borrowRateMode; } } }
11,500,350
[ 1, 1622, 1634, 364, 392, 432, 26714, 331, 21, 317, 331, 22, 1754, 6333, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 432, 836, 10224, 56, 6388, 353, 7659, 5041, 288, 203, 565, 2254, 2313, 1071, 5381, 432, 26714, 67, 30269, 54, 1013, 67, 5572, 273, 5178, 31, 203, 203, 565, 1758, 1071, 5381, 432, 26714, 67, 58, 21, 67, 900, 2908, 1360, 67, 20339, 67, 8355, 7031, 1090, 55, 273, 203, 3639, 374, 92, 3247, 69, 9452, 74, 40, 6030, 39, 29, 6669, 37, 9498, 40, 74, 25, 40, 713, 40, 6260, 2733, 39, 5026, 71, 24, 74, 9349, 5608, 28, 71, 28, 31, 203, 565, 1758, 1071, 5381, 432, 26714, 67, 58, 21, 67, 8362, 11133, 67, 14142, 273, 374, 6554, 6840, 1403, 27, 37, 22, 16234, 70, 4449, 24, 42, 20, 70, 8204, 21, 41, 26, 5877, 41, 26, 38, 23, 73, 8204, 23, 758, 20, 5292, 4488, 31, 203, 565, 1758, 1071, 5381, 432, 26714, 67, 58, 22, 67, 8362, 11133, 67, 14142, 273, 374, 92, 26, 38, 2947, 3028, 23, 15259, 6840, 28246, 72, 28, 73, 28, 4848, 4313, 39, 26, 6564, 28, 5193, 27, 69, 42, 4848, 27, 4315, 27, 10160, 31, 203, 203, 565, 1758, 1071, 5381, 432, 26714, 67, 58, 21, 67, 17667, 30153, 67, 16085, 273, 374, 5841, 37, 4313, 20, 4331, 69, 23, 69, 28, 40, 20, 38, 31728, 71, 37, 29, 3361, 25, 37, 22, 38, 10689, 22343, 5698, 6675, 3462, 29, 2226, 31, 203, 565, 1758, 1071, 5381, 432, 26714, 67, 58, 22, 67, 17667, 30153, 67, 16085, 273, 374, 92, 23, 3672, 10689, 5540, 3103, 11035, 6030, 5718, 311, 39, 26, 5540, 2 ]
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./OnlyCore.sol"; import "./lib/dYdX/TokenProxy.sol"; import "./lib/dYdX/TokenInteract.sol"; contract Escrow is OnlyCore { using SafeMath for uint256; TokenProxy tokenProxy; // === EVENTS === // would be nice to log actual amounts, but not sure if worth the computation on-chain event EscrowBid(address[] tokens, address to, uint256[] amounts); event ReleaseBid(address[] tokens, address to, uint256[] amounts); constructor(address core) OnlyCore(core) public { } function setTokenProxy(address tokenProxyAddress) public onlyCore { tokenProxy = TokenProxy(tokenProxyAddress); } /** * Escrows quantities specified by bid. Only callable by the fund contract. * @param tokens Addresses of tokens * @param from Bidder address to transfer from * @param quantities Quantities for one creation unit * @param totalUnits Total number of creation units */ function escrowBid( address[] memory tokens, address from, int256[] memory quantities, uint256 totalUnits ) public onlyCore { uint256[] memory amounts = new uint256[](tokens.length); // For log for (uint256 i = 0; i < tokens.length; i++) { if (quantities[i] > 0) { uint256 amount = uint256(quantities[i]).mul(totalUnits); tokenProxy.transferTokens(tokens[i], from, address(this), amount); amounts[i] = amount; } } emit EscrowBid(tokens, from, amounts); } /** * Releases escrowed tokens. Only callable by fund. * @param tokens Addresses of tokens * @param to Bidder address to transfer to * @param quantities Quantities for one creation unit * @param totalUnits Total number of creation units */ function releaseBid( address[] memory tokens, address to, int256[] memory quantities, uint256 totalUnits ) public onlyCore { uint256[] memory amounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { if (quantities[i] > 0) { uint256 amount = uint256(quantities[i]).mul(totalUnits); TokenInteract.transfer(tokens[i], to, amount); amounts[i] = amount; } } emit ReleaseBid(tokens, to, amounts); } }
* Escrows quantities specified by bid. Only callable by the fund contract. @param tokens Addresses of tokens @param from Bidder address to transfer from @param quantities Quantities for one creation unit @param totalUnits Total number of creation units/
function escrowBid( address[] memory tokens, address from, int256[] memory quantities, uint256 totalUnits ) public onlyCore { for (uint256 i = 0; i < tokens.length; i++) { if (quantities[i] > 0) { uint256 amount = uint256(quantities[i]).mul(totalUnits); tokenProxy.transferTokens(tokens[i], from, address(this), amount); amounts[i] = amount; } } emit EscrowBid(tokens, from, amounts); }
1,081,998
[ 1, 6412, 3870, 10251, 1961, 1269, 635, 9949, 18, 5098, 4140, 635, 326, 284, 1074, 6835, 18, 225, 2430, 23443, 434, 2430, 225, 628, 605, 350, 765, 1758, 358, 7412, 628, 225, 10251, 1961, 4783, 970, 1961, 364, 1245, 6710, 2836, 225, 2078, 7537, 10710, 1300, 434, 6710, 4971, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2904, 492, 17763, 12, 203, 565, 1758, 8526, 3778, 2430, 16, 203, 565, 1758, 628, 16, 203, 565, 509, 5034, 8526, 3778, 10251, 1961, 16, 203, 565, 2254, 5034, 2078, 7537, 203, 225, 262, 203, 565, 1071, 203, 565, 1338, 4670, 203, 225, 288, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2430, 18, 2469, 31, 277, 27245, 288, 203, 1377, 309, 261, 17753, 1961, 63, 77, 65, 405, 374, 13, 288, 203, 3639, 2254, 5034, 3844, 273, 2254, 5034, 12, 17753, 1961, 63, 77, 65, 2934, 16411, 12, 4963, 7537, 1769, 203, 3639, 1147, 3886, 18, 13866, 5157, 12, 7860, 63, 77, 6487, 628, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 3639, 30980, 63, 77, 65, 273, 3844, 31, 203, 1377, 289, 203, 565, 289, 203, 565, 3626, 512, 1017, 492, 17763, 12, 7860, 16, 628, 16, 30980, 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 ]
pragma solidity ^ 0.4 .16; /* 创建一个父类,账户管理员 */ contract owned { address public owner; constructor() public { owner = msg.sender; } /* 修改标志 */ modifier onlyOwner { require(msg.sender == owner); _; } /* 修改管理员账户, onlyOwner代表只能是用户管理员来修改 */ function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } /* receiveApproval服务合约指示代币合约将代币从发送者的账户转移到服务合约的账户(通过调用服务合约的 */ contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { // 公共变量 string public name; //代币名字 string public symbol; //代币符号 uint8 public decimals = 18; //代币小数点位数, 18是默认, 尽量不要更改 uint256 public totalSupply; //代币总量 // 记录各个账户的代币数目 mapping(address => uint256) public balanceOf; // A账户存在B账户资金 mapping(address => mapping(address => uint256)) public allowance; // 转账通知事件 event Transfer(address indexed from, address indexed to, uint256 value); // 销毁金额通知事件 event Burn(address indexed from, uint256 value); /* 构造函数 */ constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 根据decimals计算代币的数量 balanceOf[msg.sender] = totalSupply; // 给生成者所有的代币数量 name = tokenName; // 设置代币的名字 symbol = tokenSymbol; // 设置代币的符号 } /* 私有的交易函数 */ function _transfer(address _from, address _to, uint _value) internal { // 防止转移到0x0, 用burn代替这个功能 require(_to != 0x0); // 检测发送者是否有足够的资金 //require(canOf[_from] >= _value); require(balanceOf[_from] >= _value); // 检查是否溢出(数据类型的溢出) require(balanceOf[_to] + _value > balanceOf[_to]); // 将此保存为将来的断言, 函数最后会有一个检验 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 减少发送者资产 balanceOf[_from] -= _value; // 增加接收者的资产 balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // 断言检测, 不应该为错 assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /* 传递tokens */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /* 从其他账户转移资产 */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /* 授权第三方从发送者账户转移代币,然后通过transferFrom()函数来执行第三方的转移操作 */ function approve(address _spender, uint256 _value) public returns(bool success) { allowance[msg.sender][_spender] = _value; return true; } /* 为其他地址设置津贴, 并通知 发送者通知代币合约, 代币合约通知服务合约receiveApproval, 服务合约指示代币合约将代币从发送者的账户转移到服务合约的账户(通过调用服务合约的transferFrom) */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns(bool success) { tokenRecipient spender = tokenRecipient(_spender); if(approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 销毁代币 */ function burn(uint256 _value) public returns(bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * 从其他账户销毁代币 */ function burnFrom(address _from, uint256 _value) public returns(bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract BTYCT is owned, TokenERC20 { uint256 public totalSupply; //代币总量 uint256 public decimals = 18; //代币小数点位数 uint256 public sellPrice = 510; //出售价格 1枚代币换多少以太 /1000 uint256 public buyPrice = 526; //购买价格 多少以太可购买1枚代币 /1000 uint256 public sysPrice = 766 * 10 ** uint256(decimals); //挖矿的衡量值 uint256 public sysPer = 225; //挖矿的增量百分比 /100 //uint256 public onceOuttime = 86400; //增量的时间 正式 //uint256 public onceAddTime = 864000; //挖矿的时间 正式 //uint256 public onceoutTimePer = 8640000; //增量的百分比 正式 uint256 public onceOuttime = 120; //增量的时间 测试 uint256 public onceAddTime = 600; //挖矿的时间 测试 uint256 public onceoutTimePer = 12000; //增量的百分比 测试 /* 冻结账户 */ mapping(address => bool) public frozenAccount; // 记录各个账户的冻结数目 mapping(address => uint256) public freezeOf; // 记录各个账户的可用数目 mapping(address => uint256) public canOf; // 记录各个账户的释放时间 mapping(address => uint) public cronoutOf; // 记录各个账户的增量时间 mapping(address => uint) public cronaddOf; /* 通知 */ event FrozenFunds(address target, bool frozen); //event Logs (string); /* 构造函数 */ function BTYCT( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} /* 转账, 比父类加入了账户冻结 */ function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(canOf[_from] >= _value); require(balanceOf[_from] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen //挖矿 if(cronaddOf[_from] < 1) { cronaddOf[_from] = now + onceAddTime; } if(cronaddOf[_to] < 1) { cronaddOf[_to] = now + onceAddTime; } //释放 if(cronoutOf[_to] < 1) { cronoutOf[_to] = now + onceOuttime; } if(cronoutOf[_to] < 1) { cronoutOf[_to] = now + onceOuttime; } //if(freezeOf[_from] > 0) { uint lefttime = now - cronoutOf[_from]; if(lefttime > onceOuttime) { uint leftper = lefttime / onceoutTimePer; if(leftper > 1) { leftper = 1; } canOf[_from] = balanceOf[_from] * leftper; freezeOf[_from] = balanceOf[_from] - canOf[_from]; cronoutOf[_from] = now + onceOuttime; } uint lefttimes = now - cronoutOf[_to]; if(lefttimes >= onceOuttime) { uint leftpers = lefttime / onceoutTimePer; if(leftpers > 1) { leftpers = 1; } canOf[_to] = balanceOf[_to] * leftpers; freezeOf[_to] = balanceOf[_to] - canOf[_to]; cronoutOf[_to] = now + onceOuttime; } balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; //减少可用 canOf[_from] -= _value; freezeOf[_from] = balanceOf[_from] - canOf[_from]; //增加冻结 freezeOf[_to] += _value; canOf[_to] = balanceOf[_to] - freezeOf[_to]; emit Transfer(_from, _to, _value); } //获取可用数目 function getcan(address target) public returns (uint256 _value) { if(cronoutOf[target] < 1) { _value = 0; }else{ uint lefttime = now - cronoutOf[target]; uint leftnum = lefttime/onceoutTimePer; if(leftnum > 1){ leftnum = 1; } _value = balanceOf[target]*leftnum; } } /// 向指定账户拨发资金 function mintToken(address target, uint256 mintedAmount) onlyOwner public { require(!frozenAccount[target]); balanceOf[target] += mintedAmount; balanceOf[this] -= mintedAmount; cronoutOf[target] = now + onceOuttime; cronaddOf[target] = now + onceAddTime; freezeOf[target] = balanceOf[target] + mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } //用户每隔10天挖矿一次 function mint() public { require(!frozenAccount[msg.sender]); require(cronaddOf[msg.sender] > 0 && now > cronaddOf[msg.sender] && balanceOf[msg.sender] >= sysPrice); uint256 mintAmount = balanceOf[msg.sender] * sysPer / 10000; balanceOf[msg.sender] += mintAmount; balanceOf[this] -= mintAmount; freezeOf[msg.sender] = balanceOf[msg.sender] + mintAmount; cronaddOf[msg.sender] = now + onceAddTime; emit Transfer(0, this, mintAmount); emit Transfer(this, msg.sender, mintAmount); } /// 冻结 or 解冻账户 function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } // 设置销售购买价格 function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } //设置挖矿参数 function setmyPrice(uint256 systyPrice, uint256 sysPermit) onlyOwner public { sysPrice = systyPrice; sysPer = sysPermit; } // 购买 function buy() payable public returns(uint256 amount) { require(!frozenAccount[msg.sender]); require(buyPrice > 0 && msg.value > buyPrice); // Avoid dividing 0, sending small amounts and spam amount = msg.value / (buyPrice/1000); // Calculate the amount of Dentacoins require(balanceOf[this] >= amount); // checks if it has enough to sell balanceOf[msg.sender] += amount; // adds the amount to buyer's balance balanceOf[this] -= amount; // subtracts amount from seller's balance emit Transfer(this, msg.sender, amount); // execute an event reflecting the change return amount; // ends function and returns } function getprice() constant public returns (uint256 bprice,uint256 spice) { bprice = buyPrice; spice = sellPrice; } function getset() constant public returns (uint256 sprice,uint256 sper) { sprice = sysPrice; sper = sysPer; } // 出售 function sell(uint256 amount) public returns(uint revenue) { require(!frozenAccount[msg.sender]); require(sellPrice > 0); // Avoid selling and spam require(balanceOf[msg.sender] >= amount); // checks if the sender has enough to sell if(cronoutOf[msg.sender] < 1) { cronoutOf[msg.sender] = now + onceOuttime; } uint lefttime = now - cronoutOf[msg.sender]; if(lefttime > onceOuttime) { uint leftper = lefttime / onceoutTimePer; if(leftper > 1) { leftper = 1; } canOf[msg.sender] = balanceOf[msg.sender] * leftper; freezeOf[msg.sender] = balanceOf[msg.sender] - canOf[msg.sender]; cronoutOf[msg.sender] = now + onceOuttime; } require(canOf[msg.sender] >= amount); balanceOf[this] += amount; // adds the amount to owner's balance balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance revenue = amount * sellPrice/1000; require(msg.sender.send(revenue)); // sends ether to the seller: it's important to do this last to prevent recursion attacks emit Transfer(msg.sender, this, amount); // executes an event reflecting on the change return revenue; } }
Check if the targeted balance is enough
require(balanceOf[_from] >= _value);
360,657
[ 1, 1564, 309, 326, 20715, 11013, 353, 7304, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 6528, 12, 12296, 951, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "./StrategySlot.sol"; import "../../../interfaces/bifi/IMarketManager.sol"; import "../../../interfaces/bifi/IFlashloanReceiver.sol"; import "../../../interfaces/bifi/IManagerFlashloan.sol"; import "../../../interfaces/bifi/IProxy.sol"; import "../../../interfaces/bifi/IMarketHandler.sol"; import "../../../interfaces/IERC20.sol"; import "../../../interfaces/IStrategy.sol"; import "../../../interfaces/uniswap/IUniswapV2Router02.sol"; import "../../../interfaces/IERC721.sol"; import "../../../utils/SafeMath.sol"; import "../../../utils/SafeERC20.sol"; /** * @title BiFi-X Standard StrategyLogic contract * @notice Strategy's make positions based on this contract * @author BiFi-X(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract StrategyLogic is IStrategy, StrategySlot { using SafeMath for uint256; using SafeERC20 for IERC20; address constant public ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 constant COLLATERAL_HANDLER = 0; uint256 constant LENDING_HANDLER = 1; uint256 constant EXECUTE_AMOUNT = 10 ** 30; uint256 constant UNIFIED_ONE = 10 ** 18; /** * @dev For successfully start the strategy, calculate the amount of borrow and call the BiFi's manager flashloan function. * @param params The encoded params of strategy * @return Whether or not start strategy succeed */ function startStrategy(bytes memory params) external payable override returns (bool) { // check strategy already executed require(!strategyExecuted, "SL001"); address _this = address(this); strategyExecuted = true; startedByOwner = true; // decode strategy params StrategyParams memory vars = _startParamsDecoder(params); uint256 actualBalance; uint256 expectedBalance = vars.amounts[0].add(vars.fees[0]).add(vars.fees[1]); handlerIDs = vars.handlerIDs; handlersAddress = vars.handlersAddress; if (handlerIDs[COLLATERAL_HANDLER] == 0) { actualBalance = _this.balance; } else { IERC20 collateralToken = IERC20(vars.tokenAddr[COLLATERAL_HANDLER]); actualBalance = collateralToken.balanceOf(_this); } // check seed require(actualBalance >= _convertUnifiedToUnderlying(expectedBalance, vars.decimal[0]), "SL002"); // start strategy for make product contract of position // so, lockFlag true for switch control flow in executeOperation function vars.lockFlag = true; IMarketManager manager = IMarketManager(factory.getManagerAddr()); vars.lendingAmount = vars.amounts[1]; vars.collateralPrice = manager.getTokenHandlerPrice(vars.handlerIDs[COLLATERAL_HANDLER]); // startStrategy's flashloan target asset is collateral asset // if handlerIDs length 1 for Boost Strategy // so, lending token same as collateral, lending asset if (handlerIDs.length == 1) { // Boost case collatral, lending token amount == flashloan amount vars.lendingPrice = vars.collateralPrice; IMarketHandler handler = IMarketHandler(vars.handlersAddress[0]); (, bytes memory data) = handler.handlerViewProxy(abi.encodeWithSelector(handler.getTokenHandlerBorrowLimit.selector)); uint256 borrowLimit = abi.decode(data, (uint256)); // check max borrow amount can repay flashloan uint256 maxBorrowAmount = vars.amounts[0].add(vars.amounts[2]).unifiedMul(borrowLimit); require(maxBorrowAmount >= vars.lendingAmount, "SL003"); emit StartStrategy(productID, address(this), handlerIDs[COLLATERAL_HANDLER], handlerIDs[COLLATERAL_HANDLER], vars.amounts[0], vars.amounts[2], vars.amounts[1], block.timestamp); } else if (handlerIDs.length == 2) { vars.lendingPrice = manager.getTokenHandlerPrice(vars.handlerIDs[LENDING_HANDLER]); emit StartStrategy(productID, address(this), handlerIDs[COLLATERAL_HANDLER], handlerIDs[LENDING_HANDLER], vars.amounts[0], vars.amounts[2], vars.amounts[1], block.timestamp); } else { revert("SL007"); } // execute(start) flashloan manager.flashloan( handlerIDs[COLLATERAL_HANDLER], _this, vars.amounts[2], abi.encode(vars) ); return true; } function endStrategyWithTransfer(uint256 amount, bytes memory params) external onlyOwner payable override returns (bool) { StrategyParams memory vars = _endParamsDecoder(params); address collateralAddr = vars.tokenAddr[0]; if (collateralAddr == ETH_ADDRESS) { require(amount == 0, "only ether transfer"); } else { address owner = NFT.ownerOf(productID); IERC20(collateralAddr).safeTransferFrom(owner, address(this), amount); } _endStrategy(params); return true; } function endStrategy(bytes memory params) external onlyOwner payable override returns (bool) { _endStrategy(params); return true; } /** * @dev End Strategy and selfdestruct Product contract. * @param params The encoded params of end strategy * @return Whether or not succeed */ function _endStrategy(bytes memory params) internal onlyOwner returns (bool) { startedByOwner = true; // decode parameter StrategyParams memory vars = _endParamsDecoder(params); address managerAddr = factory.getManagerAddr(); IMarketManager manager = IMarketManager(managerAddr); // end strategy & release product position // so, lockFlag false for switch control flow in executeOperation function vars.lockFlag = false; address _this = address(this); uint256 handlerID; // endStrategy's flashloan target token is lending token (uint256 depositWithInterest, ) = _getUserAmountWithInterest(handlersAddress[COLLATERAL_HANDLER]); // if handlerIDs length 1 for Boost Strategy // so, same as collateral, lending token if (handlerIDs.length > 1) { handlerID = handlerIDs[LENDING_HANDLER]; emit EndStrategy(productID, address(this), handlerIDs[COLLATERAL_HANDLER], handlerIDs[LENDING_HANDLER], depositWithInterest, vars.amounts[1], block.timestamp); } // else Leverage Strategy // so, flashloan target is repay token else { handlerID = handlerIDs[COLLATERAL_HANDLER]; emit EndStrategy(productID, address(this), handlerIDs[COLLATERAL_HANDLER], handlerIDs[COLLATERAL_HANDLER], depositWithInterest, vars.amounts[1], block.timestamp); } vars.amounts[2] = vars.amounts[1]; // execute(start) flashloan manager.flashloan( handlerID, _this, vars.amounts[2], abi.encode(vars) ); // claim the rewards accumulated through the lending service. _rewardClaim(); // selfdestruct this contract (for reduce gas fee) address _owner = NFT.ownerOf(productID); selfdestruct(payable(_owner)); } /** * @dev Callback function when execute manager flashloan * @param reserve The address of token borrowed * @param amount The amount of token borrowed * @param fee The fee amount of token amount borrowed * @param params The encoded params of strategy(start or end) * @return Whether or not succeed */ function executeOperation( address reserve, uint256 amount, uint256 fee, bytes calldata params ) external onlyManager returns (bool) { // check executeOperation entry point is start or end Strategy require(startedByOwner, "onlyOwner"); // decode params (StrategyParams memory vars) = abi.decode(params, (StrategyParams) ); // calculate flashloan total debt for repay flashloan vars.totalDebt = amount.add(fee); address wethAddr = factory.getWETHAddr(); IERC20 weth = IERC20(wethAddr); address _this = address(this); // if reserve is ETH, replace to WETH address for uniswap if (reserve == ETH_ADDRESS) { reserve = wethAddr; } // if handlersAddress length is 2, Boost case // Boost case, don't to build path for uniswap if (handlersAddress.length == 1) { } // if handlersAddress length is 2, Leverage case // Leverage case, need to build path for uniswap else if (handlersAddress.length == 2) { // pool is not enough (default) vars.pathCount = 3; for (uint256 i = 0; i < vars.handlerIDs.length; i++) { if (vars.handlerIDs[i] == 0) { // pool is enough, ETH vars.pathCount = 2; } } vars.path = new address[](vars.pathCount); if (vars.pathCount == 3) { vars.path[1] = wethAddr; vars.path[2] = reserve; } else if (vars.pathCount == 2) { vars.path[1] = reserve; } // if lock(startStrategy) case // path[0] : lending token (BiFi borrow) if (vars.lockFlag == true) { vars.path[0] = vars.tokenAddr[LENDING_HANDLER] == ETH_ADDRESS ? wethAddr : vars.tokenAddr[LENDING_HANDLER]; } // if unlock(endStrategy) case // path[0] : collateral token (BiFi withdraw) else { vars.path[0] = vars.tokenAddr[COLLATERAL_HANDLER] == ETH_ADDRESS ? wethAddr : vars.tokenAddr[COLLATERAL_HANDLER]; } } else { require(false, "SL004"); } // deposit, borrow if (vars.lockFlag) { _lockPosition(vars); } // repay, withdraw else { _unlockPosition(vars); } // if handlersAddress.length is 2, Leverage case // need to use uniswap if (handlersAddress.length == 2) { // if user collateral is ETH, convert ETH to WETH uint256 _thisBalance = _this.balance; if (_thisBalance > 0) { weth.deposit{value: _thisBalance}(); } if (vars.lockFlag) { // lock case, swap flashloan amount _lockPositionSwapPath(_this, vars); } else { // unlock case, swap flashloan + fee amount _unlockPositionSwapPath(_this, vars); } // if swap token is WETH, withdraw to ETH _thisBalance = weth.balanceOf(_this); if (_thisBalance > 0) { weth.withdraw(_thisBalance); } } depositAsset = vars.amounts[0].add(vars.amounts[2]).unifiedMul(vars.collateralPrice); srcAsset = vars.amounts[0].unifiedMul(vars.collateralPrice); srcPrice = vars.collateralPrice; dstAsset = vars.lendingAmount.unifiedMul(vars.lendingPrice); dstPrice = vars.lendingPrice; // repay flashloan _repayFlashloan(reserve, msg.sender, vars.totalDebt); // extra token return to owner _extraPayback(vars.tokenAddr, _this); startedByOwner = false; return true; } function getDepositAsset() external override view returns (uint256) { return depositAsset; } function getSrcAsset() external override view returns (uint256) { return srcAsset; } function getSrcPrice() external override view returns (uint256) { return srcPrice; } function getDstAsset() external override view returns (uint256) { return dstAsset; } function getDstPrice() external override view returns (uint256) { return dstPrice; } /** * @dev Repay flashloan borrow * @param reserve The address of flashloan borrow token * @param _to the address of flashloan lender * @param amount The amount of repay token */ function _repayFlashloan(address reserve, address _to, uint256 amount) internal { address wethAddr = factory.getWETHAddr(); if (reserve == ETH_ADDRESS || reserve == wethAddr) { payable(_to).transfer(amount); } else { IERC20 token = IERC20(reserve); token.safeTransfer(_to, amount); } } /** * @dev Repay flashloan borrow * @param reserve The address[] of payback token * @param _this the address of extra token owner */ function _extraPayback(address[] memory reserve, address _this) internal { address _owner = NFT.ownerOf(productID); uint256 extraAmount; for (uint256 i = 0; i < reserve.length; i++) { if (reserve[i] != ETH_ADDRESS) { address tokenAddr = reserve[i]; IERC20 token = IERC20(tokenAddr); extraAmount = token.balanceOf(_this); token.safeTransfer(_owner, extraAmount); emit ExtraPayback(productID, address(this), tokenAddr, extraAmount, _owner, block.timestamp); } } payable(_owner).transfer(_this.balance); emit ExtraPayback(productID, address(this), ETH_ADDRESS, _this.balance, _owner, block.timestamp); } /** * @dev Token Swap when lock * @param _this The address of flashloan borrow token * @param vars the count of swap number */ function _lockPositionSwapPath(address _this, StrategyParams memory vars) internal { UniswapParams memory params; params.wethAddr = factory.getWETHAddr(); params.timestamp = block.timestamp; IUniswapV2Router02 uniswap = IUniswapV2Router02(factory.getUniswapAddr()); IERC20 swapToken = IERC20(vars.path[0]); uint256 swapAmount = swapToken.balanceOf(address(this)); swapToken.safeApprove(address(uniswap), swapAmount); uniswap.swapExactTokensForTokens(swapAmount, 0, vars.path, _this, params.timestamp); emit LockPositionSwap(productID, address(this), swapAmount, vars.path, params.timestamp); } // for avoid stack too deep struct UnlockPosition { IUniswapV2Router02 uniswap; IERC20 swapToken; uint256 outTokenAmount; uint256 dstBalanceAmount; } /** * @dev Token Swap when unlock * @param _this The address of flashloan borrow token * @param vars the address[] of token swap path when use uniswap */ function _unlockPositionSwapPath(address _this, StrategyParams memory vars) internal { UniswapParams memory params; UnlockPosition memory localVars; params.timestamp = block.timestamp; localVars.uniswap = IUniswapV2Router02(factory.getUniswapAddr()); localVars.swapToken = IERC20(vars.path[0]); localVars.outTokenAmount = vars.totalDebt; IERC20 dstToken = IERC20(vars.path[vars.path.length-1]); localVars.dstBalanceAmount = dstToken.balanceOf(_this); if (vars.totalDebt > localVars.dstBalanceAmount) { localVars.outTokenAmount = vars.totalDebt.sub(localVars.dstBalanceAmount); } uint amountsInMax = _convertUnifiedToUnderlying(vars.amountsInMax, vars.decimal[0]); localVars.swapToken.safeApprove(address(localVars.uniswap), amountsInMax); localVars.uniswap.swapTokensForExactTokens(localVars.outTokenAmount, amountsInMax, vars.path, _this, params.timestamp); emit UnlockPositionSwap(productID, address(this), localVars.outTokenAmount, amountsInMax, vars.path, params.timestamp); } function _endParamsDecoder(bytes memory strategyParams) internal pure returns (StrategyParams memory) { StrategyParams memory vars; vars.amounts = new uint256[](3); (vars.tokenAddr, vars.handlersAddress, vars.handlerIDs, vars.amounts[1], vars.amountsInMax, vars.decimal) = abi.decode(strategyParams, (address[], address[], uint256[], uint256, uint256, uint256[])); return vars; } function _startParamsDecoder(bytes memory strategyParams) internal pure returns (StrategyParams memory) { StrategyParams memory vars; (vars.tokenAddr, vars.handlersAddress, vars.handlerIDs, // 0: flashloan fee, 1: swap fee vars.fees, // 0: collateral amount, 1: lending amount, 2: flashloan amount vars.amounts, vars.decimal) = abi.decode(strategyParams, (address[], address[], uint256[], uint256[], uint256[], uint256[])); return vars; } /** * @dev deposit and borrow * @param vars The variable of lock strategy * @return Whether or not _lockPosition succeed */ function _lockPosition(StrategyParams memory vars) internal returns (bool) { // add collateral amount uint256 depositAmount = vars.amounts[2].add(vars.amounts[0]); _deposit(vars.tokenAddr[0], handlersAddress[0], depositAmount); uint256 index = handlersAddress.length.sub(1); _borrow(handlersAddress[index], vars.lendingAmount); return true; } /** * @dev Repay and withdraw * @param vars The variable of lock strategy * @return Whether or not _lockPosition succeed */ function _unlockPosition(StrategyParams memory vars) internal returns (bool) { uint256 index = handlersAddress.length.sub(1); _repay(vars.tokenAddr[index], handlersAddress[index], vars.decimal[index]); _withdraw(vars.tokenAddr[0], handlersAddress[0], vars.decimal[0]); return true; } /** * @dev Deposit action to BiFi * @param reserve The address of token * @param tokenHandlerAddr The address of BiFi's tokenHandler contract * @param amount The amount of deposit */ function _deposit(address reserve, address tokenHandlerAddr, uint256 amount) internal { IProxy proxy = IProxy(tokenHandlerAddr); if (reserve == ETH_ADDRESS) { proxy.deposit{value: amount}(0, false); } else { IERC20 token = IERC20(reserve); token.safeApprove(tokenHandlerAddr, amount); proxy.deposit(amount, false); } } /** * @dev Repay action to BiFi * @param reserve The address of token * @param tokenHandlerAddr the address of BiFi's tokenHandler contract * @param decimal the decimal of reserve token */ function _repay(address reserve, address tokenHandlerAddr, uint256 decimal) internal { IProxy proxy = IProxy(tokenHandlerAddr); if (reserve == ETH_ADDRESS) { proxy.repay{value: address(this).balance}(0, false); } else { IERC20 token = IERC20(reserve); uint256 balance = token.balanceOf(address(this)); uint256 unifiedAmount = _convertUnderlyingToUnified(balance, decimal); token.safeApprove(tokenHandlerAddr, balance); proxy.repay(unifiedAmount, false); } } /** * @dev Borrow action to BiFi * @param tokenHandlerAddr the address of BiFi tokenHandler contract * @param amount the amount of borrow */ function _borrow(address tokenHandlerAddr, uint256 amount) internal { IProxy proxy = IProxy(tokenHandlerAddr); proxy.borrow(amount, false); } /** * @dev Withdraw action to BiFi * @param tokenAddr the address of bifi token handler * @param tokenHandlerAddr the address of BiFi tokenHandler contract * @param decimal the decimal of withdraw token */ function _withdraw(address tokenAddr, address tokenHandlerAddr, uint256 decimal) internal { uint256 beforeBalance; uint256 afterBalance; address _this = address(this); if (tokenAddr == ETH_ADDRESS) { beforeBalance = _this.balance; } else { beforeBalance = IERC20(tokenAddr).balanceOf(_this); } IProxy proxy = IProxy(tokenHandlerAddr); (uint256 depositAmountWithInterest, ) = _getUserAmountWithInterest(tokenHandlerAddr); proxy.withdraw(depositAmountWithInterest, false); if (tokenAddr == ETH_ADDRESS) { afterBalance = _this.balance; } else { afterBalance = IERC20(tokenAddr).balanceOf(_this); } uint256 gap = depositAmountWithInterest.unifiedMul(10 ** 15); uint256 balance = _convertUnderlyingToUnified(afterBalance.sub(beforeBalance), decimal); if (depositAmountWithInterest > balance) { require(depositAmountWithInterest.sub(balance) <= gap, "SL005"); } else { require(balance.sub(depositAmountWithInterest) <= gap, "SL006"); } } /** * @dev Reward claim action to BiFi */ function rewardClaim() external { _rewardClaim(); } function getProductID() external view returns (uint256) { return productID; } /** * @dev Reward claim action to BiFi */ function _rewardClaim() internal { address userAddr = address(this); address bifiAddr = factory.getBifiAddr(); IMarketManager manager = IMarketManager(factory.getManagerAddr()); IERC20 bifi = IERC20(bifiAddr); uint256 handlerLength = handlerIDs.length; for (uint256 i = 0; i < handlerLength; i++) { manager.claimHandlerReward(handlerIDs[i], payable(userAddr)); } address owner = NFT.ownerOf(productID); bifi.safeTransfer(owner, bifi.balanceOf(userAddr)); } function _getUserAmountWithInterest(address handlerAddr) internal view returns (uint256, uint256) { IMarketHandler handler = IMarketHandler(handlerAddr); (,bytes memory data)= handler.handlerViewProxy( abi.encodeWithSelector(handler.getUserAmountWithInterest.selector, address(this)) ); return abi.decode(data, (uint256, uint256)); } function _convertUnderlyingToUnified(uint256 underlyingTokenAmount, uint256 underlyingTokenDecimal) internal pure returns (uint256) { return (underlyingTokenAmount.mul(UNIFIED_ONE)) / underlyingTokenDecimal; } function _convertUnifiedToUnderlying(uint256 unifiedTokenAmount, uint256 underlyingTokenDecimal) internal pure returns (uint256) { return (unifiedTokenAmount.mul(underlyingTokenDecimal)) / UNIFIED_ONE; } receive() external payable { } }
* @dev Deposit action to BiFi @param reserve The address of token @param tokenHandlerAddr The address of BiFi's tokenHandler contract @param amount The amount of deposit/
function _deposit(address reserve, address tokenHandlerAddr, uint256 amount) internal { IProxy proxy = IProxy(tokenHandlerAddr); if (reserve == ETH_ADDRESS) { IERC20 token = IERC20(reserve); token.safeApprove(tokenHandlerAddr, amount); proxy.deposit(amount, false); } }
12,627,480
[ 1, 758, 1724, 1301, 358, 16682, 42, 77, 225, 20501, 1021, 1758, 434, 1147, 225, 1147, 1503, 3178, 1021, 1758, 434, 16682, 42, 77, 1807, 1147, 1503, 6835, 225, 3844, 1021, 3844, 434, 443, 1724, 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, 323, 1724, 12, 2867, 20501, 16, 1758, 1147, 1503, 3178, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 565, 467, 3886, 2889, 273, 467, 3886, 12, 2316, 1503, 3178, 1769, 203, 203, 565, 309, 261, 455, 6527, 422, 512, 2455, 67, 15140, 13, 288, 203, 1377, 467, 654, 39, 3462, 1147, 273, 467, 654, 39, 3462, 12, 455, 6527, 1769, 203, 1377, 1147, 18, 4626, 12053, 537, 12, 2316, 1503, 3178, 16, 3844, 1769, 203, 1377, 2889, 18, 323, 1724, 12, 8949, 16, 629, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xF456899bA5c2738778BC88e10d4ae379F439A0DA/sources/contracts/WAGMI/WagmiFlyer.sol
* @dev owner can convert flyer to main contract's NFT/
function flyerConversion(address owner, uint256 tokenId) external { require(_msgSender() == mainContractAddress, "Only main contract can do this."); require(owner == ownerOf(tokenId), "Target must own token."); _burn(tokenId); emit Conversion(owner, tokenId); }
16,545,477
[ 1, 8443, 848, 1765, 21434, 264, 358, 2774, 6835, 1807, 423, 4464, 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, 565, 445, 21434, 264, 6814, 12, 2867, 3410, 16, 2254, 5034, 1147, 548, 13, 3903, 288, 203, 3639, 2583, 24899, 3576, 12021, 1435, 422, 2774, 8924, 1887, 16, 315, 3386, 2774, 6835, 848, 741, 333, 1199, 1769, 203, 3639, 2583, 12, 8443, 422, 3410, 951, 12, 2316, 548, 3631, 315, 2326, 1297, 4953, 1147, 1199, 1769, 203, 3639, 389, 70, 321, 12, 2316, 548, 1769, 203, 3639, 3626, 16401, 12, 8443, 16, 1147, 548, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.13; import "./interfaces/IFactory.sol"; import "./interfaces/IBDeployer.sol"; import "./interfaces/IBorrowable.sol"; import "./interfaces/ICDeployer.sol"; import "./interfaces/ICollateral.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./interfaces/ISimpleUniswapOracle.sol"; import "./libraries/Errors.sol"; // TODO: Inherit IFactory. contract Factory { address public admin; address public pendingAdmin; address public reservesAdmin; address public reservesPendingAdmin; address public reservesManager; struct LendingPool { bool initialized; uint24 lendingPoolId; address collateral; address borrowable0; address borrowable1; } mapping(address => LendingPool) public getLendingPool; // get by UniswapV2Pair address[] public allLendingPools; // address of the UniswapV2Pair function allLendingPoolsLength() external view returns (uint) { return allLendingPools.length; } IBDeployer public bDeployer; ICDeployer public cDeployer; ISimpleUniswapOracle public simpleUniswapOracle; event LendingPoolInitialized(address indexed uniswapV2Pair, address indexed token0, address indexed token1, address collateral, address borrowable0, address borrowable1, uint lendingPoolId); event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); event NewAdmin(address oldAdmin, address newAdmin); event NewReservesPendingAdmin(address oldReservesPendingAdmin, address newReservesPendingAdmin); event NewReservesAdmin(address oldReservesAdmin, address newReservesAdmin); event NewReservesManager(address oldReservesManager, address newReservesManager); constructor(address _admin, address _reservesAdmin, IBDeployer _bDeployer, ICDeployer _cDeployer, ISimpleUniswapOracle _simpleUniswapOracle) { admin = _admin; reservesAdmin = _reservesAdmin; bDeployer = _bDeployer; cDeployer = _cDeployer; simpleUniswapOracle = _simpleUniswapOracle; emit NewAdmin(address(0), _admin); emit NewReservesAdmin(address(0), _reservesAdmin); } function _getTokens(address uniswapV2Pair) private view returns (address token0, address token1) { token0 = IUniswapV2Pair(uniswapV2Pair).token0(); token1 = IUniswapV2Pair(uniswapV2Pair).token1(); } function _createLendingPool(address uniswapV2Pair) private { if (getLendingPool[uniswapV2Pair].lendingPoolId != 0) return; allLendingPools.push(uniswapV2Pair); getLendingPool[uniswapV2Pair] = LendingPool(false, uint24(allLendingPools.length), address(0), address(0), address(0)); } function createCollateral(address uniswapV2Pair) external returns (address collateral) { _getTokens(uniswapV2Pair); _require(getLendingPool[uniswapV2Pair].collateral == address(0), Errors.LENDING_COMPONENT_ALREADY_EXISTS); collateral = cDeployer.deployCollateral(uniswapV2Pair); ICollateral(collateral)._setFactory(); _createLendingPool(uniswapV2Pair); getLendingPool[uniswapV2Pair].collateral = collateral; } function createBorrowable0(address uniswapV2Pair) external returns (address borrowable0) { _getTokens(uniswapV2Pair); _require(getLendingPool[uniswapV2Pair].borrowable0 == address(0), Errors.LENDING_COMPONENT_ALREADY_EXISTS); borrowable0 = bDeployer.deployBorrowable(uniswapV2Pair, 0); IBorrowable(borrowable0)._setFactory(); _createLendingPool(uniswapV2Pair); getLendingPool[uniswapV2Pair].borrowable0 = borrowable0; } function createBorrowable1(address uniswapV2Pair) external returns (address borrowable1) { _getTokens(uniswapV2Pair); _require(getLendingPool[uniswapV2Pair].borrowable1 == address(0), Errors.LENDING_COMPONENT_ALREADY_EXISTS); borrowable1 = bDeployer.deployBorrowable(uniswapV2Pair, 1); IBorrowable(borrowable1)._setFactory(); _createLendingPool(uniswapV2Pair); getLendingPool[uniswapV2Pair].borrowable1 = borrowable1; } function initializeLendingPool(address uniswapV2Pair) external { (address token0, address token1) = _getTokens(uniswapV2Pair); LendingPool memory lPool = getLendingPool[uniswapV2Pair]; _require(!lPool.initialized, Errors.LENDING_POOL_ALREADY_INITIALIZED); _require(lPool.collateral != address(0), Errors.COLLATERAL_NOT_CREATED); _require(lPool.borrowable0 != address(0), Errors.BORROWABLE_ZERO_NOT_CREATED); _require(lPool.borrowable1 != address(0), Errors.BORROWABLE_ONE_NOT_CREATED); (,,,,,bool oracleInitialized) = simpleUniswapOracle.getPair(uniswapV2Pair); if (!oracleInitialized) simpleUniswapOracle.initialize(uniswapV2Pair); ICollateral(lPool.collateral)._initialize("Impermax Collateral", "imxC", uniswapV2Pair, lPool.borrowable0, lPool.borrowable1); IBorrowable(lPool.borrowable0)._initialize("Impermax Borrowable", "imxB", token0, lPool.collateral); IBorrowable(lPool.borrowable1)._initialize("Impermax Borrowable", "imxB", token1, lPool.collateral); getLendingPool[uniswapV2Pair].initialized = true; emit LendingPoolInitialized(uniswapV2Pair, token0, token1, lPool.collateral, lPool.borrowable0, lPool.borrowable1, lPool.lendingPoolId); } function _setPendingAdmin(address newPendingAdmin) external { _require(msg.sender == admin, Errors.UNAUTHORIZED_CALL); address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } function _acceptAdmin() external { _require(msg.sender == pendingAdmin, Errors.UNAUTHORIZED_CALL); address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; admin = pendingAdmin; pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, address(0)); } function _setReservesPendingAdmin(address newReservesPendingAdmin) external { _require(msg.sender == reservesAdmin, Errors.UNAUTHORIZED_CALL); address oldReservesPendingAdmin = reservesPendingAdmin; reservesPendingAdmin = newReservesPendingAdmin; emit NewReservesPendingAdmin(oldReservesPendingAdmin, newReservesPendingAdmin); } function _acceptReservesAdmin() external { _require(msg.sender == reservesPendingAdmin, Errors.UNAUTHORIZED_CALL); address oldReservesAdmin = reservesAdmin; address oldReservesPendingAdmin = reservesPendingAdmin; reservesAdmin = reservesPendingAdmin; reservesPendingAdmin = address(0); emit NewReservesAdmin(oldReservesAdmin, reservesAdmin); emit NewReservesPendingAdmin(oldReservesPendingAdmin, address(0)); } function _setReservesManager(address newReservesManager) external { _require(msg.sender == reservesAdmin, Errors.UNAUTHORIZED_CALL); address oldReservesManager = reservesManager; reservesManager = newReservesManager; emit NewReservesManager(oldReservesManager, newReservesManager); } }
TODO: Inherit IFactory.
contract Factory { address public admin; address public pendingAdmin; address public reservesAdmin; address public reservesPendingAdmin; address public reservesManager; struct LendingPool { bool initialized; uint24 lendingPoolId; address collateral; address borrowable0; address borrowable1; } function allLendingPoolsLength() external view returns (uint) { return allLendingPools.length; } IBDeployer public bDeployer; ICDeployer public cDeployer; ISimpleUniswapOracle public simpleUniswapOracle; event LendingPoolInitialized(address indexed uniswapV2Pair, address indexed token0, address indexed token1, address collateral, address borrowable0, address borrowable1, uint lendingPoolId); event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); event NewAdmin(address oldAdmin, address newAdmin); event NewReservesPendingAdmin(address oldReservesPendingAdmin, address newReservesPendingAdmin); event NewReservesAdmin(address oldReservesAdmin, address newReservesAdmin); event NewReservesManager(address oldReservesManager, address newReservesManager); constructor(address _admin, address _reservesAdmin, IBDeployer _bDeployer, ICDeployer _cDeployer, ISimpleUniswapOracle _simpleUniswapOracle) { admin = _admin; reservesAdmin = _reservesAdmin; bDeployer = _bDeployer; cDeployer = _cDeployer; simpleUniswapOracle = _simpleUniswapOracle; emit NewAdmin(address(0), _admin); emit NewReservesAdmin(address(0), _reservesAdmin); } function _getTokens(address uniswapV2Pair) private view returns (address token0, address token1) { token0 = IUniswapV2Pair(uniswapV2Pair).token0(); token1 = IUniswapV2Pair(uniswapV2Pair).token1(); } function _createLendingPool(address uniswapV2Pair) private { if (getLendingPool[uniswapV2Pair].lendingPoolId != 0) return; allLendingPools.push(uniswapV2Pair); getLendingPool[uniswapV2Pair] = LendingPool(false, uint24(allLendingPools.length), address(0), address(0), address(0)); } function createCollateral(address uniswapV2Pair) external returns (address collateral) { _getTokens(uniswapV2Pair); _require(getLendingPool[uniswapV2Pair].collateral == address(0), Errors.LENDING_COMPONENT_ALREADY_EXISTS); collateral = cDeployer.deployCollateral(uniswapV2Pair); ICollateral(collateral)._setFactory(); _createLendingPool(uniswapV2Pair); getLendingPool[uniswapV2Pair].collateral = collateral; } function createBorrowable0(address uniswapV2Pair) external returns (address borrowable0) { _getTokens(uniswapV2Pair); _require(getLendingPool[uniswapV2Pair].borrowable0 == address(0), Errors.LENDING_COMPONENT_ALREADY_EXISTS); borrowable0 = bDeployer.deployBorrowable(uniswapV2Pair, 0); IBorrowable(borrowable0)._setFactory(); _createLendingPool(uniswapV2Pair); getLendingPool[uniswapV2Pair].borrowable0 = borrowable0; } function createBorrowable1(address uniswapV2Pair) external returns (address borrowable1) { _getTokens(uniswapV2Pair); _require(getLendingPool[uniswapV2Pair].borrowable1 == address(0), Errors.LENDING_COMPONENT_ALREADY_EXISTS); borrowable1 = bDeployer.deployBorrowable(uniswapV2Pair, 1); IBorrowable(borrowable1)._setFactory(); _createLendingPool(uniswapV2Pair); getLendingPool[uniswapV2Pair].borrowable1 = borrowable1; } function initializeLendingPool(address uniswapV2Pair) external { (address token0, address token1) = _getTokens(uniswapV2Pair); LendingPool memory lPool = getLendingPool[uniswapV2Pair]; _require(!lPool.initialized, Errors.LENDING_POOL_ALREADY_INITIALIZED); _require(lPool.collateral != address(0), Errors.COLLATERAL_NOT_CREATED); _require(lPool.borrowable0 != address(0), Errors.BORROWABLE_ZERO_NOT_CREATED); _require(lPool.borrowable1 != address(0), Errors.BORROWABLE_ONE_NOT_CREATED); (,,,,,bool oracleInitialized) = simpleUniswapOracle.getPair(uniswapV2Pair); if (!oracleInitialized) simpleUniswapOracle.initialize(uniswapV2Pair); ICollateral(lPool.collateral)._initialize("Impermax Collateral", "imxC", uniswapV2Pair, lPool.borrowable0, lPool.borrowable1); IBorrowable(lPool.borrowable0)._initialize("Impermax Borrowable", "imxB", token0, lPool.collateral); IBorrowable(lPool.borrowable1)._initialize("Impermax Borrowable", "imxB", token1, lPool.collateral); getLendingPool[uniswapV2Pair].initialized = true; emit LendingPoolInitialized(uniswapV2Pair, token0, token1, lPool.collateral, lPool.borrowable0, lPool.borrowable1, lPool.lendingPoolId); } function _setPendingAdmin(address newPendingAdmin) external { _require(msg.sender == admin, Errors.UNAUTHORIZED_CALL); address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } function _acceptAdmin() external { _require(msg.sender == pendingAdmin, Errors.UNAUTHORIZED_CALL); address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; admin = pendingAdmin; pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, address(0)); } function _setReservesPendingAdmin(address newReservesPendingAdmin) external { _require(msg.sender == reservesAdmin, Errors.UNAUTHORIZED_CALL); address oldReservesPendingAdmin = reservesPendingAdmin; reservesPendingAdmin = newReservesPendingAdmin; emit NewReservesPendingAdmin(oldReservesPendingAdmin, newReservesPendingAdmin); } function _acceptReservesAdmin() external { _require(msg.sender == reservesPendingAdmin, Errors.UNAUTHORIZED_CALL); address oldReservesAdmin = reservesAdmin; address oldReservesPendingAdmin = reservesPendingAdmin; reservesAdmin = reservesPendingAdmin; reservesPendingAdmin = address(0); emit NewReservesAdmin(oldReservesAdmin, reservesAdmin); emit NewReservesPendingAdmin(oldReservesPendingAdmin, address(0)); } function _setReservesManager(address newReservesManager) external { _require(msg.sender == reservesAdmin, Errors.UNAUTHORIZED_CALL); address oldReservesManager = reservesManager; reservesManager = newReservesManager; emit NewReservesManager(oldReservesManager, newReservesManager); } }
945,950
[ 1, 6241, 30, 25953, 467, 1733, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7822, 288, 203, 202, 2867, 1071, 3981, 31, 203, 202, 2867, 1071, 4634, 4446, 31, 203, 202, 2867, 1071, 400, 264, 3324, 4446, 31, 203, 202, 2867, 1071, 400, 264, 3324, 8579, 4446, 31, 203, 202, 2867, 1071, 400, 264, 3324, 1318, 31, 203, 1082, 203, 202, 1697, 511, 2846, 2864, 288, 203, 202, 202, 6430, 6454, 31, 203, 202, 202, 11890, 3247, 328, 2846, 25136, 31, 203, 202, 202, 2867, 4508, 2045, 287, 31, 203, 202, 202, 2867, 29759, 429, 20, 31, 203, 202, 202, 2867, 29759, 429, 21, 31, 203, 202, 97, 203, 202, 915, 777, 48, 2846, 16639, 1782, 1435, 3903, 1476, 1135, 261, 11890, 13, 288, 203, 202, 202, 2463, 777, 48, 2846, 16639, 18, 2469, 31, 203, 202, 97, 203, 202, 203, 202, 13450, 10015, 264, 1071, 324, 10015, 264, 31, 203, 202, 2871, 10015, 264, 1071, 276, 10015, 264, 31, 203, 202, 5127, 2052, 984, 291, 91, 438, 23601, 1071, 4143, 984, 291, 91, 438, 23601, 31, 203, 202, 203, 202, 2575, 511, 2846, 2864, 11459, 12, 2867, 8808, 640, 291, 91, 438, 58, 22, 4154, 16, 1758, 8808, 1147, 20, 16, 1758, 8808, 1147, 21, 16, 203, 202, 202, 2867, 4508, 2045, 287, 16, 1758, 29759, 429, 20, 16, 1758, 29759, 429, 21, 16, 2254, 328, 2846, 25136, 1769, 203, 202, 2575, 1166, 8579, 4446, 12, 2867, 1592, 8579, 4446, 16, 1758, 394, 8579, 4446, 1769, 203, 202, 2575, 1166, 4446, 12, 2867, 1592, 4446, 16, 1758, 394, 4446, 1769, 203, 202, 2575, 1166, 607, 264, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {BFacetOwner} from "./base/BFacetOwner.sol"; import {LibConcurrentCanExec} from "../libraries/LibConcurrentCanExec.sol"; contract ConcurrentCanExecFacet is BFacetOwner { function setSlotLength(uint256 _slotLength) external onlyOwner { LibConcurrentCanExec.setSlotLength(_slotLength); } function slotLength() external view returns (uint256) { return LibConcurrentCanExec.slotLength(); } function concurrentCanExec(uint256 _buffer) external view returns (bool) { return LibConcurrentCanExec.concurrentCanExec(_buffer); } function getCurrentExecutorIndex() external view returns (uint256 executorIndex, uint256 remainingBlocksInSlot) { return LibConcurrentCanExec.getCurrentExecutorIndex(); } function currentExecutor() external view returns ( address executor, uint256 executorIndex, uint256 remainingBlocksInSlot ) { return LibConcurrentCanExec.currentExecutor(); } function mySlotStatus(uint256 _buffer) external view returns (LibConcurrentCanExec.SlotStatus) { return LibConcurrentCanExec.mySlotStatus(_buffer); } function calcExecutorIndex( uint256 _currentBlock, uint256 _blocksPerSlot, uint256 _numberOfExecutors ) external pure returns (uint256 executorIndex, uint256 remainingBlocksInSlot) { return LibConcurrentCanExec.calcExecutorIndex( _currentBlock, _blocksPerSlot, _numberOfExecutors ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {LibDiamond} from "../../libraries/standard/LibDiamond.sol"; abstract contract BFacetOwner { modifier onlyOwner() { LibDiamond.enforceIsContractOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {LibExecutor} from "./LibExecutor.sol"; library LibConcurrentCanExec { using LibExecutor for address; enum SlotStatus {Open, Closing, Closed} struct ConcurrentExecStorage { uint256 slotLength; } bytes32 private constant _CONCURRENT_EXEC_STORAGE_POSITION = keccak256("gelato.diamond.concurrentexec.storage"); function setSlotLength(uint256 _slotLength) internal { concurrentExecStorage().slotLength = _slotLength; } function slotLength() internal view returns (uint256) { return concurrentExecStorage().slotLength; } function concurrentCanExec(uint256 _buffer) internal view returns (bool) { return msg.sender.canExec() && LibExecutor.numberOfExecutors() == 1 ? true : mySlotStatus(_buffer) == LibConcurrentCanExec.SlotStatus.Open; } function getCurrentExecutorIndex() internal view returns (uint256 executorIndex, uint256 remainingBlocksInSlot) { uint256 numberOfExecutors = LibExecutor.numberOfExecutors(); uint256 currentSlotLength = slotLength(); require( numberOfExecutors > 0, "LibConcurrentCanExec.getCurrentExecutorIndex: 0 executors" ); require( currentSlotLength > 0, "LibConcurrentCanExec.getCurrentExecutorIndex: 0 slotLength" ); return calcExecutorIndex( block.number, currentSlotLength, numberOfExecutors ); } function currentExecutor() internal view returns ( address executor, uint256 executorIndex, uint256 remainingBlocksInSlot ) { (executorIndex, remainingBlocksInSlot) = getCurrentExecutorIndex(); executor = LibExecutor.executorAt(executorIndex); } function mySlotStatus(uint256 _buffer) internal view returns (SlotStatus) { (uint256 executorIndex, uint256 remainingBlocksInSlot) = getCurrentExecutorIndex(); address executor = LibExecutor.executorAt(executorIndex); if (msg.sender != executor) return SlotStatus.Closed; return remainingBlocksInSlot <= _buffer ? SlotStatus.Closing : SlotStatus.Open; } // Example: blocksPerSlot = 3, numberOfExecutors = 2 // // Block number 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ... // --------------------------------------------- // slotIndex 0 | 0 | 0 | 1 | 1 | 1 | 2 | 2 | 2 | 3 | ... // --------------------------------------------- // executorIndex 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | ... // remainingBlocksInSlot 2 | 1 | 0 | 2 | 1 | 0 | 2 | 1 | 0 | 2 | ... // function calcExecutorIndex( uint256 _currentBlock, uint256 _blocksPerSlot, uint256 _numberOfExecutors ) internal pure returns (uint256 executorIndex, uint256 remainingBlocksInSlot) { uint256 slotIndex = _currentBlock / _blocksPerSlot; return ( slotIndex % _numberOfExecutors, (slotIndex + 1) * _blocksPerSlot - _currentBlock - 1 ); } function concurrentExecStorage() internal pure returns (ConcurrentExecStorage storage ces) { bytes32 position = _CONCURRENT_EXEC_STORAGE_POSITION; assembly { ces.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import { EnumerableSet } from "../../../vendor/openzeppelin/contracts/utils/EnumerableSet.sol"; library LibExecutor { using EnumerableSet for EnumerableSet.AddressSet; struct ExecutorStorage { EnumerableSet.AddressSet executors; uint256 gasMargin; } bytes32 private constant _EXECUTOR_STORAGE_POSITION = keccak256("gelato.diamond.executor.storage"); function addExecutor(address _executor) internal returns (bool) { return executorStorage().executors.add(_executor); } function removeExecutor(address _executor) internal returns (bool) { return executorStorage().executors.remove(_executor); } function setGasMargin(uint256 _gasMargin) internal { executorStorage().gasMargin = _gasMargin; } function canExec(address _executor) internal view returns (bool) { return isExecutor(_executor); } function isExecutor(address _executor) internal view returns (bool) { return executorStorage().executors.contains(_executor); } function executorAt(uint256 _index) internal view returns (address) { return executorStorage().executors.at(_index); } function executors() internal view returns (address[] memory executors_) { uint256 length = numberOfExecutors(); executors_ = new address[](length); for (uint256 i; i < length; i++) executors_[i] = executorAt(i); } function numberOfExecutors() internal view returns (uint256) { return executorStorage().executors.length(); } function gasMargin() internal view returns (uint256) { return executorStorage().gasMargin; } function executorStorage() internal pure returns (ExecutorStorage storage es) { bytes32 position = _EXECUTOR_STORAGE_POSITION; assembly { es.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; // https://github.com/mudgen/diamond-3/blob/b009cd08b7822bad727bbcc47aa1b50d8b50f7f0/contracts/libraries/LibDiamond.sol#L1 /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import "../../interfaces/standard/IDiamondCut.sol"; // Custom due to incorrect string casting (non UTF-8 formatted) import {GelatoBytes} from "../../../../lib/GelatoBytes.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct FacetAddressAndPosition { address facetAddress; uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint16 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the selector in the facetFunctionSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. 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 isContractOwner(address _guy) internal view returns (bool) { return _guy == contractOwner(); } function enforceIsContractOwner() internal view { require( msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner" ); } event DiamondCut( IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata ); // Internal function version of diamondCut function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { for ( uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++ ) { IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action; if (action == IDiamondCut.FacetCutAction.Add) { addFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else if (action == IDiamondCut.FacetCutAction.Replace) { replaceFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else if (action == IDiamondCut.FacetCutAction.Remove) { removeFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { require( _functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut" ); DiamondStorage storage ds = diamondStorage(); // uint16 selectorCount = uint16(diamondStorage().selectors.length); require( _facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)" ); uint16 selectorPosition = uint16( ds.facetFunctionSelectors[_facetAddress] .functionSelectors .length ); // add new facet address if it does not exist if (selectorPosition == 0) { enforceHasContractCode( _facetAddress, "LibDiamondCut: New facet has no code" ); ds.facetFunctionSelectors[_facetAddress] .facetAddressPosition = uint16(ds.facetAddresses.length); ds.facetAddresses.push(_facetAddress); } for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++ ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require( oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists" ); ds.facetFunctionSelectors[_facetAddress].functionSelectors.push( selector ); ds.selectorToFacetAndPosition[selector] .facetAddress = _facetAddress; ds.selectorToFacetAndPosition[selector] .functionSelectorPosition = selectorPosition; selectorPosition++; } } function replaceFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { require( _functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut" ); DiamondStorage storage ds = diamondStorage(); require( _facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)" ); uint16 selectorPosition = uint16( ds.facetFunctionSelectors[_facetAddress] .functionSelectors .length ); // add new facet address if it does not exist if (selectorPosition == 0) { enforceHasContractCode( _facetAddress, "LibDiamondCut: New facet has no code" ); ds.facetFunctionSelectors[_facetAddress] .facetAddressPosition = uint16(ds.facetAddresses.length); ds.facetAddresses.push(_facetAddress); } for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++ ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require( oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function" ); removeFunction(oldFacetAddress, selector); // add function ds.selectorToFacetAndPosition[selector] .functionSelectorPosition = selectorPosition; ds.facetFunctionSelectors[_facetAddress].functionSelectors.push( selector ); ds.selectorToFacetAndPosition[selector] .facetAddress = _facetAddress; selectorPosition++; } } function removeFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { require( _functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut" ); DiamondStorage storage ds = diamondStorage(); // if function does not exist then do nothing and return require( _facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)" ); for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++ ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; removeFunction(oldFacetAddress, selector); } } function removeFunction(address _facetAddress, bytes4 _selector) internal { DiamondStorage storage ds = diamondStorage(); require( _facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist" ); // an immutable function is a function defined directly in a diamond require( _facetAddress != address(this), "LibDiamondCut: Can't remove immutable function" ); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1; // if not the same then replace _selector with lastSelector if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[ lastSelectorPosition ]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[ selectorPosition ] = lastSelector; ds.selectorToFacetAndPosition[lastSelector] .functionSelectorPosition = uint16(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress] .facetAddressPosition = uint16(facetAddressPosition); } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_facetAddress] .facetAddressPosition; } } 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 GelatoBytes.revertWithError(error, "LibDiamondCut:_init:"); } 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); } } // "SPDX-License-Identifier: UNLICENSED" pragma solidity 0.8.0; library GelatoBytes { function calldataSliceSelector(bytes calldata _bytes) internal pure returns (bytes4 selector) { selector = _bytes[0] | (bytes4(_bytes[1]) >> 8) | (bytes4(_bytes[2]) >> 16) | (bytes4(_bytes[3]) >> 24); } function memorySliceSelector(bytes memory _bytes) internal pure returns (bytes4 selector) { selector = _bytes[0] | (bytes4(_bytes[1]) >> 8) | (bytes4(_bytes[2]) >> 16) | (bytes4(_bytes[3]) >> 24); } function revertWithError(bytes memory _bytes, string memory _tracingInfo) internal pure { // 68: 32-location, 32-length, 4-ErrorSelector, UTF-8 err if (_bytes.length % 32 == 4) { bytes4 selector; assembly { selector := mload(add(0x20, _bytes)) } if (selector == 0x08c379a0) { // Function selector for Error(string) assembly { _bytes := add(_bytes, 68) } revert(string(abi.encodePacked(_tracingInfo, string(_bytes)))); } else { revert( string(abi.encodePacked(_tracingInfo, "NoErrorSelector")) ); } } else { revert( string(abi.encodePacked(_tracingInfo, "UnexpectedReturndata")) ); } } function returnError(bytes memory _bytes, string memory _tracingInfo) internal pure returns (string memory) { // 68: 32-location, 32-length, 4-ErrorSelector, UTF-8 err if (_bytes.length % 32 == 4) { bytes4 selector; assembly { selector := mload(add(0x20, _bytes)) } if (selector == 0x08c379a0) { // Function selector for Error(string) assembly { _bytes := add(_bytes, 68) } return string(abi.encodePacked(_tracingInfo, string(_bytes))); } else { return string(abi.encodePacked(_tracingInfo, "NoErrorSelector")); } } else { return string(abi.encodePacked(_tracingInfo, "UnexpectedReturndata")); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, "EnumerableSet: index out of bounds" ); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
Custom due to incorrect string casting (non UTF-8 formatted)
import {GelatoBytes} from "../../../../lib/GelatoBytes.sol";
51,212
[ 1, 3802, 6541, 358, 11332, 533, 27660, 261, 5836, 6380, 17, 28, 4955, 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, 5666, 288, 43, 292, 31093, 2160, 97, 628, 315, 16644, 16644, 2941, 19, 43, 292, 31093, 2160, 18, 18281, 14432, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.4; import './ZetherVerifier.sol'; import './BurnVerifier.sol'; import './CashToken.sol'; contract ZSC { CashToken coin; ZetherVerifier zetherverifier; BurnVerifier burnverifier; uint256 public epochLength; // now in milliseconds. uint256 bTotal = 0; // could use erc20.balanceOf(this), but (even pure / view) calls cost gas during EVM execution uint256 constant MAX = 4294967295; // 2^32 - 1 // no sload for constants...! mapping(bytes32 => bytes32[2][2]) acc; // main account mapping mapping(bytes32 => bytes32[2][2]) pTransfers; // storage for pending transfers mapping(bytes32 => address) ethAddrs; mapping(bytes32 => uint256) lastRollOver; bytes32[] nonceSet; // would be more natural to use a mapping, but they can't be deleted / reset! uint256 lastGlobalUpdate = 0; // will be also used as a proxy for "current epoch", seeing as rollovers will be anticipated // not implementing account locking for now...revisit event TransferOccurred(bytes32[2][] parties); // all parties will be notified, client can determine whether it was real or not. // arg is still necessary for transfers---not even so much to know when you received a transfer, as to know when you got rolled over. constructor(address _coin, address _zether, address _burn, uint256 _epochLength) public { coin = CashToken(_coin); zetherverifier = ZetherVerifier(_zether); burnverifier = BurnVerifier(_burn); epochLength = _epochLength; } function simulateAccounts(bytes32[2][] calldata y, uint256 epoch) view external returns (bytes32[2][2][] memory accounts) { // all of this could be assembled locally by querying `acc` and `pTransfers` (and `lastRollOver`) and assembling things by hand // turns out this is extremely _slow_ though, because of the ~ 4 * N queries which must be made. turns out it's much faster // to simply move the entire process into a contract method, and in fact this allows us to make the above 3 private uint256 size = y.length; accounts = new bytes32[2][2][](size); for (uint256 i = 0; i < size; i++) { bytes32 yHash = keccak256(abi.encodePacked(y[i])); accounts[i] = acc[yHash]; if (lastRollOver[yHash] < epoch) { bytes32[2][2] memory scratch = pTransfers[yHash]; assembly { let result := 1 let m := mload(0x40) mstore(m, mload(mload(scratch))) mstore(add(m, 0x20), mload(add(mload(scratch), 0x20))) mstore(add(m, 0x40), mload(mload(mload(add(add(accounts, 0x20), mul(i, 0x20)))))) mstore(add(m, 0x60), mload(add(mload(mload(add(add(accounts, 0x20), mul(i, 0x20)))), 0x20))) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(mload(add(add(accounts, 0x20), mul(i, 0x20)))), 0x40)) mstore(m, mload(mload(add(scratch, 0x20)))) mstore(add(m, 0x20), mload(add(mload(add(scratch, 0x20)), 0x20))) mstore(add(m, 0x40), mload(mload(add(mload(add(add(accounts, 0x20), mul(i, 0x20))), 0x20)))) mstore(add(m, 0x60), mload(add(mload(add(mload(add(add(accounts, 0x20), mul(i, 0x20))), 0x20)), 0x20))) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(add(mload(add(add(accounts, 0x20), mul(i, 0x20))), 0x20)), 0x40)) if iszero(result) { revert(0, 0) } } } } } function rollOver(bytes32 yHash) internal { uint256 e = block.timestamp / 1000000 / epochLength; // can block.timestamp be "gamed"? // https://github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md // note that block.timestamp is technically in _nanoseconds_, although its trailing 3 digits are always 0 (so really micro) if (lastRollOver[yHash] < e) { bytes32[2][2][2] memory scratch = [acc[yHash], pTransfers[yHash]]; assembly { let result := 1 let m := mload(0x40) mstore(m, mload(mload(mload(scratch)))) mstore(add(m, 0x20), mload(add(mload(mload(scratch)), 0x20))) mstore(add(m, 0x40), mload(mload(mload(add(scratch, 0x20))))) mstore(add(m, 0x60), mload(add(mload(mload(add(scratch, 0x20))), 0x20))) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(mload(scratch)), 0x40)) mstore(m, mload(mload(add(mload(scratch), 0x20)))) mstore(add(m, 0x20), mload(add(mload(add(mload(scratch), 0x20)), 0x20))) mstore(add(m, 0x40), mload(mload(add(mload(add(scratch, 0x20)), 0x20)))) mstore(add(m, 0x60), mload(add(mload(add(mload(add(scratch, 0x20)), 0x20)), 0x20))) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(add(mload(scratch), 0x20)), 0x40)) if iszero(result) { revert(0, 0) } } acc[yHash] = scratch[0]; pTransfers[yHash] = [[bytes32(0), bytes32(0)], [bytes32(0), bytes32(0)]]; lastRollOver[yHash] = e; } if (lastGlobalUpdate < e) { lastGlobalUpdate = e; delete nonceSet; } } function register(bytes32[2] calldata y) external { // keeping this as is bytes32 yHash = keccak256(abi.encodePacked(y)); bytes32[2][2] memory scratch = acc[yHash]; require((scratch[0][0] | scratch[0][1] | scratch[1][0] | scratch[1][1]) == 0x00, "Account already registered."); ethAddrs[yHash] = msg.sender; // eth address will be _permanently_ bound to y // warning: front-running danger. client should verify that he was not front-run before depositing funds to y! assembly { calldatacopy(mload(scratch), 0x04, 0x40) // copy contents of y to first inner array of scratch mstore(mload(add(scratch, 0x20)), 0x077da99d806abd13c9f15ece5398525119d11e11e9836b2ee7d23f6159ad87d4) mstore(add(mload(add(scratch, 0x20)), 0x20), 0x01485efa927f2ad41bff567eec88f32fb0a0f706588b4e41a8d587d008b7f875) // account of y is now [y, g] = ElG_y(e, 1). sentinel for having registered } acc[yHash] = scratch; } function fund(bytes32[2] calldata y, uint256 bTransfer) external { bytes32 yHash = keccak256(abi.encodePacked(y)); rollOver(yHash); // registration check here would be redundant, as any `transferFrom` the 0 address will necessarily fail. save an sload require(bTransfer <= MAX, "Deposit amount out of range."); // uint, so other way not necessary? require(bTransfer + bTotal <= MAX, "Fund pushes contract past maximum value."); // if pTransfers[yHash] == [0, 0, 0, 0] then an add and a write will be equivalent... bytes32[2] memory scratch = pTransfers[yHash][0]; // won't let me assign this array using literals / casts assembly { let m := mload(0x40) let result := 1 mstore(m, mload(scratch)) mstore(add(m, 0x20), mload(add(scratch, 0x20))) mstore(add(m, 0x40), 0x077da99d806abd13c9f15ece5398525119d11e11e9836b2ee7d23f6159ad87d4) mstore(add(m, 0x60), 0x01485efa927f2ad41bff567eec88f32fb0a0f706588b4e41a8d587d008b7f875) mstore(add(m, 0x80), bTransfer) // b will hopefully be a primitive / literal and not a pointer / address? result := and(result, staticcall(gas, 0x07, add(m, 0x40), 0x60, add(m, 0x40), 0x40)) result := and(result, staticcall(gas, 0x06, m, 0x80, scratch, 0x40)) if iszero(result) { revert(0, 0) } } pTransfers[yHash][0] = scratch; require(coin.transferFrom(ethAddrs[yHash], address(this), bTransfer), "Transfer from sender failed."); // front-running here would be disadvantageous, but still prevent it here by using ethAddrs[yHash] instead of msg.sender // also adds flexibility: can later issue messages from arbitrary ethereum accounts. bTotal += bTransfer; } function transfer(bytes32[2][] memory L, bytes32[2] memory R, bytes32[2][] memory y, bytes32[2] memory u, bytes memory proof) public { uint256 size = y.length; bytes32[2][] memory CLn = new bytes32[2][](size); bytes32[2][] memory CRn = new bytes32[2][](size); require(L.length == size, "Input array length mismatch!"); uint256 result = 1; for (uint256 i = 0; i < y.length; i++) { bytes32 yHash = keccak256(abi.encodePacked(y[i])); rollOver(yHash); bytes32[2][2] memory scratch = pTransfers[yHash]; assembly { let m := mload(0x40) mstore(m, mload(mload(scratch))) mstore(add(m, 0x20), mload(add(mload(scratch), 0x20))) // calldatacopy(add(m, 0x40), add(0x104, mul(i, 0x40)), 0x40) // copy L[i] onto running block // having to change external --> public to avoid stacktoodeep // as a result, have to use the below two lines instead of the above single line. mstore(add(m, 0x40), mload(mload(add(add(L, 0x20), mul(i, 0x20))))) mstore(add(m, 0x60), mload(add(mload(add(add(L, 0x20), mul(i, 0x20))), 0x20))) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(scratch), 0x40)) mstore(m, mload(mload(add(scratch, 0x20)))) mstore(add(m, 0x20), mload(add(mload(add(scratch, 0x20)), 0x20))) // calldatacopy(add(m, 0x40), 0x24, 0x40) // copy R onto running block mstore(add(m, 0x40), mload(R)) mstore(add(m, 0x60), mload(add(R, 0x20))) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(add(scratch, 0x20)), 0x40)) } pTransfers[yHash] = scratch; // credit / debit / neither y's account. scratch = acc[yHash]; assembly { let m := mload(0x40) mstore(m, mload(mload(scratch))) mstore(add(m, 0x20), mload(add(mload(scratch), 0x20))) mstore(add(m, 0x40), mload(mload(add(add(L, 0x20), mul(i, 0x20))))) mstore(add(m, 0x60), mload(add(mload(add(add(L, 0x20), mul(i, 0x20))), 0x20))) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(add(add(CLn, 0x20), mul(i, 0x20))), 0x40)) mstore(m, mload(mload(add(scratch, 0x20)))) mstore(add(m, 0x20), mload(add(mload(add(scratch, 0x20)), 0x20))) mstore(add(m, 0x40), mload(R)) mstore(add(m, 0x60), mload(add(R, 0x20))) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(add(add(CRn, 0x20), mul(i, 0x20))), 0x40)) } } require(result == 1, "Elliptic curve operations failure. Bad points?"); // warning: no check that recipients are registered accounts, i.e., that _every_ y has been registered to. // make sure that you register your eth account to your pubkey before receiving funds (unless you're using a throwaway, see below). // if you don't, your registration could be pre-empted by an adversary, necessitating that you further transfer before withdrawing // if this pre-empt goes unnoticed, and the further transfer is _not_ taken prior to withdrawal, then you'll lose funds // this is a design decision: could require everyone to be registered...? but this would dampen anonymity a bit. i.e., throwaways // it would be more convenient to not have to register a (new, random) eth account to each throwaway you make. // sure, an adversary could latch on to your throwaway, but you were going to transfer it back to your main account anyway, so who cares? // thus the burden is thus now on you, the _recipient_, to make sure you (successfully) register before receiving funds, // and if you don't and re pre-empted / front-run, to _notice_ and to transfer to a new account before withdrawing // this won't be an issue in practice, as the client software will _force_ you to register right away when your public key is generated, // and will notify you if the process is compromised. bool seen = false; bytes32 uHash = keccak256(abi.encodePacked(u)); for (uint256 i = 0; i < nonceSet.length; i++) { if (nonceSet[i] == uHash) { seen = true; break; } } require(!seen, "Nonce already seen!"); if (size > zetherverifier.baseSize()) { zetherverifier.extendBase(size); } require(zetherverifier.verifyTransfer(CLn, CRn, L, R, y, lastGlobalUpdate, u, proof), "Transfer proof verification failed!"); nonceSet.push(uHash); emit TransferOccurred(y); } function burn(bytes32[2] memory y, uint256 bTransfer, bytes32[2] memory u, bytes memory proof) public { bytes32 yHash = keccak256(abi.encodePacked(y)); rollOver(yHash); require(ethAddrs[yHash] != address(0), "Unregistered account!"); // not necessary for safety, but will prevent accidentally withdrawing to the 0 address require(0 <= bTransfer && bTransfer <= MAX, "Transfer amount out of range."); bytes32[2][2] memory scratch = pTransfers[yHash]; // could technically use sload, but... let's not go there. assembly { let result := 1 let m := mload(0x40) mstore(m, mload(mload(scratch))) mstore(add(m, 0x20), mload(add(mload(scratch), 0x20))) // load bulletproof generator here mstore(add(m, 0x40), 0x077da99d806abd13c9f15ece5398525119d11e11e9836b2ee7d23f6159ad87d4) // g_x mstore(add(m, 0x60), 0x01485efa927f2ad41bff567eec88f32fb0a0f706588b4e41a8d587d008b7f875) // g_y mstore(add(m, 0x80), sub(0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001, bTransfer)) result := and(result, staticcall(gas, 0x07, add(m, 0x40), 0x60, add(m, 0x40), 0x40)) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(scratch), 0x40)) // scratch[0] = acc[yHash][0] * g ^ -b, scratch[1] doesn't change if iszero(result) { revert(0, 0) } } pTransfers[yHash] = scratch; // debit y's balance scratch = acc[yHash]; // simulate debit of acc---just for use in verification, won't be applied assembly { let result := 1 let m := mload(0x40) mstore(m, mload(mload(scratch))) mstore(add(m, 0x20), mload(add(mload(scratch), 0x20))) mstore(add(m, 0x40), 0x077da99d806abd13c9f15ece5398525119d11e11e9836b2ee7d23f6159ad87d4) // g_x mstore(add(m, 0x60), 0x01485efa927f2ad41bff567eec88f32fb0a0f706588b4e41a8d587d008b7f875) // g_y mstore(add(m, 0x80), sub(0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001, bTransfer)) result := and(result, staticcall(gas, 0x07, add(m, 0x40), 0x60, add(m, 0x40), 0x40)) result := and(result, staticcall(gas, 0x06, m, 0x80, mload(scratch), 0x40)) // scratch[0] = acc[yHash][0] * g ^ -b, scratch[1] doesn't change if iszero(result) { revert(0, 0) } } bool seen = false; bytes32 uHash = keccak256(abi.encodePacked(u)); for (uint256 i = 0; i < nonceSet.length; i++) { if (nonceSet[i] == uHash) { // does this have to repeat the sload for each iteration?!? revisit seen = true; break; } } require(!seen, "Nonce already seen!"); require(burnverifier.verifyBurn(scratch[0], scratch[1], y, bTransfer, lastGlobalUpdate, u, proof), "Burn proof verification failed!"); require(coin.transfer(ethAddrs[yHash], bTransfer), "This shouldn't fail... Something went severely wrong."); // note: change from Zether spec. should use bound address not msg.sender, to prevent "front-running attack". bTotal -= bTransfer; nonceSet.push(uHash); } }
can block.timestamp be "gamed"?
uint256 e = block.timestamp / 1000000 / epochLength;
5,473,614
[ 1, 4169, 1203, 18, 5508, 506, 315, 75, 2808, 6, 35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 425, 273, 1203, 18, 5508, 342, 15088, 342, 7632, 1782, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xc3793ecC3A0aa3B5a0f7b23A375b0c92df72DA25/sources/src/utils/MetadataEncoder.sol
@title Librairy used to write and encode on-chain metadata
library MetadataEncoder { using MetadataEncoder for string; function encodeMetadata( string memory name, string memory description, string memory image, string memory externalUrl import {Base64} from "openzeppelin-contracts/contracts/utils/Base64.sol"; import {MetadataProperties} from "src/metadata/MetadataProperties.sol"; ) internal pure returns (string memory) { return string( abi.encodePacked( MetadataProperties.HEADER, Base64.encode( _jsonFile( name, description, encodeSVG(image), externalUrl ) ) ) ); } function _jsonFile( string memory name, string memory description, string memory image, string memory externalUrl ) internal pure returns (bytes memory) { string memory jsonString; jsonString = jsonString.append(MetadataProperties.OPEN_JSON); jsonString = jsonString.append(MetadataProperties.PRE_NAME); jsonString = jsonString.append(name); jsonString = jsonString.append(MetadataProperties.NEXT_ATTRIBUTE); jsonString = jsonString.append(MetadataProperties.PRE_DESCRIPTION); jsonString = jsonString.append(description); jsonString = jsonString.append(MetadataProperties.NEXT_ATTRIBUTE); jsonString = jsonString.append(MetadataProperties.PRE_IMAGE); jsonString = jsonString.append(image); jsonString = jsonString.append(MetadataProperties.NEXT_ATTRIBUTE); jsonString = jsonString.append(MetadataProperties.PRE_EXTERNAL_URL); jsonString = jsonString.append(externalUrl); jsonString = jsonString.append(MetadataProperties.CLOSE_JSON); return abi.encodePacked(jsonString); } function encodeSVG(string memory svgCode) internal pure returns (string memory) { return string( abi.encodePacked( MetadataProperties.SVG_HEADER, Base64.encode(bytes(svgCode)) ) ); } function append(string memory baseString, string memory element) internal pure returns (string memory) { return string.concat(baseString, element); } }
1,911,869
[ 1, 5664, 354, 6913, 1399, 358, 1045, 471, 2017, 603, 17, 5639, 1982, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6912, 7204, 288, 203, 565, 1450, 6912, 7204, 364, 533, 31, 203, 203, 565, 445, 2017, 2277, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 2477, 16, 203, 3639, 533, 3778, 1316, 16, 203, 3639, 533, 3778, 3903, 1489, 203, 203, 5666, 288, 2171, 1105, 97, 628, 315, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 19, 16351, 87, 19, 5471, 19, 2171, 1105, 18, 18281, 14432, 203, 5666, 288, 2277, 2297, 97, 628, 315, 4816, 19, 4165, 19, 2277, 2297, 18, 18281, 14432, 203, 565, 262, 2713, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 203, 5411, 533, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 6912, 2297, 18, 7557, 16, 203, 10792, 3360, 1105, 18, 3015, 12, 203, 13491, 389, 1977, 812, 12, 203, 18701, 508, 16, 203, 18701, 2477, 16, 203, 18701, 2017, 26531, 12, 2730, 3631, 203, 18701, 3903, 1489, 203, 13491, 262, 203, 10792, 262, 203, 7734, 262, 203, 5411, 11272, 203, 565, 289, 203, 203, 565, 445, 389, 1977, 812, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 2477, 16, 203, 3639, 533, 3778, 1316, 16, 203, 3639, 533, 3778, 3903, 1489, 203, 565, 262, 2713, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 533, 3778, 25775, 31, 203, 3639, 25775, 273, 25775, 18, 6923, 12, 2277, 2297, 18, 11437, 67, 2986, 1769, 203, 3639, 25775, 273, 25775, 18, 6923, 12, 2277, 2297, 18, 3670, 67, 1985, 1769, 203, 3639, 25775, 273, 25775, 18, 2 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { // Data persistance using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct airlinesRegistered{ bool funded; uint votes; string name; bool elected; uint256 timestamp; } address[] airlines; mapping (address => airlinesRegistered) private registeredAirlines; mapping(address => uint256) private credit; mapping(address => bool) private authorizedCaller; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event FundsWithdrawed(address sender, uint256 value); //event insuranceBought (uint256 txId, address from, uint256 value); //debug event insuranceBought (uint256 txId, address from, uint256 value, bytes32 flightKey, address airline, string flight, uint256 timestamp, uint256 credited); event insureesCredited (address who, uint256 value, bytes32 flightKey, uint256 credited); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirline ) public { contractOwner = msg.sender; // address firstAirline = contractOwner; //test, remove! registeredAirlines[firstAirline] = airlinesRegistered({ funded: true, votes: 1, name: "First airline", elected: true, timestamp: 1 //block.timestamp //now }); airlines.push(firstAirline); //this.fund.value(10 ether)(firstAirline); //registerAirline(firstAirline); //flightSuretyData.registerAirline(firstAirline, firstAirlineName); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } modifier requireIsAuthorized(address addr) { require(authorizedCaller[addr]==true, "Contract is not authorized"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier requireEnoughFunds(uint256 amount) { require(msg.value >= amount, "Not enough funds"); _; } modifier requireAirlineIsElected (address addr) { require (registeredAirlines[addr].elected==true, "Required by modifier to be registered by an elected/registered airline"); _; } modifier requireAirlineIsFunded (address addr) { require (registeredAirlines[addr].funded==true, "Required by modifier to be funded"); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint256 price, address to) { _; uint256 amountToReturn = msg.value - price; if (amountToReturn >= 0) to.transfer(amountToReturn); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() view external returns(bool) { return operational; } function kill() external { require(msg.sender == contractOwner, "Only the owner can kill this contract"); selfdestruct(contractOwner); } /** * * @return A bool that is this is a voted/registered/elected airline */ function airlineIsRegistered(address addr) view external returns(bool) { return registeredAirlines[addr].elected; } /* * @return For testing, cleans the list */ function cleansRegistered() external { for (uint a = 2; a < airlines.length; a++ ) { delete registeredAirlines[airlines[a]]; } airlines.length = 1; } /** * * @return A bool that is this is a funded airline */ function airlineIsFunded(address addr) view external returns(bool) { return registeredAirlines[addr].funded; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add a contract to the authorization list * */ function authorizeCaller ( address contractAddress ) external requireContractOwner returns(bool success) { authorizedCaller[contractAddress] = true; return (true); } function deauthorizeContract ( address contractAddress ) external requireContractOwner { delete authorizedCaller[contractAddress]; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address addr, string flight, address registeringAirline ) external requireIsAuthorized(msg.sender) returns(bool success) //, uint256 votes { require (registeredAirlines[registeringAirline].funded==true, "Required that registering airline is funded"); require (registeredAirlines[registeringAirline].elected==true, "Required that registering airline is registered"); success = false; if (registeredAirlines[addr].votes == 0) { registeredAirlines[addr].votes = 1; registeredAirlines[addr].elected = false; registeredAirlines[addr].name = flight; } else { registeredAirlines[addr].votes = registeredAirlines[addr].votes.add(1); } if (registeredAirlines[addr].elected == true) return true; // if enough voted if ((airlines.length < 2 * registeredAirlines[addr].votes) || (airlines.length < 4 )) { if (registeredAirlines[addr].funded==true) airlines.push(addr); registeredAirlines[addr].elected = true; success = true; } return (success); //, registeredAirlines[addr].votes } //Track everyone who paid the insurance struct clients { address addr; uint value;// less than 1 ether } mapping(bytes32 => clients[]) private insuree; /** * @dev Buy insurance for a flight * */ function buy ( address airline, string flight, uint256 timestamp, address from ) external payable //checkValue(insurancePrice, tx.origin) { // Transfer money to fund bytes32 flightKey = keccak256(abi.encodePacked(airline, flight, timestamp)); uint256 txId = insuree[flightKey].push(clients({addr: from, value: msg.value})); emit insuranceBought (txId, from, msg.value, flightKey, airline, flight, timestamp, credit[contractOwner]); } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 keyFlight ) external requireIsAuthorized(msg.sender) { clients[] storage ins = insuree[keyFlight]; for (uint i = 0; i < ins.length; i++) { credit[ins[i].addr] = credit[ins[i].addr].add(ins[i].value.mul(15).div(10)); emit insureesCredited (ins[i].addr, ins[i].value, keyFlight, credit[ins[i].addr]); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( uint256 amount ) external requireIsOperational { address ins = tx.origin; //check require (amount <= credit[ins], "Not enough credit"); //effect credit[ins] = credit[ins].sub(amount); //interaction ins.transfer(amount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund (address addr, uint256 value) external payable { require (value >= 10, "Insuficient payment"); // if this is an airline, register as funded registeredAirlines[addr].funded = true; if (registeredAirlines[addr].elected==true) airlines.push(addr); } function safeWithdraw ( uint256 amount, address sender ) external requireEnoughFunds (amount) payable returns (bool) //recipient.call.gas(0).value(...) { // check //require(msg.sender == tx.origin, "Contracts not allowed to call this function"); require(credit[sender] >= msg.value, "There is no sufficient value to withdraw"); //effect credit[sender] = credit[sender].sub(msg.value); //Interaction emit FundsWithdrawed(sender, msg.value); return sender.send(msg.value); //sender.call.value(amount).gas(4712388)(); } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure public returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function getFlightData (address addr ) view external returns (uint256 timestamp) { return registeredAirlines[addr].timestamp; } function getCreditAmount (address passenger) external view requireIsOperational returns (uint256 amount) { return credit[passenger]; } /** * @dev Fallback function for funding smart contract. */ function() external payable { // this.fund(msg.sender); } }
* @dev Add a contract to the authorization list/
function authorizeCaller ( address contractAddress ) external requireContractOwner returns(bool success) { authorizedCaller[contractAddress] = true; return (true); }
6,467,262
[ 1, 986, 279, 6835, 358, 326, 6093, 666, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12229, 11095, 203, 18701, 261, 27699, 27573, 1758, 6835, 1887, 203, 18701, 262, 203, 18701, 3903, 203, 18701, 2583, 8924, 5541, 203, 18701, 1135, 12, 6430, 2216, 13, 203, 565, 288, 203, 3639, 10799, 11095, 63, 16351, 1887, 65, 273, 638, 31, 203, 3639, 327, 261, 3767, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /// @title Interface to interact with Bubbles contract. interface IBubbles { function mint(address recipient, uint256 amount) external; } /// @author The Axolittles Team /// @title Contract for staking axos to receive $BUBBLE contract AxolittlesStaking is Ownable { address public AXOLITTLES = 0xf36446105fF682999a442b003f2224BcB3D82067; address public TOKEN = 0x58f46F627C88a3b217abc80563B9a726abB873ba; bool public stakingPaused; bool public isPositiveSum = true; uint64 internal stakeTarget = 6000; // Amount of $BUBBLE generated each block, contains 18 decimals. uint256 public emissionPerBlock = 15000000000000000; uint256 internal totalStaked; /// @notice struct per owner address to store: /// a. previously calced rewards, b. number staked, and block since last reward calculation. struct staker { // number of axolittles currently staked uint256 numStaked; // block since calcedReward was last updated uint256 blockSinceLastCalc; // previously calculated rewards uint256 calcedReward; } mapping(address => staker) public stakers; mapping(uint256 => address) public stakedAxos; constructor() {} event Stake(address indexed owner, uint256[] tokenIds); event Unstake(address indexed owner, uint256[] tokenIds); event Claim(address indexed owner, uint256 totalReward); event SetStakingPaused(bool _stakingPaused); event SetPositiveSum(bool _isPositiveSum, uint64 stakeTarget); event AdminTransfer(uint256[] tokenIds); /// @notice Function to stake axos. Transfers axos from sender to this contract. function stake(uint256[] memory tokenIds) external { require(!stakingPaused, "Staking is paused"); require(tokenIds.length > 0, "Nothing to stake"); stakers[msg.sender].calcedReward = _checkRewardInternal(msg.sender); stakers[msg.sender].numStaked += tokenIds.length; stakers[msg.sender].blockSinceLastCalc = block.number; totalStaked += tokenIds.length; for (uint256 i = 0; i < tokenIds.length; i++) { IERC721(AXOLITTLES).transferFrom(msg.sender, address(this), tokenIds[i]); stakedAxos[tokenIds[i]] = msg.sender; } emit Stake(msg.sender, tokenIds); } /// @notice Function to unstake axos. Transfers axos from this contract back to sender address. function unstake(uint256[] memory tokenIds) external { require(tokenIds.length > 0, "Nothing to unstake"); require(tokenIds.length <= stakers[msg.sender].numStaked, "Not your axo!"); stakers[msg.sender].calcedReward = _checkRewardInternal(msg.sender); stakers[msg.sender].numStaked -= tokenIds.length; stakers[msg.sender].blockSinceLastCalc = block.number; totalStaked -= tokenIds.length; for (uint256 i = 0; i < tokenIds.length; i++) { require(msg.sender == stakedAxos[tokenIds[i]], "Not your axo!"); delete stakedAxos[tokenIds[i]]; IERC721(AXOLITTLES).transferFrom(address(this), msg.sender, tokenIds[i]); } emit Unstake(msg.sender, tokenIds); } /// @notice Function to claim $BUBBLE. function claim() external { //todo: ownership and other checks here uint256 totalReward = _checkRewardInternal(msg.sender); require(totalReward > 0, "Nothing to claim"); stakers[msg.sender].blockSinceLastCalc = block.number; stakers[msg.sender].calcedReward = 0; IBubbles(TOKEN).mint(msg.sender, totalReward); emit Claim(msg.sender, totalReward); } /// @notice Function to check rewards per staker address function checkReward(address _staker_address) external view returns (uint256) { return _checkRewardInternal(_staker_address); } /// @notice Internal function to check rewards per staker address function _checkRewardInternal(address _staker_address) internal view returns (uint256) { uint256 totalReward = stakers[_staker_address].calcedReward + stakers[_staker_address].numStaked * emissionPerBlock * (block.number - stakers[_staker_address].blockSinceLastCalc); if (isPositiveSum) { totalReward *= (1 + (totalStaked / stakeTarget)); } return totalReward; } //ADMIN FUNCTIONS /// @notice Function to change address of NFT function setAxolittlesAddress(address _axolittlesAddress) external onlyOwner { AXOLITTLES = _axolittlesAddress; } /// @notice Function to change address of reward token function setTokenAddress(address _tokenAddress) external onlyOwner { TOKEN = _tokenAddress; } /// @notice Function to change amount of $BUBBLE generated each block per axo function setEmissionPerBlock(uint256 _emissionPerBlock) external onlyOwner { emissionPerBlock = _emissionPerBlock; } /// @notice Function to prevent further staking function setStakingPaused(bool _isPaused) external onlyOwner { stakingPaused = _isPaused; emit SetStakingPaused(stakingPaused); } ///@notice Function to turn on positive sum staking function setPositiveSum(bool _isPositiveSum, uint64 _stakeTarget) external onlyOwner { isPositiveSum = _isPositiveSum; stakeTarget = _stakeTarget; emit SetPositiveSum(isPositiveSum, stakeTarget); } /// @notice Function for admin to transfer axos out of contract back to original owner function adminTransfer(uint256[] memory tokenIds) external onlyOwner { require(tokenIds.length > 0, "Nothing to unstake"); totalStaked -= tokenIds.length; for (uint256 i = 0; i < tokenIds.length; i++) { address owner = stakedAxos[tokenIds[i]]; require(owner != address(0), "Axo not found"); stakers[owner].numStaked--; delete stakedAxos[tokenIds[i]]; IERC721(AXOLITTLES).transferFrom(address(this), owner, tokenIds[i]); } emit AdminTransfer(tokenIds); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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 // 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/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // 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 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 // 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; } }
@notice Function to turn on positive sum staking
function setPositiveSum(bool _isPositiveSum, uint64 _stakeTarget) external onlyOwner { isPositiveSum = _isPositiveSum; stakeTarget = _stakeTarget; emit SetPositiveSum(isPositiveSum, stakeTarget); }
1,545,611
[ 1, 2083, 358, 7005, 603, 6895, 2142, 384, 6159, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 14900, 3495, 12, 6430, 389, 291, 14900, 3495, 16, 2254, 1105, 389, 334, 911, 2326, 13, 203, 565, 3903, 203, 565, 1338, 5541, 203, 225, 288, 203, 565, 353, 14900, 3495, 273, 389, 291, 14900, 3495, 31, 203, 565, 384, 911, 2326, 273, 389, 334, 911, 2326, 31, 203, 565, 3626, 1000, 14900, 3495, 12, 291, 14900, 3495, 16, 384, 911, 2326, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "./interfaces/IArtworkStore.sol"; import "./interfaces/ITRLabCore.sol"; import "./base/ERC2981Upgradeable.sol"; import "./lib/LibArtwork.sol"; /// @title Interface of TRLab NFT core contract /// @author Joe /// @notice This is the interface of TRLab NFT core contract contract TRLabCore is ITRLabCore, Initializable, ERC2981Upgradeable, ERC721Upgradeable, ERC721URIStorageUpgradeable, PausableUpgradeable, OwnableUpgradeable, UUPSUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; using SafeERC20Upgradeable for IERC20Upgradeable; using StringsUpgradeable for uint256; // ---------------- params ----------------- /// @dev internal id counter, do not use directly, use _getNextTokenId() CountersUpgradeable.Counter private _tokenIdCounter; /// @dev account address => approved or not mapping(address => bool) public override approvedTokenCreators; /// @dev token id => ArtworkRelease mapping(uint256 => LibArtwork.ArtworkRelease) public tokenIdToArtworkRelease; /// @dev artwork store contract address IArtworkStore public artworkStore; /// @dev reentrancy constants uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; /// @dev reentrancy status uint256 private _status; /// @dev Throws if called by any account other than the owner or approved creator modifier onlyOwnerOrCreator() { require( owner() == _msgSender() || approvedTokenCreators[_msgSender()], "caller is not the owner or approved creator" ); _; } /** * @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; } function initialize( string memory _tokenName, string memory _tokenSymbol, address _storeAddress ) public initializer { __ERC721_init(_tokenName, _tokenSymbol); __ERC2981_init(); __ERC721URIStorage_init(); __Pausable_init(); __Ownable_init(); __UUPSUpgradeable_init(); _status = _NOT_ENTERED; // counter starts from 0, increase to 1 _tokenIdCounter.increment(); setStoreAddress(_storeAddress); } /// @dev get current total supply of NFTs function totalSupply() public view override returns (uint256) { return getNextTokenId() - 1; } /// @dev Set store address. Only called by the owner. function setStoreAddress(address _storeAddress) public override onlyOwner { artworkStore = IArtworkStore(_storeAddress); emit NewArtworkStore(_storeAddress); } /// @inheritdoc ITRLabCore function setTokenRoyalty( uint256 _tokenId, address _receiver, uint256 _bps ) public override onlyOwner { Royalty memory r = Royalty({receiver: _receiver, bps: _bps}); _setRoyalty(_tokenId, r); } /// @dev set the royalty of tokens. Can only be called by owner at emergency /// @param _tokenIds uint256[] the ids of the token /// @param _receiver address the receiver address of the royalty /// @param _bps uint256 the royalty percentage in bps function setTokensRoyalty( uint256[] calldata _tokenIds, address _receiver, uint256 _bps ) public override onlyOwner { Royalty memory r = Royalty({receiver: _receiver, bps: _bps}); for (uint256 idx = 0; idx < _tokenIds.length; idx++) { uint256 id = _tokenIds[idx]; _setRoyalty(id, r); } } /// @dev Set approved creator. Only called by the owner. function setApprovedCreator(address[] calldata creators, bool ok) external onlyOwner { for (uint256 idx = 0; idx < creators.length; idx++) { approvedTokenCreators[creators[idx]] = ok; } } /// @inheritdoc ITRLabCore function getArtwork(uint256 _artworkId) external view override returns (LibArtwork.Artwork memory artwork) { artwork = _getArtwork(_artworkId); } /// @inheritdoc ITRLabCore function createArtwork( uint32 _totalSupply, string calldata _metadataPath, address _royaltyReceiver, uint256 _royaltyBps ) external override whenNotPaused onlyOwnerOrCreator { _createArtwork(_msgSender(), _totalSupply, _metadataPath, _royaltyReceiver, _royaltyBps); } /// @inheritdoc ITRLabCore function createArtworkAndReleases( uint32 _totalSupply, string calldata _metadataPath, uint32 _numReleases, address _royaltyReceiver, uint256 _royaltyBps ) external override whenNotPaused onlyOwnerOrCreator { uint256 artworkId = _createArtwork(_msgSender(), _totalSupply, _metadataPath, _royaltyReceiver, _royaltyBps); _batchArtworkRelease(_msgSender(), artworkId, _numReleases); } /// @inheritdoc ITRLabCore function releaseArtwork(uint256 _artworkId, uint32 _numReleases) external override whenNotPaused onlyOwnerOrCreator { _batchArtworkRelease(_msgSender(), _artworkId, _numReleases); } /// @inheritdoc ITRLabCore function releaseArtworkForReceiver( address _receiver, uint256 _artworkId, uint32 _numReleases ) external override whenNotPaused onlyOwnerOrCreator { _batchArtworkRelease(_receiver, _artworkId, _numReleases); } /// @notice get the next token id, won't change state function getNextTokenId() public view override returns (uint256) { return _tokenIdCounter.current(); } /// @notice burns an artwork, Once this function succeeds, this artwork /// will no longer be able to mint any more tokens. Existing tokens need to be /// burned individually though. /// @param _artworkId the id of the artwork to burn function burnArtwork(uint256 _artworkId) public onlyOwner { _burnArtwork(_artworkId); } /// @dev pause the contract function pause() public onlyOwner { _pause(); } /// @dev unpause the contract function unpause() public onlyOwner { _unpause(); } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public whenNotPaused { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } /// @notice returns ipfs uri of token /// @param tokenId uint256 id of token /// @return the ipfs uri function tokenURI(uint256 tokenId) public view override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); LibArtwork.ArtworkRelease memory artworkRelease = tokenIdToArtworkRelease[tokenId]; uint256 artworkId = artworkRelease.artworkId; uint256 printEdition = artworkRelease.printEdition; LibArtwork.Artwork memory artwork = _getArtwork(artworkId); string memory baseURI = artwork.metadataPath; return _tokenURIHelper(baseURI, printEdition); } function _tokenURIHelper(string memory baseURI, uint256 printEdition) private pure returns (string memory) { return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, printEdition.toString())) : ""; } /** * Creates a new artwork object. Returns the artwork id. */ function _createArtwork( address _creator, uint32 _totalSupply, string calldata _metadataPath, address _royaltyReceiver, uint256 _royaltyBps ) internal returns (uint256) { return artworkStore.createArtwork(_creator, _totalSupply, _metadataPath, _royaltyReceiver, _royaltyBps); } /** * Creates _count number of NFT token for artwork * Bumps up the print index by _count. * @param _nftOwner address the owner of the NFT token * @param _artworkId uint256 the artwork id * @param _count uint256 how many tokens of this batch */ function _batchArtworkRelease( address _nftOwner, uint256 _artworkId, uint32 _count ) internal nonReentrant { // Sanity check of _count number. Negative number will throw overflow exception require(_count < 10000, "Cannot print more than 10K tokens at once"); LibArtwork.Artwork memory _artwork = _getArtwork(_artworkId); // If artwork not exists, its creator is address(0) require(_artwork.creator != address(0), "artwork not exists"); // Get the old print index before increment. uint32 currentPrintIndex = _artwork.printIndex; // Increase print index before mint logic, check if increment valid. Saving gas if count exceeds maxSupply. _incrementArtworkPrintIndex(_artworkId, _count); Royalty memory royalty = Royalty({receiver: _artwork.royaltyReceiver, bps: _artwork.royaltyBps}); for (uint32 i = 0; i < _count; i++) { uint32 newPrintEdition = currentPrintIndex + 1 + i; LibArtwork.ArtworkRelease memory _artworkRelease = LibArtwork.ArtworkRelease({ printEdition: newPrintEdition, artworkId: _artworkId }); uint256 tokenId = _nextTokenId(); tokenIdToArtworkRelease[tokenId] = _artworkRelease; // This will assign ownership and also emit the Transfer event as per ERC721 _safeMint(_nftOwner, tokenId); _setRoyalty(tokenId, royalty); emit ArtworkReleaseCreated( tokenId, _nftOwner, _artworkId, newPrintEdition, _tokenURIHelper(_artwork.metadataPath, newPrintEdition) ); } emit ArtworkPrintIndexUpdated(_artworkId, currentPrintIndex + _count); } function _incrementArtworkPrintIndex(uint256 _artworkId, uint32 _count) internal { artworkStore.incrementArtworkPrintIndex(_artworkId, _count); } // this function changes _tokenIdCounter status function _nextTokenId() internal returns (uint256) { uint256 _nextId = _tokenIdCounter.current(); _tokenIdCounter.increment(); return _nextId; } function _getArtwork(uint256 artworkId) internal view returns (LibArtwork.Artwork memory) { return artworkStore.getArtwork(artworkId); } /** * Burns an artwork. Once this function succeeds, this artwork * will no longer be able to mint any more tokens. Existing tokens need to be * burned individually though. * @param _artworkId the id of the digital media to burn */ function _burnArtwork(uint256 _artworkId) internal { LibArtwork.Artwork memory _artwork = _getArtwork(_artworkId); uint32 increment = _artwork.totalSupply - _artwork.printIndex; _incrementArtworkPrintIndex(_artworkId, increment); emit ArtworkBurned(_artworkId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { super._burn(tokenId); delete tokenIdToArtworkRelease[tokenId]; } function supportsInterface(bytes4 interfaceId) public view override(ERC2981Upgradeable, ERC721Upgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function emergencyWithdrawERC20Tokens( address _tokenAddr, address _to, uint256 _amount ) external onlyOwner { IERC20Upgradeable(_tokenAddr).safeTransfer(_to, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721URIStorage_init_unchained(); } function __ERC721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../lib/LibArtwork.sol"; /// @title Interface for artwork data storage /// @author Joe /// @notice This is the interface for TRLab NFTs artwork data storage. /// @dev Separating artwork storage from the TRLabCore contract decouples features. interface IArtworkStore { /// @notice This event emits when a new artwork has been created. /// @param artworkId uint256 the id of the new artwork /// @param creator address the creator address of the artwork /// @param royaltyReceiver address the receiver address of the artwork second sale royalty /// @param royaltyBps uint256 the royalty percent in bps /// @param totalSupply uint256 the maximum tokens can be minted of this artwork /// @param metadataPath the ipfs path of the artwork metadata event ArtworkCreated( uint256 indexed artworkId, address indexed creator, address indexed royaltyReceiver, uint256 royaltyBps, uint256 totalSupply, string metadataPath ); /// @notice This event emits when artwork print id increases. /// @param artworkId uint256 the id of the new artwork /// @param increment uint32 the increment of artwork print index /// @param newPrintIndex uint32 the new print index of this artwork event ArtworkPrintIndexIncrement(uint256 indexed artworkId, uint32 increment, uint32 newPrintIndex); /// @notice Creates a new digital artwork object in storage /// @param _creator address the address of the creator /// @param _totalSupply uint32 the total allowable prints for this artwork /// @param _metadataPath string the ipfs metadata path /// @param _royaltyReceiver address the royalty receiver /// @param _royaltyBps uint256 the royalty percentage in bps function createArtwork( address _creator, uint32 _totalSupply, string calldata _metadataPath, address _royaltyReceiver, uint256 _royaltyBps ) external returns (uint256); /// @notice Update Artwork Royalty Info, can only be called by owner at emergency /// @param _artworkId id of the artwork /// @param _royaltyReceiver address the royalty receiver /// @param _royaltyBps uint256 the royalty percentage in bps function updateArtworkRoyaltyInfo( uint256 _artworkId, address _royaltyReceiver, uint256 _royaltyBps ) external; /// @notice Update Artwork metadata path (base uri), can only be called by owner at emergency /// @param _artworkId id of the artwork /// @param _metadataPath metadata path (base uri) function updateArtworkMetadataPath(uint256 _artworkId, string memory _metadataPath) external; /// @notice Increments the current print index of the artwork object, can be triggered by mint or burn. /// @param _artworkId uint256 the id of the artwork /// @param _increment uint32 the amount to increment by function incrementArtworkPrintIndex(uint256 _artworkId, uint32 _increment) external; /// Retrieves the artwork object by id /// @param _artworkId uint256 the address of the creator function getArtwork(uint256 _artworkId) external view returns (LibArtwork.Artwork memory artwork); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../lib/LibArtwork.sol"; /// @title Interface of TRLab NFT core contract /// @author Joe /// @notice This is the interface of TRLab NFT core contract interface ITRLabCore { /// @notice This event emits when a new NFT token has been minted. /// @param id uint256 the id of the minted NFT token. /// @param owner address the address of the token owner. /// @param artworkId uint256 the id of the artwork of this token. /// @param printEdition uint32 the print edition of this token. /// @param tokenURI string the metadata ipfs URI. event ArtworkReleaseCreated( uint256 indexed id, address indexed owner, uint256 indexed artworkId, uint32 printEdition, string tokenURI ); /// @notice This event emits when a batch of NFT tokens has been minted. /// @param artworkId uint256 the id of the artwork of this token. /// @param printEdition uint32 the new print edition of this artwork. event ArtworkPrintIndexUpdated(uint256 indexed artworkId, uint32 indexed printEdition); event NewArtworkStore(address indexed storeAddress); /// @notice This event emits when an artwork has been burned. /// @param artworkId uint256 the id of the burned artwork. event ArtworkBurned(uint256 indexed artworkId); /// @dev get current total supply of NFTs function totalSupply() external view returns (uint256); /// @dev sets the artwork store address. /// @param _storeAddress address the address of the artwork store contract. function setStoreAddress(address _storeAddress) external; /// @dev set the royalty of a token. Can only be called by owner at emergency /// @param _tokenId uint256 the id of the token /// @param _receiver address the receiver address of the royalty /// @param _bps uint256 the royalty percentage in bps function setTokenRoyalty( uint256 _tokenId, address _receiver, uint256 _bps ) external; /// @dev set the royalty of tokens. Can only be called by owner at emergency /// @param _tokenIds uint256[] the ids of the token /// @param _receiver address the receiver address of the royalty /// @param _bps uint256 the royalty percentage in bps function setTokensRoyalty( uint256[] calldata _tokenIds, address _receiver, uint256 _bps ) external; /// @notice Retrieves the artwork object by id /// @param _artworkId uint256 the address of the creator /// @return artwork the artwork object function getArtwork(uint256 _artworkId) external view returns (LibArtwork.Artwork memory artwork); /// @notice Creates a new artwork object, artwork creator is _msgSender() /// @param _totalSupply uint32 the total allowable prints for this artwork /// @param _metadataPath string the ipfs metadata path /// @param _royaltyReceiver address the royalty receiver /// @param _royaltyBps uint256 the royalty percentage in bps function createArtwork( uint32 _totalSupply, string calldata _metadataPath, address _royaltyReceiver, uint256 _royaltyBps ) external; /// @notice Creates a new artwork object and mints it's first release token. /// @dev No creations of any kind are allowed when the contract is paused. /// @param _totalSupply uint32 the total allowable prints for this artwork /// @param _metadataPath string the ipfs metadata path /// @param _numReleases uint32 the number of tokens to be minted /// @param _royaltyReceiver address the royalty receiver /// @param _royaltyBps uint256 the royalty percentage in bps function createArtworkAndReleases( uint32 _totalSupply, string calldata _metadataPath, uint32 _numReleases, address _royaltyReceiver, uint256 _royaltyBps ) external; /// @notice mints tokens of artwork. /// @dev No creations of any kind are allowed when the contract is paused. /// @param _artworkId uint256 the id of the artwork /// @param _numReleases uint32 the number of tokens to be minted function releaseArtwork(uint256 _artworkId, uint32 _numReleases) external; /// @notice mints tokens of artwork in behave of receiver. Designed for buy-now contract. /// @dev No creations of any kind are allowed when the contract is paused. /// @param _receiver address the owner of the new nft token. /// @param _artworkId uint256 the id of the artwork. /// @param _numReleases uint32 the number of tokens to be minted. function releaseArtworkForReceiver( address _receiver, uint256 _artworkId, uint32 _numReleases ) external; /// @notice get the next token id /// @return the last token id function getNextTokenId() external view returns (uint256); /// @dev getter function for approvedTokenCreators mapping. Check if caller is approved creator. /// @param caller address the address of caller to check. /// @return true if caller is approved creator, otherwise false. function approvedTokenCreators(address caller) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "../interfaces/IERC2981Upgradeable.sol"; contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable { event RoyaltySet(uint256 indexed tokenId, Royalty royalty); // bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; struct Royalty { address receiver; uint256 bps; } // token id -> royalty mapping(uint256 => Royalty) public royaltyMap; function __ERC2981_init() internal initializer { __ERC165_init_unchained(); __ERC2981_init_unchained(); } function __ERC2981_init_unchained() internal initializer {} /// @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 override returns (address receiver, uint256 royaltyAmount) { Royalty memory royalty = royaltyMap[_tokenId]; receiver = royalty.receiver; royaltyAmount = (_salePrice * royalty.bps) / 10000; } function _setRoyalty(uint256 _id, Royalty memory _royalty) internal { // require(_royalty.account != address(0), "Recipient should be present"); require(_royalty.bps <= 10000, "Royalty bps should less than 10000"); royaltyMap[_id] = _royalty; emit RoyaltySet(_id, _royalty); } /** * @dev See {IERC165-supportsInterface}. * * 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); */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC2981Upgradeable, ERC165Upgradeable) returns (bool) { return interfaceId == type(IERC2981Upgradeable).interfaceId || interfaceId == _INTERFACE_ID_ERC2981 || super.supportsInterface(interfaceId); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library LibArtwork { struct Artwork { address creator; uint32 printIndex; uint32 totalSupply; string metadataPath; address royaltyReceiver; uint256 royaltyBps; // royaltyBps is a value between 0 to 10000 } struct ArtworkRelease { // The unique edition number of this artwork release uint32 printEdition; // Reference ID to the artwork metadata uint256 artworkId; } struct ArtworkOnSaleInfo { address takeTokenAddress; // only accept erc20, should use WETH uint256 takeAmount; uint256 startTime; // timestamp in seconds uint256 endTime; uint256 purchaseLimit; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /* * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /// /// @dev Interface for the NFT Royalty Standard /// interface IERC2981Upgradeable is IERC165Upgradeable { /// 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); /// @notice Informs callers that this contract supports ERC2981 /// @dev If `_registerInterface(_INTERFACE_ID_ERC2981)` is called /// in the initializer, this should be automatic /// @param interfaceID The interface identifier, as specified in ERC-165 /// @return `true` if the contract implements /// `_INTERFACE_ID_ERC2981` and `false` otherwise function supportsInterface(bytes4 interfaceID) external view override returns (bool); }
@notice get the next token id, won't change state
function getNextTokenId() public view override returns (uint256) { return _tokenIdCounter.current(); }
1,574,249
[ 1, 588, 326, 1024, 1147, 612, 16, 8462, 1404, 2549, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 22616, 548, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 2316, 548, 4789, 18, 2972, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x3cB6DF9845Af79Ab7c2af9530da0b046bacb6cF9/sources/ERC20TokenSwapper.sol
separately tracks corresponding swap states
mapping(address => mapping(uint256 => States)) swapStates;
8,874,105
[ 1, 16627, 5173, 13933, 4656, 7720, 5493, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 11890, 5034, 516, 29577, 3719, 7720, 7629, 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 ]
pragma solidity ^0.5.0; /** * Shout out to CryptoByte721 */ /** * @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; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping(address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ 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; } /* * @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; } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor() internal { _addMinter(_msgSender()); } modifier onlyMinter() { require( isMinter(_msgSender()), "MinterRole: caller does not have the Minter role" ); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @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); } /** * @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); } /** * @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); } /** * @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; } } /** * @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 { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ECGems is Context, ERC165, IERC721, IERC721Enumerable, IERC721Metadata, MinterRole { 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; // 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 ID, used for enumeration uint256[] private _allTokens; // Mapping from token ID to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Price to mint a new token uint256 private _mintPrice = 0.0001 ether; // Mapping from token ID to its price mapping(uint256 => uint256) private _tokenPrices; /* * 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; /* * 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; /* * 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 Checks if function caller is either minter or has paid the price for minting a token. */ modifier paidMintPrice() { require( msg.value == _mintPrice || isMinter(_msgSender()), "ERC721: caller is not minter nor has paid the minting price" ); _; } /** * @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); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @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 Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external view returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Returns the price needed for minting a token (if caller isn't minter). */ function getMintPrice() public view returns (uint256) { return _mintPrice; } /** * @dev Minters can change the price for minting a token. */ function setMintPrice(uint256 newMintPrice) public onlyMinter { _mintPrice = newMintPrice; } /** * @dev Returns the price for a specific token. */ function getTokenPrice(uint256 tokenId) public view returns (uint256) { return _tokenPrices[tokenId]; } /** * @dev Sets the price for token ID. * Setting the price to 0 removes the token from sale, * otherwise it puts it up for sale. * @param tokenId ID of token to change price for * @param newPrice new price to be assigned */ function setTokenPrice(uint256 tokenId, uint256 newPrice) public { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not owner nor approved" ); _tokenPrices[tokenId] = newPrice; } /** * @dev Transfers token from owner to buyer. * Ether sent to function must be equal to price assigned for token. * Sends ether to previous owner of token. * Resets the token price. * @param tokenId ID of token to be bought */ function buyToken(uint256 tokenId) public payable { uint256 tokenPrice = getTokenPrice(tokenId); require(tokenPrice > 0, "ERC721: token not for sale"); address owner = ownerOf(tokenId); require( _msgSender() != owner, "ERC721: can't buy already owned tokens" ); require( msg.value == tokenPrice, "ERC721: paid price doesn't equal needed price" ); _safeTransferFrom(owner, _msgSender(), tokenId, ""); address(uint160(owner)).transfer(tokenPrice); } /** * @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 { 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 Function to mint tokens. * @param to The address that will receive the minted token. * @return A boolean that indicates if the operation was successful. */ function mint(address to) public payable paidMintPrice returns (bool) { _mint(to); return true; } function setTokenURI(uint256 tokenId, string memory uri) public onlyMinter { _setTokenURI(tokenId, uri); } /** * @dev Function to safely mint tokens. * @param to The address that will receive the minted token. * @return A boolean that indicates if the operation was successful. */ function safeMint(address to) public payable paidMintPrice returns (bool) { _safeMint(to); return true; } /** * @dev Function to safely mint tokens. * @param to The address that will receive the minted token. * @param _data bytes data to send along with a safe transfer check. * @return A boolean that indicates if the operation was successful. */ function safeMint(address to, bytes memory _data) public payable paidMintPrice returns (bool) { _safeMint(to, _data); return true; } /** * @dev After someone pays for minting tokens, ETH is in the contract. * With this function any minter can withdraw this ETH to preffered address. * @param to address to withdraw ETH to */ function withdraw(address payable to) public onlyMinter { to.transfer(address(this).balance); } /** * @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 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 */ function _safeMint(address to) internal { _safeMint(to, ""); } /** * @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 _data bytes data to send along with a safe transfer check */ function _safeMint(address to, bytes memory _data) internal { uint256 tokenId = _mint(to); 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 */ function _mint(address to) internal returns (uint256) { uint256 tokenId = totalSupply() + 1; require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); emit Transfer(address(0), to, tokenId); return 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); _tokenPrices[tokenId] = 0; _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); emit Transfer(from, to, 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) public view returns (uint256[] memory) { 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 (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; } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require( _exists(tokenId), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } function setBaseURI(string memory baseURI) public onlyMinter { _setBaseURI(baseURI); } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseURI) internal { _baseURI = baseURI; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. * * _Available since v2.5.0._ */ function baseURI() external view returns (string memory) { return _baseURI; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call( abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ) ); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
* @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); _tokenPrices[tokenId] = 0; _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); emit Transfer(from, to, tokenId); }
6,514,027
[ 1, 3061, 445, 358, 7412, 23178, 434, 279, 864, 1147, 1599, 358, 4042, 1758, 18, 2970, 1061, 7423, 358, 288, 13866, 1265, 5779, 333, 709, 10522, 1158, 17499, 603, 1234, 18, 15330, 18, 225, 628, 783, 3410, 434, 326, 1147, 225, 358, 1758, 358, 6798, 326, 23178, 434, 326, 864, 1147, 1599, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 906, 4193, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 288, 203, 3639, 2583, 12, 203, 5411, 3410, 951, 12, 2316, 548, 13, 422, 628, 16, 203, 5411, 315, 654, 39, 27, 5340, 30, 7412, 434, 1147, 716, 353, 486, 4953, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 8507, 23461, 12, 2316, 548, 1769, 203, 3639, 389, 2316, 31862, 63, 2316, 548, 65, 273, 374, 31, 203, 203, 3639, 389, 995, 329, 5157, 1380, 63, 2080, 8009, 323, 3702, 5621, 203, 3639, 389, 995, 329, 5157, 1380, 63, 869, 8009, 15016, 5621, 203, 203, 3639, 389, 2316, 5541, 63, 2316, 548, 65, 273, 358, 31, 203, 203, 3639, 389, 4479, 1345, 1265, 5541, 21847, 12, 2080, 16, 1147, 548, 1769, 203, 3639, 389, 1289, 1345, 774, 5541, 21847, 12, 869, 16, 1147, 548, 1769, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.4.1 https://hardhat.org // File contracts/interfaces/IQUAI_Vault.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; interface IQUAI_Vault { function token() external view returns(address); function min() external view returns(uint256); function max() external view returns(uint256); function controller() external view returns(address); function blockLock(address) external view returns(uint256); function governance() external view returns(address); function strategist() external view returns(address); function keeper() external view returns(address); function getPricePerFullShare() external view returns (uint256); function balance() external view returns (uint256); function available() external view returns (uint256); function deposit(uint256 _amount) external; function depositFor(address recipient, uint256 _amount) external; function depositAll() external; function withdraw(uint256 _shares) external; function withdrawAll() external; function setMin(uint256 _min) external; function setController(address _controller) external; function harvest(address reserve, uint256 amount) external; function earn() external; function trackFullPricePerShare() external; } // File contracts/interfaces/IQUAI_Controller.sol pragma solidity >=0.5.0; interface IQUAI_Controller { function governance() external view returns(address); function strategist() external view returns(address); function keeper() external view returns(address); function onesplit() external view returns(address); function rewards() external view returns(address); function vaults(address) external view returns(address); function strategies(address) external view returns(address); function converters(address, address) external view returns(address); function approvedStrategies(address, address) external view returns(bool); function split() external view returns(uint256); function max() external view returns(uint256); function balanceOf(address _token) external view returns(uint256 strategyBalance); function getExpectedReturn( address _strategy, address _token, uint256 parts ) external view returns (uint256 expected); function approveStrategy(address _token, address _strategy) external; function revokeStrategy(address _token, address _strategy) external; function setRewards(address _rewards) external; function setSplit(uint256 _split) external; function setOneSplit(address _onesplit) external; function setVault(address _token, address _vault) external; function setStrategy(address _token, address _strategy) external; function setConverter( address _input, address _output, address _converter ) external; function withdrawAll(address _token) external; function inCaseTokensGetStuck(address _token, uint256 _amount) external; function inCaseStrategyTokenGetStuck(address _strategy, address _token) external; function earn(address _token, uint256 _amount) external; function withdraw(address _token, uint256 _amount) external; } // File contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { function token0() external pure returns (address); function token1() external pure returns (address); function balanceOf(address user) external view returns (uint256); function totalSupply() external view returns (uint256); function getReserves() external view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File contracts/interfaces/ICurveGaugeController.sol pragma solidity >=0.5.0; interface ICurveGaugeController { function get_gauge_weight(address addr) external view returns (uint256); function get_total_weight() external view returns (uint256); function gauge_relative_weight(address addr) external view returns (uint256); } // File contracts/interfaces/ICurveSwap.sol pragma solidity >=0.5.0; interface ICurveSwap { function coins(int128 arg0) external view returns (address); function underlying_coins(int128 arg0) external view returns (address); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function add_liquidity( uint256[4] calldata amounts, uint256 min_mint_amount, bool addUnderlying ) external; function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount, bool addUnderlying ) external; function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount, bool addUnderlying ) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount, bool removeUnderlying ) external; function calc_withdraw_one_coin(uint256 tokenAmount, int128 index) external view returns (uint256); } // File contracts/utils/Context.sol pragma solidity >=0.5.0 <0.9.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. */ contract Context { function _msgSender() internal view returns (address) { return msg.sender; } function _msgData() internal view returns (bytes memory) { return msg.data; } } // File contracts/utils/Ownable.sol pragma solidity >=0.5.0 <0.9.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be 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() public { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/upgrades/MathUpgradeable.sol pragma solidity =0.6.12; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File contracts/interfaces/ISushiChef.sol pragma solidity >=0.5.0; interface ISushiChef { // ===== Write ===== function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function updatePool(uint256 _pid) external; // ===== Read ===== function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); function owner() external view returns (address); function poolInfo(uint256 _pid) external view returns ( address, uint256, uint256, uint256 ); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); function sushiPerBlock() external view returns (uint256); } // File contracts/interfaces/IxSushi.sol pragma solidity >=0.5.0; interface IxSushi { function enter(uint256 _amount) external; function leave(uint256 _shares) external; } // File contracts/interfaces/IERC20Upgradeable.sol pragma solidity >=0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/IERC20Detailed.sol pragma solidity >=0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Detailed { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/ICurveFi.sol pragma solidity >=0.5.0; interface ICurveFi { function get_virtual_price() external returns (uint256 out); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function get_dy( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function remove_liquidity( uint256 _amount, uint256 deadline, uint256[2] calldata min_amounts ) external; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 deadline ) external; function remove_liquidity_imbalance( uint256[3] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function commit_new_parameters( int128 amplification, int128 new_fee, int128 new_admin_fee ) external; function apply_new_parameters() external; function revert_new_parameters() external; function commit_transfer_ownership(address _owner) external; function apply_transfer_ownership() external; function revert_transfer_ownership() external; function withdraw_admin_fees() external; function coins(int128 arg0) external returns (address out); function underlying_coins(int128 arg0) external returns (address out); function balances(int128 arg0) external returns (uint256 out); function A() external returns (int128 out); function fee() external returns (int128 out); function admin_fee() external returns (int128 out); function owner() external returns (address out); function admin_actions_deadline() external returns (uint256 out); function transfer_ownership_deadline() external returns (uint256 out); function future_A() external returns (int128 out); function future_fee() external returns (int128 out); function future_admin_fee() external returns (int128 out); function future_owner() external returns (address out); } // File contracts/interfaces/ICurveGauge.sol pragma solidity >=0.5.0; interface ICurveGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address addr) external; function balanceOf(address arg0) external view returns (uint256); function withdraw(uint256 _value) external; function withdraw(uint256 _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function claimable_tokens(address addr) external returns (uint256); function claimable_reward(address addr) external view returns (uint256); function integrate_fraction(address arg0) external view returns (uint256); function working_balances(address arg0) external view returns (uint256); function working_supply() external view returns (uint256); } // File contracts/interfaces/IUniswapRouterV2.sol pragma solidity >=0.5.0; interface IUniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // File contracts/interfaces/IMintr.sol pragma solidity >=0.5.0; interface IMintr { function mint(address) external; } // File contracts/interfaces/IConverter.sol pragma solidity >=0.5.0; interface IConverter { function convert(address) external returns (uint256); } // File contracts/interfaces/IOneSplitAudit.sol pragma solidity >=0.5.0; interface IOneSplitAudit { function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags ) external payable returns (uint256 returnAmount); function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns (uint256 returnAmount, uint256[] memory distribution); } // File contracts/interfaces/IController.sol pragma solidity >=0.5.0; interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // File contracts/interfaces/IStrategy.sol pragma solidity >=0.5.0; interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address) external returns (uint256 balance); // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function getName() external pure returns (string memory); function setStrategist(address _strategist) external; function setWithdrawalFee(uint256 _withdrawalFee) external; function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external; function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external; function setGovernance(address _governance) external; function setController(address _controller) external; } // File contracts/upgrades/SafeMathUpgradeable.sol pragma solidity =0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/upgrades/AddressUpgradeable.sol pragma solidity =0.6.12; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/upgrades/SafeERC20Upgradeable.sol pragma solidity =0.6.12; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/upgrades/Initializable.sol pragma solidity =0.6.12; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File contracts/upgrades/ContextUpgradeable.sol pragma solidity =0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File contracts/upgrades/ERC20Upgradeable.sol pragma solidity =0.6.12; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // File contracts/upgrades/OwnableUpgradeable.sol pragma solidity =0.6.12; /** * @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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File contracts/upgrades/PausableUpgradeable.sol pragma solidity =0.6.12; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File contracts/QuaiAccessControl.sol pragma solidity =0.6.12; /* Common base for permissioned roles throughout QUAI ecosystem */ contract QuaiAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist"); } function _onlyAuthorizedActors() internal view { require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance, "onlyAuthorizedActors"); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // File contracts/QuaiAccessControlDefended.sol pragma solidity =0.6.12; /* Add ability to prevent unwanted contract access to Vault permissions */ contract QuaiAccessControlDefended is QuaiAccessControl { mapping (address => bool) public approved; function approveContractAccess(address account) external { _onlyGovernance(); approved[account] = true; } function revokeContractAccess(address account) external { _onlyGovernance(); approved[account] = false; } function _defend() internal view returns (bool) { require(approved[msg.sender] || msg.sender == tx.origin, "Access denied for caller"); } uint256[50] private __gap; } // File contracts/BaseStrategy.sol pragma solidity =0.6.12; abstract contract BaseStrategy is PausableUpgradeable, QuaiAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token 0x49849C98ae39Fff122806C06791Fa73784FB3675 uint256 public performanceFeeGovernance; //1000 uint256 public performanceFeeStrategist; //1000 uint256 public withdrawalFee; //50 uint256 public constant MAX_FEE = 10000; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public controller; address public guardian; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController" ); } function _onlyAuthorizedPausers() internal view { require(msg.sender == guardian || msg.sender == strategist || msg.sender == governance, "onlyPausers"); } /// ===== View Functions ===== /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public virtual view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public virtual pure returns (bool) { return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Withdraw all funds, normally used when migrating strategies function withdrawAll() external virtual whenNotPaused returns (uint256) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); uint256 _balance = IERC20Upgradeable(want).balanceOf(address(this)); // Withdraw some from activities if idle want is not sufficient to cover withdrawal if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_amount); // Transfer remaining to Vault to handle withdrawal _transferToVault(_amount.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyAuthorizedPausers(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn( uint256 balance, address[] memory path ) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity( token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp ); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _want) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external view virtual returns (address[] memory); /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external virtual pure returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public virtual view returns (uint256); uint256[50] private __gap; } // File contracts/StrategySushiLpOptimizer.sol pragma solidity =0.6.12; /* Optimize Sushi rewards for arbitrary Sushi LP pair */ contract StrategySushiLpOptimizer is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; // WBTC Token address public constant sushi = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; // SUSHI token address public constant xsushi = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI token address public constant sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; //SUSHI router address public constant chef = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; // Master staking contract address public token0; //first half of LP token address public token1; //second half of LP token address[] public pathRewardToToken0; //sushi to first half of LP token address[] public pathRewardToToken1; //sushi to second half of LP token uint256 public pid; event SushiHarvest( uint256 xSushiHarvested, uint256 totalxSushi, uint256 lpComponentDeposited, uint256 toStrategist, uint256 toGovernance, uint256 timestamp, uint256 blockNumber ); struct HarvestData { uint256 xSushiHarvested; uint256 totalxSushi; uint256 lpComponentDeposited; uint256 toStrategist; uint256 toGovernance; uint256 timestamp; uint256 blockNumber; } struct TendData { uint256 sushiTended; } event WithdrawState(uint256 toWithdraw, uint256 preWant, uint256 postWant, uint256 withdrawn); //_want = LP token //_pathRewardToToken0 = sushi to first half of LP token //_pathRewardToToken1 = sushi to second half of LP token function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address _want, uint256 _pid, uint256[3] memory _feeConfig, address[] memory _pathRewardToToken0, address[] memory _pathRewardToToken1 ) public initializer whenNotPaused { __BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian); want = _want; pid = _pid; // LP token pool ID performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; pathRewardToToken0 = _pathRewardToToken0; pathRewardToToken1 = _pathRewardToToken1; token0 = _pathRewardToToken0[_pathRewardToToken0.length - 1]; token1 = _pathRewardToToken1[_pathRewardToToken1.length - 1]; // Approve Chef and xSushi (aka SushiBar) to use our sushi IERC20Upgradeable(want).approve(chef, uint256(-1)); IERC20Upgradeable(sushi).approve(xsushi, uint256(-1)); // Approve sushi router to transfer token0 and token1 IERC20Upgradeable(token0).approve(sushiRouter, uint256(-1)); IERC20Upgradeable(token1).approve(sushiRouter, uint256(-1)); } /// ===== View Functions ===== function version() external pure returns (string memory) { return "1.1"; } function getName() external pure override returns (string memory) { return "StrategySushiLpOptimizer"; } function balanceOfPool() public view override returns (uint256) { (uint256 staked, ) = ISushiChef(chef).userInfo(pid, address(this)); return staked; } function getProtectedTokens() external view override returns (address[] memory) { address[] memory protectedTokens = new address[](3); protectedTokens[0] = want; protectedTokens[1] = sushi; protectedTokens[2] = xsushi; return protectedTokens; } function isTendable() public pure override returns (bool) { return true; } /// ===== Internal Core Implementations ===== function _onlyNotProtectedTokens(address _asset) internal override { require(address(want) != _asset, "want"); require(address(sushi) != _asset, "sushi"); require(address(xsushi) != _asset, "xsushi"); } /// @dev Deposit Badger into the staking contract /// @dev Track balance in the StakingRewards function _deposit(uint256 _want) internal override { // Deposit all want in sushi chef ISushiChef(chef).deposit(pid, _want); } /// @dev Unroll from all strategy positions, and transfer non-core tokens to controller rewards function _withdrawAll() internal override { (uint256 staked, ) = ISushiChef(chef).userInfo(pid, address(this)); // Withdraw all want from Chef ISushiChef(chef).withdraw(pid, staked); // === Transfer extra token: Sushi === // Withdraw all sushi from SushiBar uint256 _xsushi = IERC20Upgradeable(xsushi).balanceOf(address(this)); IxSushi(xsushi).leave(_xsushi); uint256 _sushi = IERC20Upgradeable(sushi).balanceOf(address(this)); // Send all Sushi to controller rewards IERC20Upgradeable(sushi).safeTransfer(IController(controller).rewards(), _sushi); // Note: All want is automatically withdrawn outside this "inner hook" in base strategy function } /// @dev Withdraw want from staking rewards, using earnings first function _withdrawSome(uint256 _amount) internal override returns (uint256) { // Get idle want in the strategy uint256 _preWant = IERC20Upgradeable(want).balanceOf(address(this)); // If we lack sufficient idle want, withdraw the difference from the strategy position if (_preWant < _amount) { uint256 _toWithdraw = _amount.sub(_preWant); ISushiChef(chef).withdraw(pid, _toWithdraw); // Note: Withdrawl process will earn sushi, this will be deposited into SushiBar on next tend() } // Confirm how much want we actually end up with uint256 _postWant = IERC20Upgradeable(want).balanceOf(address(this)); // Return the actual amount withdrawn if less than requested uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount); emit WithdrawState(_amount, _preWant, _postWant, _withdrawn); return _withdrawn; } /// @notice Harvest sushi gains from Chef and deposit into SushiBar (xSushi) to increase gains /// @notice Any excess Sushi sitting in the Strategy will be staked as well /// @notice The more frequent the tend, the higher returns will be function tend() external whenNotPaused returns (TendData memory) { _onlyAuthorizedActors(); TendData memory tendData; // Note: Deposit of zero harvests rewards balance. ISushiChef(chef).deposit(pid, 0); tendData.sushiTended = IERC20Upgradeable(sushi).balanceOf(address(this)); // Stake any harvested sushi in SushiBar to increase returns if (tendData.sushiTended > 0) { IxSushi(xsushi).enter(tendData.sushiTended); } emit Tend(tendData.sushiTended); return tendData; } /// @dev Harvest accumulated sushi from SushiChef and SushiBar and send to rewards tree for distribution. Take performance fees on gains /// @dev The less frequent the harvest, the higher the gains due to compounding function harvest() external whenNotPaused returns (HarvestData memory) { _onlyAuthorizedActors(); HarvestData memory harvestData; uint256 _beforexSushi = IERC20Upgradeable(xsushi).balanceOf(address(this)); uint256 _beforeLp = IERC20Upgradeable(want).balanceOf(address(this)); // == Harvest sushi rewards from Chef == // Note: Deposit of zero harvests rewards balance, but go ahead and deposit idle want if we have it ISushiChef(chef).deposit(pid, _beforeLp); // Put all sushi into xsushi uint256 _sushi = IERC20Upgradeable(sushi).balanceOf(address(this)); if (_sushi > 0) { IxSushi(xsushi).enter(_sushi); } uint256 _xsushi = IERC20Upgradeable(xsushi).balanceOf(address(this)); //all xsushi is profit harvestData.totalxSushi = _xsushi; //harvested is the xsushi gain since last tend harvestData.xSushiHarvested = _xsushi.sub(_beforexSushi); // Process performance fees //performance fees in xsushi harvestData.toStrategist = _processFee(xsushi, harvestData.totalxSushi, performanceFeeStrategist, strategist); harvestData.toGovernance = _processFee(xsushi, harvestData.totalxSushi, performanceFeeGovernance, IController(controller).rewards()); // Turn remaining xsushi back into sushi uint256 _xsushiAfterFees = IERC20Upgradeable(xsushi).balanceOf(address(this)); if (_xsushiAfterFees > 0) { IxSushi(xsushi).leave(_xsushiAfterFees); } uint256 _sushiAfterFees = IERC20Upgradeable(sushi).balanceOf(address(this)); uint256 _want; // Swap remaining sushi into more want if (_sushiAfterFees > 0) { _want = _swapToWant(_sushiAfterFees); } harvestData.lpComponentDeposited = _want; // Deposit any new want into Chef if (_want > 0) { ISushiChef(chef).deposit(pid, _want); } emit SushiHarvest( harvestData.xSushiHarvested, harvestData.totalxSushi, harvestData.lpComponentDeposited, harvestData.toStrategist, harvestData.toGovernance, block.timestamp, block.number ); emit Harvest(_want, block.number); return harvestData; } function _swapToWant(uint256 sushiIn) internal returns(uint256) { uint256 amountIn = (sushiIn / 2); // swap to token0 uint256 amountOutToken0 = amountIn; if (pathRewardToToken0.length != 1) { uint256[] memory amountsOutToken0 = IUniswapRouterV2(sushiRouter).getAmountsOut(amountIn, pathRewardToToken0); amountOutToken0 = amountsOutToken0[amountsOutToken0.length - 1]; IUniswapRouterV2(sushiRouter).swapExactTokensForTokens(amountIn, amountOutToken0, pathRewardToToken0, address(this), block.timestamp); } // swap to token1 uint256 amountOutToken1 = amountIn; if (pathRewardToToken1.length != 1) { uint256[] memory amountsOutToken1 = IUniswapRouterV2(sushiRouter).getAmountsOut(amountIn, pathRewardToToken1); amountOutToken1 = amountsOutToken1[amountsOutToken1.length - 1]; IUniswapRouterV2(sushiRouter).swapExactTokensForTokens(amountIn, amountOutToken1, pathRewardToToken1, address(this), block.timestamp); } (,,uint256 liquidity) = IUniswapRouterV2(sushiRouter).addLiquidity( token0, token1, amountOutToken0, amountOutToken1, 0, 0, address(this), block.timestamp ); return liquidity; } } // File contracts/StrategyCurveGaugeBase.sol pragma solidity =0.6.12; contract StrategyCurveGaugeBase is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address public gauge; // Curve renBtc Gauge address public mintr; // Curve CRV Minter address public curveSwap; // Curve renBtc Swap address public lpComponent; // renBTC for renCrv and sCrv address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // CRV token address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Weth Token, used for crv <> weth <> wbtc route address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; // Wbtc Token address public constant renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // renBTC token uint256 public keepCRV; event CurveHarvest( uint256 crvHarvested, uint256 keepCrv, uint256 crvRecycled, uint256 lpComponentDeposited, uint256 wantProcessed, uint256 wantDeposited, uint256 governancePerformanceFee, uint256 strategistPerformanceFee ); struct HarvestData { uint256 crvHarvested; uint256 keepCrv; uint256 crvRecycled; uint256 lpComponentDeposited; uint256 wantProcessed; uint256 wantDeposited; uint256 governancePerformanceFee; uint256 strategistPerformanceFee; } function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[5] memory _wantConfig, uint256[4] memory _feeConfig ) public initializer { __BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian); want = _wantConfig[0]; gauge = _wantConfig[1]; mintr = _wantConfig[2]; curveSwap = _wantConfig[3]; lpComponent = _wantConfig[4]; performanceFeeGovernance = _feeConfig[0]; //1000 performanceFeeStrategist = _feeConfig[1]; //1000 withdrawalFee = _feeConfig[2]; //50 keepCRV = _feeConfig[3]; // 0 IERC20Upgradeable(want).safeApprove(gauge, type(uint256).max); } /// ===== View Functions ===== function getName() external override pure returns (string memory) { return "StrategyCurveGauge"; } function balanceOfPool() public override view returns (uint256) { return ICurveGauge(gauge).balanceOf(address(this)); } function getProtectedTokens() external view override returns (address[] memory) { address[] memory protectedTokens = new address[](3); protectedTokens[0] = want; protectedTokens[1] = lpComponent; protectedTokens[2] = crv; return protectedTokens; } /// ===== Permissioned Actions: Governance ===== function setKeepCRV(uint256 _keepCRV) external { _onlyGovernance(); keepCRV = _keepCRV; } /// ===== Internal Core Implementations ===== function _onlyNotProtectedTokens(address _asset) internal override { require(address(want) != _asset, "want"); require(lpComponent != _asset, "lpComponent"); require(crv != _asset, "crv"); } function _deposit(uint256 _want) internal override { ICurveGauge(gauge).deposit(_want); } function _withdrawAll() internal override { ICurveGauge(gauge).withdraw(ICurveGauge(gauge).balanceOf(address(this))); } function _withdrawSome(uint256 _amount) internal override returns (uint256) { ICurveGauge(gauge).withdraw(_amount); return _amount; } /// @notice Harvest from strategy mechanics, realizing increase in underlying position function harvest() external whenNotPaused returns (HarvestData memory) { _onlyAuthorizedActors(); HarvestData memory harvestData; uint256 _before = IERC20Upgradeable(want).balanceOf(address(this)); uint256 _beforeCrv = IERC20Upgradeable(crv).balanceOf(address(this)); // Harvest from Gauge IMintr(mintr).mint(address(gauge)); uint256 _afterCrv = IERC20Upgradeable(crv).balanceOf(address(this)); harvestData.crvHarvested = _afterCrv.sub(_beforeCrv); uint256 _crv = _afterCrv; // Transfer CRV to keep to Rewards harvestData.keepCrv = _crv.mul(keepCRV).div(MAX_FEE); if (harvestData.keepCrv > 0) { IERC20Upgradeable(crv).safeTransfer(IController(controller).rewards(), harvestData.keepCrv); } harvestData.crvRecycled = _crv.sub(harvestData.keepCrv); // Convert remaining CRV to lpComponent if (harvestData.crvRecycled > 0) { address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = lpComponent; _swap(crv, harvestData.crvRecycled, path); } // Deposit into Curve to increase LP position harvestData.lpComponentDeposited = IERC20Upgradeable(lpComponent).balanceOf(address(this)); if (harvestData.lpComponentDeposited > 0) { _safeApproveHelper(lpComponent, curveSwap, harvestData.lpComponentDeposited); _add_liquidity_curve(harvestData.lpComponentDeposited); } // Take fees from want increase and deposit remaining into Gauge harvestData.wantProcessed = (IERC20Upgradeable(want).balanceOf(address(this))).sub(_before); if (harvestData.wantProcessed > 0) { harvestData.governancePerformanceFee = _processFee( want, harvestData.wantProcessed, performanceFeeGovernance, IController(controller).rewards() ); harvestData.strategistPerformanceFee = _processFee(want, harvestData.wantProcessed, performanceFeeStrategist, strategist); harvestData.wantDeposited = IERC20Upgradeable(want).balanceOf(address(this)); if (harvestData.wantDeposited > 0) { _deposit(harvestData.wantDeposited); } } emit CurveHarvest( harvestData.crvHarvested, harvestData.keepCrv, harvestData.crvRecycled, harvestData.lpComponentDeposited, harvestData.wantProcessed, harvestData.wantDeposited, harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee ); emit Harvest(harvestData.wantProcessed, block.number); } /// ===== Internal Helper Functions ===== /// @dev Handle the particular function variant for CurveSwap function _add_liquidity_curve(uint256 _amount) internal virtual { // e.g. ICurveFi(curveSwap).add_liquidity([0, _amount, 0], 0); } } pragma solidity ^0.6.12; contract APY_Helper is Ownable { address public constant sushi = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; address public constant chef = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; address public constant sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant curve = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant curveGaugeController = 0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB; address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public quai_controller; //using historical average of 13.2 seconds/block //365*24*60*60/13.2 = 2389091 uint256 public constant blocksPerYear = 2389091; constructor(address _quai_controller) public { setQUAI_Controller(_quai_controller); } function setQUAI_Controller(address _quai_controller) public onlyOwner { quai_controller = _quai_controller; } function getTotalInvested(address vault) public view returns(uint256) { return IQUAI_Vault(vault).balance(); } function getYearlySushiRewards(address strategy) public view returns(uint256) { uint256 pid = StrategySushiLpOptimizer(strategy).pid(); (uint256 lpDeposited, ) = ISushiChef(chef).userInfo(pid, strategy); uint256 sushiPerBlock = ISushiChef(chef).sushiPerBlock(); uint256 totalAllocPoint = ISushiChef(chef).totalAllocPoint(); (address lpToken, uint256 poolAllocPoint, , ) = ISushiChef(chef).poolInfo(pid); uint256 lpInChef = IERC20Upgradeable(lpToken).balanceOf(chef); uint256 sushiRewardsPerYear = (sushiPerBlock * blocksPerYear * poolAllocPoint * lpDeposited) / (totalAllocPoint * lpInChef); return sushiRewardsPerYear; } //price of 1e18 sushi in WETH function getSushiPriceInWeth() public view returns(uint256) { address[] memory path = new address[](2); path[0] = sushi; path[1] = WETH; uint256[] memory amountsOut = IUniswapRouterV2(sushiRouter).getAmountsOut(1e18, path); uint256 wethOut = amountsOut[amountsOut.length - 1]; return wethOut; } //price of 1e18 SLP in WETH function getSLPPriceInWeth(address lpToken) public view returns(uint256) { address token0 = IUniswapV2Pair(lpToken).token0(); uint256 totalLP = IUniswapV2Pair(lpToken).totalSupply(); uint256 totalToken0 = IERC20Upgradeable(token0).balanceOf(lpToken); //use 1e6 here instead of 1e18 in case one of the underlying tokens has low number of decimals uint256 token0PerLP = (totalToken0 * 1e6) / totalLP; uint256 wethOut; if(token0 == WETH) { wethOut = token0PerLP; } else { address[] memory path = new address[](2); path[0] = token0; path[1] = WETH; uint256[] memory amountsOut = IUniswapRouterV2(sushiRouter).getAmountsOut(token0PerLP, path); wethOut = amountsOut[amountsOut.length - 1]; } //multiply by 1e12 here to get to correct 1e18 scaling return (wethOut * 2 * 1e12); } //result is scaled up by 1e18 function getScaledSushiAPY(address lpToken) public view returns(uint256) { address vault = IQUAI_Controller(quai_controller).vaults(lpToken); address strategy = IQUAI_Controller(quai_controller).strategies(lpToken); uint256 totalLpInvested = getTotalInvested(vault); uint256 sushiRewardsPerYear = getYearlySushiRewards(strategy); uint256 yearlyWethRewards = sushiRewardsPerYear * getSushiPriceInWeth(); uint256 lpPriceInWeth = getSLPPriceInWeth(lpToken); uint256 totalLpValueInWeth = totalLpInvested * lpPriceInWeth; return (yearlyWethRewards * 1e18) / totalLpValueInWeth; } // gauge_relative_weight(address pool) / 1e18 = fraction of new CRV minted to pool // get_gauge_weight(address pool) = new CRV tokens minted to pool per year function getYearlyCurveRewards(address strategy) public view returns(uint256) { address gauge = StrategyCurveGaugeBase(strategy).gauge(); uint256 gaugeWeight = ICurveGaugeController(curveGaugeController).get_gauge_weight(gauge); uint256 workingBalance = ICurveGauge(gauge).working_balances(strategy); uint256 workingSupply = ICurveGauge(gauge).working_supply(); return (gaugeWeight * workingBalance) / workingSupply; } //price of 1e18 CRV in WETH function getCurvePriceInWeth() public view returns(uint256) { address[] memory path = new address[](2); path[0] = curve; path[1] = WETH; uint256[] memory amountsOut = IUniswapRouterV2(uniswapRouter).getAmountsOut(1e18, path); uint256 wethOut = amountsOut[amountsOut.length - 1]; return wethOut; } //price of 1e18 Curve LP in WETH function getCurveLPPriceInWeth(address lpToken) public view returns(uint256) { address strategy = IQUAI_Controller(quai_controller).strategies(lpToken); address curveSwap = StrategyCurveGaugeBase(strategy).curveSwap(); address token0 = ICurveSwap(curveSwap).coins(0); uint256 token0PerLP = ICurveSwap(curveSwap).calc_withdraw_one_coin(1e18, 0); address[] memory path = new address[](2); path[0] = token0; path[1] = WETH; uint256[] memory amountsOut = IUniswapRouterV2(uniswapRouter).getAmountsOut(token0PerLP, path); uint256 wethOut = amountsOut[amountsOut.length - 1]; return wethOut; } //result is scaled up by 1e18 function getScaledCurveAPY(address lpToken) public view returns(uint256) { address vault = IQUAI_Controller(quai_controller).vaults(lpToken); address strategy = IQUAI_Controller(quai_controller).strategies(lpToken); uint256 totalLpInvested = getTotalInvested(vault); uint256 curveRewardsPerYear = getYearlyCurveRewards(strategy); uint256 yearlyWethRewards = curveRewardsPerYear * getCurvePriceInWeth(); uint256 lpPriceInWeth = getCurveLPPriceInWeth(lpToken); uint256 totalLpValueInWeth = totalLpInvested * lpPriceInWeth; return (yearlyWethRewards * 1e18) / totalLpValueInWeth; } }
multiply by 1e12 here to get to correct 1e18 scaling
return (wethOut * 2 * 1e12);
1,625,162
[ 1, 7027, 1283, 635, 404, 73, 2138, 2674, 358, 336, 358, 3434, 404, 73, 2643, 10612, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 327, 261, 91, 546, 1182, 380, 576, 380, 404, 73, 2138, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract AcceptingDonations { /// save the address of the owner of the smart contract in the blockchain address public owner; constructor() payable { owner = payable(msg.sender); } struct Funder { address addr; uint256 amount; } /// save an associative array in the blockchain to store the structure for each funder mapping (address => Funder) public funders; /// save an array of unique funders in the blockchain address[] public uniqFunders; modifier onlyOwner() { require(msg.sender == owner, "Your address in not owner."); _; } modifier saveInfomtionsAboutDonation() { if(msg.value != 0) { if (funders[msg.sender].amount != 0) { uint correntBalance = funders[msg.sender].amount; funders[msg.sender].amount = correntBalance + msg.value; } else { funders[msg.sender] = Funder({ addr: msg.sender, amount: msg.value }); uniqFunders.push(msg.sender); } emit Paid(msg.sender, msg.value); } _; } event Paid(address _from, uint256 _amount); fallback() external { } /// accept funds at the address of the contract receive() external payable saveInfomtionsAboutDonation{ } /// show contract balance function currentBalance() public view returns(uint256) { return address(this).balance; } /// make a donation function transfer() public payable saveInfomtionsAboutDonation { } /// withdraw any amount to any address function withdraw(address addressOutput, uint256 weis) public onlyOwner { address payable _to = payable(addressOutput); _to.transfer(weis); } /// function that returns an array of unique funder addresses function getAccountsOfDonors() public view returns(address[] memory) { return uniqFunders; } /// function that returns the amount of donations to a specific address function amountOfAccountDonations(address addressFunder) public view returns(uint256) { return funders[addressFunder].amount; } }
accept funds at the address of the contract
receive() external payable saveInfomtionsAboutDonation{ }
12,946,890
[ 1, 9436, 284, 19156, 622, 326, 1758, 434, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6798, 1435, 3903, 8843, 429, 1923, 13149, 362, 88, 1115, 24813, 22293, 367, 95, 203, 21281, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// pragma solidity ^0.4.25; pragma solidity ^0.8.0; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "./FlightSuretyData.sol"; // this is not required since interface is defined at the end of this file for reference. /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // operational flag bool private operational = true; // registration fee uint256 public constant registrationFee = 10 ether; uint16 public constant PAYOUT_PERCENT = 150; // Flight status codes. For status codes 20, 40, 50 airline pays out to the insured customer. uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract // reference to Data Contract FlightSuretyData private flightSuretyData; /**** moved to Data Contract struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } mapping(bytes32 => Flight) private flights; ***************/ /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireRegisteredAirline() { require(flightSuretyData.isAirlineRegistered(msg.sender),"Invalid caller - not registered"); _; } /***** modifier requireRegisteredAndPaidAirline() { require(flightSuretyData.isAirlineRegisteredAndPaid(msg.sender),"Invalid caller - not registerede and paid"); _; } *******/ modifier requireFlightNotRegistered(string memory flightId, address airline, uint256 timestamp) { string memory rflightId; uint256 flightTime; address airlineAddress; bool isRegistered; uint8 statusCode; bytes32 flightKey = getFlightKey(airline, flightId, timestamp); (rflightId, airlineAddress, flightTime, isRegistered, statusCode) = flightSuretyData.getFlight(flightKey); require(!isRegistered, "Flight already registered"); _; } modifier requireFlightRegistered(string memory flightId, address airline, uint256 timestamp) { string memory rflightId; uint256 flightTime; address airlineAddress; bool isRegistered; uint8 statusCode; bytes32 flightKey = getFlightKey(airline, flightId, timestamp); (rflightId, airlineAddress, flightTime, isRegistered, statusCode) = flightSuretyData.getFlight(flightKey); require(isRegistered, "Flight not registered for insurance purchase"); _; } modifier requireNotPaid() { address airlineAddress; string memory airlineName; bool regPaid; bool isReg; uint256 paidAmt; (airlineAddress, airlineName, regPaid, paidAmt, isReg) = flightSuretyData.getAirline(msg.sender); require(regPaid == false, "Registration has been paid"); _; } modifier requireRegAmount() { require(msg.value >= 1, "Minimum of 1 ether required for registration amount"); _; } modifier requireCustomerNotPaid(string memory flightId, address airline, uint256 flightTime) { bytes32 flightKey = getFlightKey(airline, flightId, flightTime); require(!flightSuretyData.hasCustomerPaid(msg.sender, flightKey)); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address _flightSuretyData, address firstAirline) { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(payable(_flightSuretyData)); // flightSuretyData.authorizeContract(address(this)); // flightSuretyData.authorizeContract(firstAirline); // done from deployment script // flightSuretyData.registerAirline(firstAirline); // done from deployment script } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { return operational; // Modify to call data contract's status } function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ // Airline making payment for registration. This method accepts payment from airlines for // registration. This is a prerequisite for registration. Until airlines have paid, other // airline cannot propose to register an airline. function makeRegPayment(string memory airlineName) requireIsOperational requireNotPaid requireRegAmount external payable { uint256 paidAmount = msg.value; // registration amount required is 1 ether. Return excess value uint256 surplus = paidAmount - registrationFee; // change state (effects) bool regPaid = true; flightSuretyData.acceptPayment{value: msg.value}(msg.sender, registrationFee, airlineName,regPaid); // do interaction payable(msg.sender).transfer(surplus); } /** * @dev Add an airline to the registration queue * */ function registerAirline(address airline) requireIsOperational requireRegisteredAirline external // returns(bool success, uint256 votes) { if (!flightSuretyData.isAirlineRegistered(airline)) { // check the number of alirline registered if (flightSuretyData.getRegisteredAirlines().length < 4) { // register the airline flightSuretyData.registerAirline(airline); } else { // reg airline count is >=4, put it in reg queue // if 50% of vote is there, then register the airline if (!flightSuretyData.hasSenderVoted(msg.sender, airline)) { // add the votef flightSuretyData.addVote(msg.sender, airline); // get the number of votes. if > 50% of reg airlines, register the airline uint voteCount = flightSuretyData.getVotes(airline).length; uint regAirlineCount = flightSuretyData.getRegisteredAirlines().length; // if (voteCount >= regAirlineCount/2) { if ((voteCount*100)/regAirlineCount >= 50) { // register the airline. All conditions are satisfied flightSuretyData.registerAirline(airline); // TODO: clean (delete) the reg queue for the airline } } } } // return (success, 0); } function isAirlineRegistered(address airline) requireRegisteredAirline view external returns(bool) { return flightSuretyData.isAirlineRegistered(airline); } function getRegisteredAirlines() requireRegisteredAirline view external returns(address[] memory) { return flightSuretyData.getRegisteredAirlines(); } /** * @dev Register a future flight for insuring. * */ function registerFlight (string memory flightId, uint256 flightTime) requireIsOperational requireRegisteredAirline requireFlightNotRegistered(flightId, msg.sender, flightTime) external { address airlineAddress = msg.sender; flightSuretyData.registerFlight(airlineAddress, flightId, flightTime); } // purchase insurance for a flight. Customers call this method to purchase flight insurance function purchaseFlightInsurance(string memory flightId, address airline, uint256 flightTime) requireIsOperational // requireCustomerNotPaid(flightId, airline, flightTime) requireFlightRegistered(flightId, airline, flightTime) external payable { bytes32 flightKey = getFlightKey(airline, flightId, flightTime); flightSuretyData.buy{value: msg.value}(flightKey, msg.sender, msg.value); // flightSuretyData.buy{value: msg.value}(getFlightKey(airline, flightId, flightTime), msg.sender, msg.value); } /** * @dev Called after oracle has updated flight status. TODO: Determine the payouts if the flight was delayed * */ function processFlightStatus ( bytes32 requestKey, uint8 statusCode ) internal { uint256 premiumAmt; uint256 payoutAmt; // check if status code is 20, 40 or 50. // For these status codes, payout needds to happen to the customer. // payout is 1.5 times. // fetch the customers who has insured for the flight. // multiply the paid amout by 1.5 and transfer ether from data contract to customer if (statusCode == 20 || statusCode == 40 || statusCode == 50) { // get insured customer list address[] memory insuredCustomers = flightSuretyData.getInsuredCustomers(requestKey); // get the customer premium for each insured customer and make payment for (uint8 i; i< insuredCustomers.length; i++) { premiumAmt = flightSuretyData.getCustomerPremium(insuredCustomers[i], requestKey); payoutAmt = (premiumAmt * PAYOUT_PERCENT)/100; flightSuretyData.makePayout(insuredCustomers[i],payoutAmt); } } } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string memory flight, uint256 timestamp ) external returns(bytes32) { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); // my addtion to fix the compile problem /**** Gopi commented outto replance it idfferently for solidity v > 0.7.0 oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true, responses: newResponses }); */ // for solidity v0.7.0 and greater // initialize ResponseInfof for the request flightSuretyData.initializeRespInfo(key, msg.sender, index); /****** moved to Data str ResponseInfo storage newResponseInfo = oracleResponses[key]; newResponseInfo.requester = msg.sender; newResponseInfo.isOpen = true; ****** */ emit OracleRequest(index, airline, flight, timestamp); return key; } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; /**** data structures moved from here to Data Contract */ // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); event InsuredCustomers(address[] insuredCustomers); event RespEventCode(uint8 statusCode); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); modifier requireRegFee() { string memory messag = "Caller did not send registration fee of "; string memory regFee = string(abi.encodePacked(bytes32(REGISTRATION_FEE))); require(msg.value >= REGISTRATION_FEE, string(abi.encodePacked(messag, regFee))); _; } // Register an oracle with the contract. function registerOracle ( ) external payable requireRegFee { // Require registration fee. Below line commented out. Functionality moved to modifier // require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[] memory indexes = generateIndexes(msg.sender); flightSuretyData.registerOracle{value: msg.value}(msg.sender, indexes); /**** moved to Data Contract oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); **** moved to data contract *****/ } // Obtain indexes for the given oracle function getOracle ( address account ) public view returns(uint8[] memory) { require(flightSuretyData.isOracleRegistered(account), "Oracle not registered"); return flightSuretyData.getOracleIndexes(account); } function getMyIndexes ( ) view public returns(uint8[] memory) { // require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); require(flightSuretyData.isOracleRegistered(msg.sender), "Oracle not registered"); // return oracles[msg.sender].indexes; // moved to Data contract return flightSuretyData.getOracleIndexes(msg.sender); } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string memory flight, uint256 timestamp, uint8 statusCode ) external { uint8[] memory orclIndexes = getOracle(msg.sender); require((orclIndexes[0] == index) || (orclIndexes[1] == index) || (orclIndexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); // ensure the index receives is the same as the index associated with the flight status request uint8 reqIndex = flightSuretyData.getRequestIndex(key); // require(oracleResponses[key].index == index, "index received is not the index in flight status request"); require(reqIndex == index, "index received is not the index in flight status request"); bool reqOpen = flightSuretyData.isRequestOpen(key); // should be either open or close . If close do nothing require(reqOpen,"No longer open for response"); // add the oracle's response flightSuretyData.addOrclResponse(key, msg.sender, statusCode); // oracleResponses[key].responses[statusCode].push(msg.sender); // moved to Data Contract // emit an event for each valid response received. emit OracleReport(airline, flight, timestamp, statusCode); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information address[] memory orclResponses = flightSuretyData.getOrclResponses(key, statusCode); if (orclResponses.length >= MIN_RESPONSES) { // close the request flightSuretyData.closeOrclResponse(key); // close the request. No further responses will be accepted. // Handle flight status as appropriate.. // processFlightStatus(key, statusCode); // BUG was here. See the description belowmoved to Data contract processFlightStatus(getFlightKey(airline, flight, timestamp), statusCode); // flightSuretyData.creditInsurees(key, statusCode); // THIS WAS THE BUG. WAS HARD TO FIND WITHOUT THE console output in truffle. Used hardhat to identify it. // flightSuretyData.creditInsurees(getFlightKey(airline, flight, timestamp), statusCode); } } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure public returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[] memory) { uint8[] memory indexes = new uint8[](3); indexes[0] = getRandomIndex(account); /* indexes.push(getRandomIndex(account)); indexes.push(getRandomIndex(account)); indexes.push(getRandomIndex(account)); */ indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } if (random == 0) { random = 4;} return random; } // endregion } /* // add reference to FlightData Contract. Similar to itnerface interface FlightSuretyData { // add all the public functions here function registerAirline(address airline) external; function buy() external payable; function creditInsurees() external; function pay() external; function fund() external payable; function getFlightKey(address airline, string memory flight, uint256 timestamp) external returns(bytes32); } */ /***** Before refactoring function submitOracleResponse ( uint8 index, address airline, string memory flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); // ensure the index receives is the same as the index associated with the flight status request require(oracleResponses[key].index == index, "index received is not the index in flight status request"); require(oracleResponses[key].isOpen,"No longer open for response"); oracleResponses[key].responses[statusCode].push(msg.sender); // emit an event for each valid response received. emit OracleReport(airline, flight, timestamp, statusCode); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); oracleResponses[key].isOpen = false; // close the request. No further responses will be accepted. // Handle flight status as appropriate.. TODO processFlightStatus(airline, flight, timestamp, statusCode); } } *************** */
Modify to call data contract's status
{ require(operational, "Contract is currently not operational"); }
989,261
[ 1, 11047, 358, 745, 501, 6835, 1807, 1267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 3639, 2583, 12, 22716, 16, 315, 8924, 353, 4551, 486, 1674, 287, 8863, 21281, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0xF438A8836c49931c873ec3f30aBE4e1e48B27317/sources/ValueLiquidPair.sol
using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply;
17,209,831
[ 1, 9940, 324, 26488, 11932, 450, 17, 86, 396, 7006, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3844, 21, 273, 4501, 372, 24237, 18, 16411, 12, 12296, 21, 13, 342, 389, 4963, 3088, 1283, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping (address=>bool) private authorizedCallers; // Checks whether address is authorized or not /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // event to trigger when airline gets registered event AirlineRegistered( address airlineAccount, string airlineName ); // event to trigger when insurance is purchased event InsurancePurchased( address passengerAccount, uint256 amount, address airlineAccount, string airlineName ); // event to trigger when insurance credit is available event InsuranceCreditAvailable( address airlineAccount, string airlineName ); // event to trigger when insurance credit is paid to passenger event InsurancePaid( address passengerAddress, uint256 payableAmount ); // event to trigger when airline is funded event AirlineFunded(address airlineAddress, uint256 amount); event FlightRegistered(address airlineAddress, string name); event Log256(uint256 val); event LogString(string val); event LogAddress(address val); event LogB32(bytes32 val); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; authorizedCallers[contractOwner] = true; //Add contract owner as authorized caller } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireAuthorizedCaller() { require( authorizedCallers[msg.sender] == true, "Caller is not authorized" ); _; } modifier requireMsgData() { require( msg.data.length > 0, "Message data is absent" ); _; } modifier requireIsAirline() { require(airlines[msg.sender].isRegistered == true, "Caller is not airline"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireAuthorizedCaller { operational = mode; } function authorizeCaller(address _address) external requireIsOperational requireContractOwner { authorizedCallers[_address] = true; } function deauthorizeCaller(address _address) external requireIsOperational requireContractOwner { delete authorizedCallers[_address]; } /********************************************************************************************/ /* SMART CONTRACT VARIABLES */ /********************************************************************************************/ // Structs struct Airline { address airlineAccount; // account address of airline string name; // name of airline bool isRegistered; // is this airline registered or not bool isFunded; // is this airline funded or not bool isNominated; // is this airline nominated or not uint256 fund; // amount of fund available } struct Insurance { mapping(address => uint256) amount; //Address and Amount address[] passengers; bool isPaid; } struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } //Flight Key to Flight mapping(bytes32 => Flight) private flights; //Flight Key to Insurance mapping(bytes32 => Insurance) private insurance; //Address to Airline Struct mapping(address => Airline) private airlines; mapping(address => uint256) private passengerBalance; uint256 internal numberOfRegisteredAirlines = 0; /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airlineAddress, string calldata airlineName ) external requireIsOperational requireAuthorizedCaller { numberOfRegisteredAirlines = numberOfRegisteredAirlines.add(1); airlines[airlineAddress] = Airline(airlineAddress, airlineName, true, false, false, 0); emit AirlineRegistered(airlineAddress, airlineName); } function getAirlineFunds(address airlineAddress) external view requireIsOperational requireAuthorizedCaller returns (uint256) { return airlines[airlineAddress].fund; } function nominateAirline(address airlineAddress) external requireIsOperational requireAuthorizedCaller { airlines[airlineAddress].isNominated = true; } /** * @dev Buy insurance for a flight * */ function buyInsurance ( address passengerAddress, uint256 insuranceAmount, bytes32 flightKey, address airlineAddress ) external requireIsOperational requireAuthorizedCaller { airlines[airlineAddress].fund.add(insuranceAmount); insurance[flightKey].amount[passengerAddress] = insuranceAmount; insurance[flightKey].passengers.push(passengerAddress); emit InsurancePurchased(passengerAddress, insuranceAmount, airlineAddress, airlines[airlineAddress].name); } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 flightKey, address airlineAddress ) external requireIsOperational requireAuthorizedCaller { require(!insurance[flightKey].isPaid, 'Insurance has already been paid'); for(uint i = 0; i < insurance[flightKey].passengers.length; i++){ address passengerAddress = insurance[flightKey].passengers[i]; uint256 insuranceAmount = insurance[flightKey].amount[passengerAddress]; uint256 payoutAmount = insuranceAmount.mul(3).div(2); passengerBalance[passengerAddress] = passengerBalance[passengerAddress].add(payoutAmount); airlines[airlineAddress].fund.sub(payoutAmount); } insurance[flightKey].isPaid = true; emit InsuranceCreditAvailable(airlineAddress, airlines[airlineAddress].name); } /** * @dev Transfers eligible payout funds to insuree * */ function payPassenger ( address payable passengerAddress ) external requireIsOperational requireAuthorizedCaller { uint256 payableAmount = passengerBalance[passengerAddress]; delete(passengerBalance[passengerAddress]); passengerAddress.transfer(payableAmount); emit InsurancePaid(passengerAddress, payableAmount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fundAirline ( address airlineAddress, uint256 amount ) external requireIsOperational requireAuthorizedCaller { airlines[airlineAddress].fund = airlines[airlineAddress].fund.add(amount); airlines[airlineAddress].isFunded = true; emit AirlineFunded(airlineAddress, amount); } function registerFlight( address airline, string calldata flight, uint256 departureTime, uint8 statusCode ) external requireIsOperational requireAuthorizedCaller returns(bool isRegistered) { bytes32 key = getFlightKey(airline, flight, departureTime); flights[key] = Flight({ isRegistered: true, airline: airline, updatedTimestamp: departureTime, statusCode: statusCode }); emit LogB32(key); emit FlightRegistered(airline, flight); return flights[key].isRegistered; } function updateFlightStatus( uint8 statusCode, bytes32 flightKey ) external requireIsOperational requireAuthorizedCaller { flights[flightKey].statusCode = statusCode; } function isFlightRegistered( bytes32 flightKey ) external view requireIsOperational requireAuthorizedCaller returns (bool) { return flights[flightKey].isRegistered == true; } function getFlightStatus( bytes32 flightKey ) external view requireIsOperational requireAuthorizedCaller returns (uint8) { return flights[flightKey].statusCode; } function getPassengerBalance(address passengerAddress) external view requireIsOperational requireAuthorizedCaller returns(uint256) { return passengerBalance[passengerAddress]; } function isAirlineFunded(address airlineAddress) external view requireIsOperational requireAuthorizedCaller returns (bool) { return airlines[airlineAddress].isFunded == true; } function isAirlineRegistered(address airlineAddress) external view requireIsOperational requireAuthorizedCaller returns (bool) { return airlines[airlineAddress].isRegistered == true; } function isAirlineNominated(address airlineAddress) external view requireIsOperational requireAuthorizedCaller returns (bool) { return airlines[airlineAddress].isNominated == true; } function getNumberOfRegisteredAirlines() external view returns(uint256) { return numberOfRegisteredAirlines; } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function() external payable { // React to receiving ether } }
is this airline nominated or not
bool isNominated;
14,085,852
[ 1, 291, 333, 23350, 1369, 12457, 7458, 578, 486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1426, 8197, 362, 7458, 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 ]
./full_match/43113/0x82d4d5B0D89Ab194Dd1D8e7364130990463685D6/sources/PolyCrystal_MasterChef.sol
Deposit LP tokens to MasterHealer for CRYSTL allocation.
function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCrystalPerShare).div(1e18).sub(user.rewardDebt); if (pending > 0) { safeCrystalTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accCrystalPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); }
13,162,763
[ 1, 758, 1724, 511, 52, 2430, 358, 13453, 5256, 6774, 364, 30565, 882, 48, 13481, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 1661, 426, 8230, 970, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 309, 261, 1355, 18, 8949, 405, 374, 13, 288, 203, 5411, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 12893, 31365, 2173, 9535, 2934, 2892, 12, 21, 73, 2643, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 5411, 309, 261, 9561, 405, 374, 13, 288, 203, 7734, 4183, 12893, 31365, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 5411, 289, 203, 3639, 289, 203, 3639, 309, 261, 67, 8949, 405, 374, 13, 288, 203, 5411, 2845, 18, 9953, 1345, 18, 4626, 5912, 1265, 12, 2867, 12, 3576, 18, 15330, 3631, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 5411, 309, 261, 6011, 18, 323, 1724, 14667, 30573, 405, 374, 13, 288, 203, 7734, 2254, 5034, 443, 1724, 14667, 273, 389, 8949, 18, 16411, 12, 6011, 18, 323, 1724, 14667, 30573, 2934, 2892, 12, 23899, 1769, 203, 7734, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 21386, 1887, 16, 443, 1724, 14667, 1769, 203, 7734, 729, 18, 8949, 273, 729, 18, 8949, 18, 1289, 24899, 8949, 2934, 1717, 12, 323, 1724, 14667, 1769, 203, 7734, 729, 18, 8949, 273, 729, 18, 8949, 18, 1289, 24899, 8949, 1769, 203, 2 ]
pragma solidity ^0.4.22; /** * @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; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title MultiOwnable * @dev The MultiOwnable contract has an owner address[], and provides basic authorization control */ contract MultiOwnable is Ownable { struct Types { mapping (address => bool) access; } mapping (uint => Types) private multiOwnersTypes; event AddOwner(uint _type, address addr); event AddOwner(uint[] types, address addr); event RemoveOwner(uint _type, address addr); modifier onlyMultiOwnersType(uint _type) { require(multiOwnersTypes[_type].access[msg.sender] || msg.sender == owner, "403"); _; } function onlyMultiOwnerType(uint _type, address _sender) public view returns(bool) { if (multiOwnersTypes[_type].access[_sender] || _sender == owner) { return true; } return false; } function addMultiOwnerType(uint _type, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); multiOwnersTypes[_type].access[_owner] = true; emit AddOwner(_type, _owner); return true; } function addMultiOwnerTypes(uint[] types, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); require(types.length > 0); for (uint i = 0; i < types.length; i++) { multiOwnersTypes[types[i]].access[_owner] = true; } emit AddOwner(types, _owner); return true; } function removeMultiOwnerType(uint types, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); multiOwnersTypes[types].access[_owner] = false; emit RemoveOwner(types, _owner); return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract IBonus { function getCurrentDayBonus(uint startSaleDate, bool saleState) public view returns(uint); function _currentDay(uint startSaleDate, bool saleState) public view returns(uint); function getBonusData() public view returns(string); function getPreSaleBonusPercent() public view returns(uint); function getMinReachUsdPayInCents() public view returns(uint); } contract ICurrency { function getUsdAbsRaisedInCents() external view returns(uint); function getCoinRaisedBonusInWei() external view returns(uint); function getCoinRaisedInWei() public view returns(uint); function getUsdFromETH(uint ethWei) public view returns(uint); function getTokenFromETH(uint ethWei) public view returns(uint); function getCurrencyRate(string _ticker) public view returns(uint); function addPay(string _ticker, uint value, uint usdAmount, uint coinRaised, uint coinRaisedBonus) public returns(bool); function checkTickerExists(string ticker) public view returns(bool); function getUsdFromCurrency(string ticker, uint value) public view returns(uint); function getUsdFromCurrency(string ticker, uint value, uint usd) public view returns(uint); function getUsdFromCurrency(bytes32 ticker, uint value) public view returns(uint); function getUsdFromCurrency(bytes32 ticker, uint value, uint usd) public view returns(uint); function getTokenWeiFromUSD(uint usdCents) public view returns(uint); function editPay(bytes32 ticker, uint currencyValue, uint currencyUsdRaised, uint _usdAbsRaisedInCents, uint _coinRaisedInWei, uint _coinRaisedBonusInWei) public returns(bool); function getCurrencyList(string ticker) public view returns(bool active, uint usd, uint devision, uint raised, uint usdRaised, uint usdRaisedExchangeRate, uint counter, uint lastUpdate); function getCurrencyList(bytes32 ticker) public view returns(bool active, uint usd, uint devision, uint raised, uint usdRaised, uint usdRaisedExchangeRate, uint counter, uint lastUpdate); function getTotalUsdRaisedInCents() public view returns(uint); function getAllCurrencyTicker() public view returns(string); function getCoinUSDRate() public view returns(uint); function addPreSaleBonus(uint bonusToken) public returns(bool); function editPreSaleBonus(uint beforeBonus, uint afterBonus) public returns(bool); } contract IStorage { function processPreSaleBonus(uint minTotalUsdAmountInCents, uint bonusPercent, uint _start, uint _limit) external returns(uint); function checkNeedProcessPreSaleBonus(uint minTotalUsdAmountInCents) external view returns(bool); function getCountNeedProcessPreSaleBonus(uint minTotalUsdAmountInCents, uint start, uint limit) external view returns(uint); function reCountUserPreSaleBonus(uint uId, uint minTotalUsdAmountInCents, uint bonusPercent, uint maxPayTime) external returns(uint, uint); function getContributorIndexes(uint index) external view returns(uint); function checkNeedSendSHPC(bool proc) external view returns(bool); function getCountNeedSendSHPC(uint start, uint limit) external view returns(uint); function checkETHRefund(bool proc) external view returns(bool); function getCountETHRefund(uint start, uint limit) external view returns(uint); function addPayment(address _addr, string pType, uint _value, uint usdAmount, uint currencyUSD, uint tokenWithoutBonus, uint tokenBonus, uint bonusPercent, uint payId) public returns(bool); function addPayment(uint uId, string pType, uint _value, uint usdAmount, uint currencyUSD, uint tokenWithoutBonus, uint tokenBonus, uint bonusPercent, uint payId) public returns(bool); function checkUserIdExists(uint uId) public view returns(bool); function getContributorAddressById(uint uId) public view returns(address); function editPaymentByUserId(uint uId, uint payId, uint _payValue, uint _usdAmount, uint _currencyUSD, uint _totalToken, uint _tokenWithoutBonus, uint _tokenBonus, uint _bonusPercent) public returns(bool); function getUserPaymentById(uint uId, uint payId) public view returns(uint time, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus, uint tokenWithoutBonus, uint usdAbsRaisedInCents, bool refund); function checkWalletExists(address addr) public view returns(bool result); function checkReceivedCoins(address addr) public view returns(bool); function getContributorId(address addr) public view returns(uint); function getTotalCoin(address addr) public view returns(uint); function setReceivedCoin(uint uId) public returns(bool); function checkPreSaleReceivedBonus(address addr) public view returns(bool); function checkRefund(address addr) public view returns(bool); function setRefund(uint uId) public returns(bool); function getEthPaymentContributor(address addr) public view returns(uint); function refundPaymentByUserId(uint uId, uint payId) public returns(bool); function changeSupportChangeMainWallet(bool support) public returns(bool); } /** * @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 ShipCoin Crowdsale */ contract ShipCoinCrowdsale is MultiOwnable { using SafeMath for uint256; ERC20Basic public coinContract; IStorage public storageContract; ICurrency public currencyContract; IBonus public bonusContract; enum SaleState {NEW, PRESALE, CALCPSBONUS, SALE, END, REFUND} uint256 private constant ONE_DAY = 86400; SaleState public state; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } // minimum goal USD uint public softCapUSD = 500000000; // 5,000,000$ in cents // maximum goal USD uint public hardCapUSD = 6200000000; // 62,000,000$ in cents // maximum available SHPC with a bonus uint public maxDistributeCoin = 600000000 * 1 ether; //600,000,000 shpc (incl. bonus) // minimal accept payment uint public minimalContributionUSD = 100000; // 1000$ in cents // start and end timestamps where investments are allowed in PreSale uint public startPreSaleDate; uint public endPreSaleDate; uint public unfreezeRefundPreSale; uint public unfreezeRefundAll; // start and end timestamps where investments are allowed in sale uint public startSaleDate; uint public endSaleDate; bool public softCapAchieved = false; address public multiSig1; address public multiSig2; bool public multiSigReceivedSoftCap = false; /* Events */ event ChangeState(uint blockNumber, SaleState state); event ChangeMinContribUSD(uint oldAmount, uint newAmount); event ChangeStorageContract(address oldAddress, address newAddress); event ChangeCurrencyContract(address oldAddress, address newAddress); event ChangeCoinContract(address oldAddress, address newAddress); event ChangeBonusContract(address oldAddress, address newAddress); event AddPay(address contributor); event EditPay(address contributor); event SoftCapAchieved(uint amount); event ManualChangeStartPreSaleDate(uint oldDate, uint newDate); event ManualChangeEndPreSaleDate(uint oldDate, uint newDate); event ManualChangeStartSaleDate(uint oldDate, uint newDate); event ManualEndSaleDate(uint oldDate, uint newDate); event SendSHPCtoContributor(address contributor); event SoftCapChanged(); event Refund(address contributor); event RefundPay(address contributor); struct PaymentInfo { bytes32 pType; uint currencyUSD; uint bonusPercent; uint payValue; uint totalToken; uint tokenBonus; uint usdAbsRaisedInCents; bool refund; } struct CurrencyInfo { uint value; uint usdRaised; uint usdAbsRaisedInCents; uint coinRaisedInWei; uint coinRaisedBonusInWei; } struct EditPaymentInfo { uint usdAmount; uint currencyUSD; uint bonusPercent; uint totalToken; uint tokenWithoutBonus; uint tokenBonus; CurrencyInfo currency; } function () external whenNotPaused payable { buyTokens(msg.sender); } /** * @dev Run after deploy. Initialize initial variables * @param _coinAddress address coinContract * @param _storageContract address storageContract * @param _currencyContract address currencyContract * @param _bonusContract address bonusContract * @param _multiSig1 address multiSig where eth will be transferred * @param _startPreSaleDate timestamp * @param _endPreSaleDate timestamp * @param _startSaleDate timestamp * @param _endSaleDate timestamp */ function init( address _coinAddress, address _storageContract, address _currencyContract, address _bonusContract, address _multiSig1, uint _startPreSaleDate, uint _endPreSaleDate, uint _startSaleDate, uint _endSaleDate ) public onlyOwner { require(_coinAddress != address(0)); require(_storageContract != address(0)); require(_currencyContract != address(0)); require(_multiSig1 != address(0)); require(_bonusContract != address(0)); require(_startPreSaleDate > 0 && _startSaleDate > 0); require(_startSaleDate > _endPreSaleDate); require(_endSaleDate > _startSaleDate); require(startSaleDate == 0); coinContract = ERC20Basic(_coinAddress); storageContract = IStorage(_storageContract); currencyContract = ICurrency(_currencyContract); bonusContract = IBonus(_bonusContract); multiSig1 = _multiSig1; multiSig2 = 0x231121dFCB61C929BCdc0D1E6fC760c84e9A02ad; startPreSaleDate = _startPreSaleDate; endPreSaleDate = _endPreSaleDate; startSaleDate = _startSaleDate; endSaleDate = _endSaleDate; unfreezeRefundPreSale = _endSaleDate; unfreezeRefundAll = _endSaleDate.add(ONE_DAY); state = SaleState.NEW; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner { paused = true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner { paused = false; } /** * @dev Change the minimum amount in dollars indicated in cents to accept payment. * @param minContribUsd in cents */ function setMinimalContributionUSD(uint minContribUsd) public onlyOwner { require(minContribUsd > 100); // > 1$ uint oldMinAmount = minimalContributionUSD; minimalContributionUSD = minContribUsd; emit ChangeMinContribUSD(oldMinAmount, minimalContributionUSD); } /** * @dev Set the time when contributors can receive tokens * @param _time timestamp */ function setUnfreezeRefund(uint _time) public onlyOwner { require(_time > startSaleDate); unfreezeRefundPreSale = _time; unfreezeRefundAll = _time.add(ONE_DAY); } /** * @dev Change address ShipCoinStorage contracts. * @param _storageContract address ShipCoinStorage contracts */ function setStorageContract(address _storageContract) public onlyOwner { require(_storageContract != address(0)); address oldStorageContract = storageContract; storageContract = IStorage(_storageContract); emit ChangeStorageContract(oldStorageContract, storageContract); } /** * @dev Change address ShipCoin contracts. * @param _coinContract address ShipCoin contracts */ function setCoinContract(address _coinContract) public onlyOwner { require(_coinContract != address(0)); address oldCoinContract = coinContract; coinContract = ERC20Basic(_coinContract); emit ChangeCoinContract(oldCoinContract, coinContract); } /** * @dev Change address ShipCoinCurrency contracts. * @param _currencyContract address ShipCoinCurrency contracts */ function setCurrencyContract(address _currencyContract) public onlyOwner { require(_currencyContract != address(0)); address oldCurContract = currencyContract; currencyContract = ICurrency(_currencyContract); emit ChangeCurrencyContract(oldCurContract, currencyContract); } /** * @dev Change address ShipCoinBonusSystem contracts. * @param _bonusContract address ShipCoinBonusSystem contracts */ function setBonusContract(address _bonusContract) public onlyOwner { require(_bonusContract != address(0)); address oldContract = _bonusContract; bonusContract = IBonus(_bonusContract); emit ChangeBonusContract(oldContract, bonusContract); } /** * @dev Change address multiSig1. * @param _address address multiSig1 */ function setMultisig(address _address) public onlyOwner { require(_address != address(0)); multiSig1 = _address; } /** * @dev Set softCapUSD * @param _softCapUsdInCents uint softCapUSD > 100000 */ function setSoftCap(uint _softCapUsdInCents) public onlyOwner { require(_softCapUsdInCents > 100000); softCapUSD = _softCapUsdInCents; emit SoftCapChanged(); } /** * @dev Change maximum number of tokens sold * @param _maxCoin maxDistributeCoin */ function changeMaxDistributeCoin(uint _maxCoin) public onlyOwner { require(_maxCoin > 0 && _maxCoin >= currencyContract.getCoinRaisedInWei()); maxDistributeCoin = _maxCoin; } /** * @dev Change status. Start presale. */ function startPreSale() public onlyMultiOwnersType(1) { require(block.timestamp <= endPreSaleDate); require(state == SaleState.NEW); state = SaleState.PRESALE; emit ChangeState(block.number, state); } /** * @dev Change status. Start calculate presale bonus. */ function startCalculatePreSaleBonus() public onlyMultiOwnersType(5) { require(state == SaleState.PRESALE); state = SaleState.CALCPSBONUS; emit ChangeState(block.number, state); } /** * @dev Change status. Start sale. */ function startSale() public onlyMultiOwnersType(2) { require(block.timestamp <= endSaleDate); require(state == SaleState.CALCPSBONUS); //require(!storageContract.checkNeedProcessPreSaleBonus(getMinReachUsdPayInCents())); state = SaleState.SALE; emit ChangeState(block.number, state); } /** * @dev Change status. Set end if sale it was successful. */ function saleSetEnded() public onlyMultiOwnersType(3) { require((state == SaleState.SALE) || (state == SaleState.PRESALE)); require(block.timestamp >= startSaleDate); require(checkSoftCapAchieved()); state = SaleState.END; storageContract.changeSupportChangeMainWallet(false); emit ChangeState(block.number, state); } /** * @dev Change status. Set refund when sale did not reach softcap. */ function saleSetRefund() public onlyMultiOwnersType(4) { require((state == SaleState.SALE) || (state == SaleState.PRESALE)); require(block.timestamp >= endSaleDate); require(!checkSoftCapAchieved()); state = SaleState.REFUND; emit ChangeState(block.number, state); } /** * @dev Payable function. Processes contribution in ETH. */ function buyTokens(address _beneficiary) public whenNotPaused payable { require((state == SaleState.PRESALE && block.timestamp >= startPreSaleDate && block.timestamp <= endPreSaleDate) || (state == SaleState.SALE && block.timestamp >= startSaleDate && block.timestamp <= endSaleDate)); require(_beneficiary != address(0)); require(msg.value > 0); uint usdAmount = currencyContract.getUsdFromETH(msg.value); assert(usdAmount >= minimalContributionUSD); uint bonusPercent = 0; if (state == SaleState.SALE) { bonusPercent = bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); assert((totalToken > 0 && totalToken <= calculateMaxCoinIssued())); uint usdRate = currencyContract.getCurrencyRate("ETH"); assert(storageContract.addPayment(_beneficiary, "ETH", msg.value, usdAmount, usdRate, tokenWithoutBonus, tokenBonus, bonusPercent, 0)); assert(currencyContract.addPay("ETH", msg.value, usdAmount, totalToken, tokenBonus)); emit AddPay(_beneficiary); } /** * @dev Manually add alternative contribution payment. * @param ticker string * @param value uint * @param uId uint contributor identificator * @param _pId uint payment identificator * @param _currencyUSD uint current ticker rate (optional field) */ function addPay(string ticker, uint value, uint uId, uint _pId, uint _currencyUSD) public onlyMultiOwnersType(6) { require(value > 0); require(storageContract.checkUserIdExists(uId)); require(_pId > 0); string memory _ticker = ticker; uint _value = value; assert(currencyContract.checkTickerExists(_ticker)); uint usdAmount = currencyContract.getUsdFromCurrency(_ticker, _value, _currencyUSD); assert(usdAmount > 0); uint bonusPercent = 0; if (state == SaleState.SALE) { bonusPercent = bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); assert(tokenWithoutBonus > 0); uint usdRate = _currencyUSD > 0 ? _currencyUSD : currencyContract.getCurrencyRate(_ticker); uint pId = _pId; assert(storageContract.addPayment(uId, _ticker, _value, usdAmount, usdRate, tokenWithoutBonus, tokenBonus, bonusPercent, pId)); assert(currencyContract.addPay(_ticker, _value, usdAmount, totalToken, tokenBonus)); emit AddPay(storageContract.getContributorAddressById(uId)); } /** * @dev Edit contribution payment. * @param uId uint contributor identificator * @param payId uint payment identificator * @param value uint * @param _currencyUSD uint current ticker rate (optional field) * @param _bonusPercent uint current ticker rate (optional field) */ function editPay(uint uId, uint payId, uint value, uint _currencyUSD, uint _bonusPercent) public onlyMultiOwnersType(7) { require(value > 0); require(storageContract.checkUserIdExists(uId)); require(payId > 0); require((_bonusPercent == 0 || _bonusPercent <= getPreSaleBonusPercent())); PaymentInfo memory payment = getPaymentInfo(uId, payId); EditPaymentInfo memory paymentInfo = calcEditPaymentInfo(payment, value, _currencyUSD, _bonusPercent); assert(paymentInfo.tokenWithoutBonus > 0); assert(paymentInfo.currency.value > 0); assert(paymentInfo.currency.usdRaised > 0); assert(paymentInfo.currency.usdAbsRaisedInCents > 0); assert(paymentInfo.currency.coinRaisedInWei > 0); assert(currencyContract.editPay(payment.pType, paymentInfo.currency.value, paymentInfo.currency.usdRaised, paymentInfo.currency.usdAbsRaisedInCents, paymentInfo.currency.coinRaisedInWei, paymentInfo.currency.coinRaisedBonusInWei)); assert(storageContract.editPaymentByUserId(uId, payId, value, paymentInfo.usdAmount, paymentInfo.currencyUSD, paymentInfo.totalToken, paymentInfo.tokenWithoutBonus, paymentInfo.tokenBonus, paymentInfo.bonusPercent)); assert(reCountUserPreSaleBonus(uId)); emit EditPay(storageContract.getContributorAddressById(uId)); } /** * @dev Refund contribution payment. * @param uId uint * @param payId uint */ function refundPay(uint uId, uint payId) public onlyMultiOwnersType(18) { require(storageContract.checkUserIdExists(uId)); require(payId > 0); (CurrencyInfo memory currencyInfo, bytes32 pType) = calcCurrency(getPaymentInfo(uId, payId), 0, 0, 0, 0); assert(storageContract.refundPaymentByUserId(uId, payId)); assert(currencyContract.editPay(pType, currencyInfo.value, currencyInfo.usdRaised, currencyInfo.usdAbsRaisedInCents, currencyInfo.coinRaisedInWei, currencyInfo.coinRaisedBonusInWei)); assert(reCountUserPreSaleBonus(uId)); emit RefundPay(storageContract.getContributorAddressById(uId)); } /** * @dev Check if softCap is reached */ function checkSoftCapAchieved() public view returns(bool) { return softCapAchieved || getTotalUsdRaisedInCents() >= softCapUSD; } /** * @dev Set softCapAchieved=true if softCap is reached */ function activeSoftCapAchieved() public onlyMultiOwnersType(8) { require(checkSoftCapAchieved()); require(getCoinBalance() >= maxDistributeCoin); softCapAchieved = true; emit SoftCapAchieved(getTotalUsdRaisedInCents()); } /** * @dev Send ETH from contract balance to multiSig. */ function getEther() public onlyMultiOwnersType(9) { require(getETHBalance() > 0); require(softCapAchieved && (!multiSigReceivedSoftCap || (state == SaleState.END))); uint sendEther = (address(this).balance / 2); assert(sendEther > 0); address(multiSig1).transfer(sendEther); address(multiSig2).transfer(sendEther); multiSigReceivedSoftCap = true; } /** * @dev Return maximum amount buy token. */ function calculateMaxCoinIssued() public view returns (uint) { return maxDistributeCoin - currencyContract.getCoinRaisedInWei(); } /** * @dev Return raised SHPC in wei. */ function getCoinRaisedInWei() public view returns (uint) { return currencyContract.getCoinRaisedInWei(); } /** * @dev Return raised usd in cents. */ function getTotalUsdRaisedInCents() public view returns (uint) { return currencyContract.getTotalUsdRaisedInCents(); } /** * @dev Return all currency rate in json. */ function getAllCurrencyTicker() public view returns (string) { return currencyContract.getAllCurrencyTicker(); } /** * @dev Return SHPC price in cents. */ function getCoinUSDRate() public view returns (uint) { return currencyContract.getCoinUSDRate(); } /** * @dev Retrun SHPC balance in contract. */ function getCoinBalance() public view returns (uint) { return coinContract.balanceOf(address(this)); } /** * @dev Return balance ETH from contract. */ function getETHBalance() public view returns (uint) { return address(this).balance; } /** * @dev Processing of the data of the contributors. Bonus assignment for presale. * @param start uint > 0 * @param limit uint > 0 */ function processSetPreSaleBonus(uint start, uint limit) public onlyMultiOwnersType(10) { require(state == SaleState.CALCPSBONUS); require(start >= 0 && limit > 0); //require(storageContract.checkNeedProcessPreSaleBonus(getMinReachUsdPayInCents())); uint bonusToken = storageContract.processPreSaleBonus(getMinReachUsdPayInCents(), getPreSaleBonusPercent(), start, limit); if (bonusToken > 0) { assert(currencyContract.addPreSaleBonus(bonusToken)); } } /** * @dev Processing of the data of the contributor by uId. Bonus assignment for presale. * @param uId uint */ function reCountUserPreSaleBonus(uint uId) public onlyMultiOwnersType(11) returns(bool) { if (uint(state) > 1) { // > PRESALE uint maxPayTime = 0; if (state != SaleState.CALCPSBONUS) { maxPayTime = startSaleDate; } (uint befTokenBonus, uint aftTokenBonus) = storageContract.reCountUserPreSaleBonus(uId, getMinReachUsdPayInCents(), getPreSaleBonusPercent(), maxPayTime); assert(currencyContract.editPreSaleBonus(befTokenBonus, aftTokenBonus)); } return true; } /** * @dev Contributor get SHPC. */ function getCoins() public { return _getCoins(msg.sender); } /** * @dev Send contributors SHPC. * @param start uint * @param limit uint */ function sendSHPCtoContributors(uint start, uint limit) public onlyMultiOwnersType(12) { require(state == SaleState.END); require(start >= 0 && limit > 0); require(getCoinBalance() > 0); //require(storageContract.checkNeedSendSHPC(state == SaleState.END)); for (uint i = start; i < limit; i++) { uint uId = storageContract.getContributorIndexes(i); if (uId > 0) { address addr = storageContract.getContributorAddressById(uId); uint coins = storageContract.getTotalCoin(addr); if (!storageContract.checkReceivedCoins(addr) && storageContract.checkWalletExists(addr) && coins > 0 && ((storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundPreSale) || (!storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundAll))) { if (coinContract.transfer(addr, coins)) { storageContract.setReceivedCoin(uId); emit SendSHPCtoContributor(addr); } } } } } /** * @dev Set startPreSaleDate * @param date timestamp */ function setStartPreSaleDate(uint date) public onlyMultiOwnersType(13) { uint oldDate = startPreSaleDate; startPreSaleDate = date; emit ManualChangeStartPreSaleDate(oldDate, date); } /** * @dev Set startPreSaleDate * @param date timestamp */ function setEndPreSaleDate(uint date) public onlyMultiOwnersType(14) { uint oldDate = endPreSaleDate; endPreSaleDate = date; emit ManualChangeEndPreSaleDate(oldDate, date); } /** * @dev Set startSaleDate * @param date timestamp */ function setStartSaleDate(uint date) public onlyMultiOwnersType(15) { uint oldDate = startSaleDate; startSaleDate = date; emit ManualChangeStartSaleDate(oldDate, date); } /** * @dev Set endSaleDate * @param date timestamp */ function setEndSaleDate(uint date) public onlyMultiOwnersType(16) { uint oldDate = endSaleDate; endSaleDate = date; emit ManualEndSaleDate(oldDate, date); } /** * @dev Return SHPC from contract. When sale ended end contributor got SHPC. */ function getSHPCBack() public onlyMultiOwnersType(17) { require(state == SaleState.END); require(getCoinBalance() > 0); //require(!storageContract.checkNeedSendSHPC(state == SaleState.END)); coinContract.transfer(msg.sender, getCoinBalance()); } /** * @dev Refund ETH contributor. */ function refundETH() public { return _refundETH(msg.sender); } /** * @dev Refund ETH contributors. * @param start uint * @param limit uint */ function refundETHContributors(uint start, uint limit) public onlyMultiOwnersType(19) { require(state == SaleState.REFUND); require(start >= 0 && limit > 0); require(getETHBalance() > 0); //require(storageContract.checkETHRefund(state == SaleState.REFUND)); for (uint i = start; i < limit; i++) { uint uId = storageContract.getContributorIndexes(i); if (uId > 0) { address addr = storageContract.getContributorAddressById(uId); uint ethAmount = storageContract.getEthPaymentContributor(addr); if (!storageContract.checkRefund(addr) && storageContract.checkWalletExists(addr) && ethAmount > 0) { storageContract.setRefund(uId); addr.transfer(ethAmount); emit Refund(addr); } } } } /** * @dev Return pre-sale bonus getPreSaleBonusPercent. */ function getPreSaleBonusPercent() public view returns(uint) { return bonusContract.getPreSaleBonusPercent(); } /** * @dev Return pre-sale minReachUsdPayInCents. */ function getMinReachUsdPayInCents() public view returns(uint) { return bonusContract.getMinReachUsdPayInCents(); } /** * @dev Return current sale day. */ function _currentDay() public view returns(uint) { return bonusContract._currentDay(startSaleDate, (state == SaleState.SALE)); } /** * @dev Return current sale day bonus percent. */ function getCurrentDayBonus() public view returns(uint) { return bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } /** * @dev Return contributor payment info. * @param uId uint * @param pId uint */ function getPaymentInfo(uint uId, uint pId) private view returns(PaymentInfo) { (, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus,, uint usdAbsRaisedInCents, bool refund) = storageContract.getUserPaymentById(uId, pId); return PaymentInfo(pType, currencyUSD, bonusPercent, payValue, totalToken, tokenBonus, usdAbsRaisedInCents, refund); } /** * @dev Return recalculate payment data from old payment user. */ function calcEditPaymentInfo(PaymentInfo payment, uint value, uint _currencyUSD, uint _bonusPercent) private view returns(EditPaymentInfo) { (uint usdAmount, uint currencyUSD, uint bonusPercent) = getUsdAmountFromPayment(payment, value, _currencyUSD, _bonusPercent); (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); (CurrencyInfo memory currency,) = calcCurrency(payment, value, usdAmount, totalToken, tokenBonus); return EditPaymentInfo(usdAmount, currencyUSD, bonusPercent, totalToken, tokenWithoutBonus, tokenBonus, currency); } /** * @dev Return usd from payment amount. */ function getUsdAmountFromPayment(PaymentInfo payment, uint value, uint _currencyUSD, uint _bonusPercent) private view returns(uint, uint, uint) { _currencyUSD = _currencyUSD > 0 ? _currencyUSD : payment.currencyUSD; _bonusPercent = _bonusPercent > 0 ? _bonusPercent : payment.bonusPercent; uint usdAmount = currencyContract.getUsdFromCurrency(payment.pType, value, _currencyUSD); return (usdAmount, _currencyUSD, _bonusPercent); } /** * @dev Return payment SHPC data from usd amount and bonusPercent */ function calcToken(uint usdAmount, uint _bonusPercent) private view returns(uint, uint, uint) { uint tokenWithoutBonus = currencyContract.getTokenWeiFromUSD(usdAmount); uint tokenBonus = _bonusPercent > 0 ? tokenWithoutBonus.mul(_bonusPercent).div(100) : 0; uint totalToken = tokenBonus > 0 ? tokenWithoutBonus.add(tokenBonus) : tokenWithoutBonus; return (totalToken, tokenWithoutBonus, tokenBonus); } /** * @dev Calculate currency data when edit user payment data */ function calcCurrency(PaymentInfo payment, uint value, uint usdAmount, uint totalToken, uint tokenBonus) private view returns(CurrencyInfo, bytes32) { (,,, uint currencyValue, uint currencyUsdRaised,,,) = currencyContract.getCurrencyList(payment.pType); uint usdAbsRaisedInCents = currencyContract.getUsdAbsRaisedInCents(); uint coinRaisedInWei = currencyContract.getCoinRaisedInWei(); uint coinRaisedBonusInWei = currencyContract.getCoinRaisedBonusInWei(); currencyValue -= payment.payValue; currencyUsdRaised -= payment.usdAbsRaisedInCents; usdAbsRaisedInCents -= payment.usdAbsRaisedInCents; coinRaisedInWei -= payment.totalToken; coinRaisedBonusInWei -= payment.tokenBonus; currencyValue += value; currencyUsdRaised += usdAmount; usdAbsRaisedInCents += usdAmount; coinRaisedInWei += totalToken; coinRaisedBonusInWei += tokenBonus; return (CurrencyInfo(currencyValue, currencyUsdRaised, usdAbsRaisedInCents, coinRaisedInWei, coinRaisedBonusInWei), payment.pType); } /** * @dev Getting the SHPC from the contributor */ function _getCoins(address addr) private { require(state == SaleState.END); require(storageContract.checkWalletExists(addr)); require(!storageContract.checkReceivedCoins(addr)); require((storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundPreSale) || (!storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundAll)); uint uId = storageContract.getContributorId(addr); uint coins = storageContract.getTotalCoin(addr); assert(uId > 0 && coins > 0); if (coinContract.transfer(addr, coins)) { storageContract.setReceivedCoin(uId); emit SendSHPCtoContributor(addr); } } /** * @dev Refund ETH contributor when sale not reach softcap. */ function _refundETH(address addr) private { require(state == SaleState.REFUND); require(storageContract.checkWalletExists(addr)); require(!storageContract.checkRefund(addr)); uint uId = storageContract.getContributorId(addr); uint ethAmount = storageContract.getEthPaymentContributor(addr); assert(uId > 0 && ethAmount > 0 && getETHBalance() >= ethAmount); storageContract.setRefund(uId); addr.transfer(ethAmount); emit Refund(addr); } }
* @dev Change address ShipCoinCurrency contracts. @param _currencyContract address ShipCoinCurrency contracts/
function setCurrencyContract(address _currencyContract) public onlyOwner { require(_currencyContract != address(0)); address oldCurContract = currencyContract; currencyContract = ICurrency(_currencyContract); emit ChangeCurrencyContract(oldCurContract, currencyContract); }
15,856,448
[ 1, 3043, 1758, 2638, 625, 27055, 7623, 20092, 18, 225, 389, 7095, 8924, 1758, 2638, 625, 27055, 7623, 20092, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 7623, 8924, 12, 2867, 389, 7095, 8924, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 24899, 7095, 8924, 480, 1758, 12, 20, 10019, 203, 565, 1758, 1592, 2408, 8924, 273, 5462, 8924, 31, 203, 565, 5462, 8924, 273, 467, 7623, 24899, 7095, 8924, 1769, 203, 565, 3626, 7576, 7623, 8924, 12, 1673, 2408, 8924, 16, 5462, 8924, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./spec_interfaces/ICommittee.sol"; import "./ManagedContract.sol"; import "./spec_interfaces/IStakingRewards.sol"; import "./spec_interfaces/IFeesAndBootstrapRewards.sol"; /// @title Committee contract contract Committee is ICommittee, ManagedContract { using SafeMath for uint256; using SafeMath for uint96; uint96 constant CERTIFICATION_MASK = 1 << 95; uint96 constant WEIGHT_MASK = ~CERTIFICATION_MASK; struct CommitteeMember { address addr; uint96 weightAndCertifiedBit; } CommitteeMember[] committee; struct MemberStatus { uint32 pos; bool inCommittee; } mapping(address => MemberStatus) public membersStatus; struct CommitteeStats { uint96 totalWeight; uint32 generalCommitteeSize; uint32 certifiedCommitteeSize; } CommitteeStats committeeStats; uint8 maxCommitteeSize; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _maxCommitteeSize is the maximum number of committee members constructor(IContractRegistry _contractRegistry, address _registryAdmin, uint8 _maxCommitteeSize) ManagedContract(_contractRegistry, _registryAdmin) public { setMaxCommitteeSize(_maxCommitteeSize); } modifier onlyElectionsContract() { require(msg.sender == electionsContract, "caller is not the elections"); _; } /* * External functions */ /// Notifies a weight change of a member /// @dev Called only by: Elections contract /// @param addr is the committee member address /// @param weight is the updated weight of the committee member function memberWeightChange(address addr, uint256 weight) external override onlyElectionsContract onlyWhenActive { MemberStatus memory status = membersStatus[addr]; if (!status.inCommittee) { return; } CommitteeMember memory member = committee[status.pos]; (uint prevWeight, bool isCertified) = getWeightCertification(member); committeeStats.totalWeight = uint96(committeeStats.totalWeight.sub(prevWeight).add(weight)); committee[status.pos].weightAndCertifiedBit = packWeightCertification(weight, isCertified); emit CommitteeChange(addr, weight, isCertified, true); } /// Notifies a change in the certification of a member /// @dev Called only by: Elections contract /// @param addr is the committee member address /// @param isCertified is the updated certification state of the member function memberCertificationChange(address addr, bool isCertified) external override onlyElectionsContract onlyWhenActive { MemberStatus memory status = membersStatus[addr]; if (!status.inCommittee) { return; } CommitteeMember memory member = committee[status.pos]; (uint weight, bool prevCertification) = getWeightCertification(member); CommitteeStats memory _committeeStats = committeeStats; feesAndBootstrapRewardsContract.committeeMembershipWillChange(addr, true, prevCertification, isCertified, _committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize); committeeStats.certifiedCommitteeSize = _committeeStats.certifiedCommitteeSize - (prevCertification ? 1 : 0) + (isCertified ? 1 : 0); committee[status.pos].weightAndCertifiedBit = packWeightCertification(weight, isCertified); emit CommitteeChange(addr, weight, isCertified, true); } /// Notifies a member removal for example due to voteOut or voteUnready /// @dev Called only by: Elections contract /// @param memberRemoved is the removed committee member address /// @return memberRemoved indicates whether the member was removed from the committee /// @return removedMemberWeight indicates the removed member weight /// @return removedMemberCertified indicates whether the member was in the certified committee function removeMember(address addr) external override onlyElectionsContract onlyWhenActive returns (bool memberRemoved, uint removedMemberWeight, bool removedMemberCertified) { MemberStatus memory status = membersStatus[addr]; if (!status.inCommittee) { return (false, 0, false); } memberRemoved = true; (removedMemberWeight, removedMemberCertified) = getWeightCertification(committee[status.pos]); committeeStats = removeMemberAtPos(status.pos, true, committeeStats); } /// Notifies a new member applicable for committee (due to registration, unbanning, certification change) /// The new member will be added only if it is qualified to join the committee /// @dev Called only by: Elections contract /// @param addr is the added committee member address /// @param weight is the added member weight /// @param isCertified is the added member certification state /// @return memberAdded bool indicates whether the member was added function addMember(address addr, uint256 weight, bool isCertified) external override onlyElectionsContract onlyWhenActive returns (bool memberAdded) { return _addMember(addr, weight, isCertified, true); } /// Checks if addMember() would add a the member to the committee (qualified to join) /// @param addr is the candidate committee member address /// @param weight is the candidate committee member weight /// @return wouldAddMember bool indicates whether the member will be added function checkAddMember(address addr, uint256 weight) external view override returns (bool wouldAddMember) { if (membersStatus[addr].inCommittee) { return false; } (bool qualified, ) = qualifiesToEnterCommittee(addr, weight, maxCommitteeSize); return qualified; } /// Returns the committee members and their weights /// @return addrs is the committee members list /// @return weights is an array of uint, indicating committee members list weight /// @return certification is an array of bool, indicating the committee members certification status function getCommittee() external override view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification) { return _getCommittee(); } /// Returns the currently appointed committee data /// @return generalCommitteeSize is the number of members in the committee /// @return certifiedCommitteeSize is the number of certified members in the committee /// @return totalWeight is the total effective stake (weight) of the committee function getCommitteeStats() external override view returns (uint generalCommitteeSize, uint certifiedCommitteeSize, uint totalWeight) { CommitteeStats memory _committeeStats = committeeStats; return (_committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize, _committeeStats.totalWeight); } /// Returns a committee member data /// @param addr is the committee member address /// @return inCommittee indicates whether the queried address is a member in the committee /// @return weight is the committee member weight /// @return isCertified indicates whether the committee member is certified /// @return totalCommitteeWeight is the total weight of the committee. function getMemberInfo(address addr) external override view returns (bool inCommittee, uint weight, bool isCertified, uint totalCommitteeWeight) { MemberStatus memory status = membersStatus[addr]; inCommittee = status.inCommittee; if (inCommittee) { (weight, isCertified) = getWeightCertification(committee[status.pos]); } totalCommitteeWeight = committeeStats.totalWeight; } /// Emits a CommitteeSnapshot events with current committee info /// @dev a CommitteeSnapshot is useful on contract migration or to remove the need to track past events. function emitCommitteeSnapshot() external override { (address[] memory addrs, uint256[] memory weights, bool[] memory certification) = _getCommittee(); for (uint i = 0; i < addrs.length; i++) { emit CommitteeChange(addrs[i], weights[i], certification[i], true); } emit CommitteeSnapshot(addrs, weights, certification); } /* * Governance functions */ /// Sets the maximum number of committee members /// @dev governance function called only by the functional manager /// @dev when reducing the number of members, the bottom ones are removed from the committee /// @param _maxCommitteeSize is the maximum number of committee members function setMaxCommitteeSize(uint8 _maxCommitteeSize) public override onlyFunctionalManager { uint8 prevMaxCommitteeSize = maxCommitteeSize; maxCommitteeSize = _maxCommitteeSize; while (committee.length > _maxCommitteeSize) { (, ,uint pos) = _getMinCommitteeMember(); committeeStats = removeMemberAtPos(pos, true, committeeStats); } emit MaxCommitteeSizeChanged(_maxCommitteeSize, prevMaxCommitteeSize); } /// Returns the maximum number of committee members /// @return maxCommitteeSize is the maximum number of committee members function getMaxCommitteeSize() external override view returns (uint8) { return maxCommitteeSize; } /// Imports the committee members from a previous committee contract during migration /// @dev initialization function called only by the initializationManager /// @dev does not update the reward contract to avoid incorrect notifications /// @param previousCommitteeContract is the address of the previous committee contract function importMembers(ICommittee previousCommitteeContract) external override onlyInitializationAdmin { (address[] memory addrs, uint256[] memory weights, bool[] memory certification) = previousCommitteeContract.getCommittee(); for (uint i = 0; i < addrs.length; i++) { _addMember(addrs[i], weights[i], certification[i], false); } } /* * Private */ /// Checks a member eligibility to join the committee and add if eligible /// @dev Private function called by AddMember and importMembers /// @dev checks if the maximum committee size has reached, removes the lowest weight member if needed /// @param addr is the added committee member address /// @param weight is the added member weight /// @param isCertified is the added member certification state /// @param notifyRewards indicates whether to notify the rewards contract on the update, false on members import during migration function _addMember(address addr, uint256 weight, bool isCertified, bool notifyRewards) private returns (bool memberAdded) { MemberStatus memory status = membersStatus[addr]; if (status.inCommittee) { return false; } (bool qualified, uint entryPos) = qualifiesToEnterCommittee(addr, weight, maxCommitteeSize); if (!qualified) { return false; } memberAdded = true; CommitteeStats memory _committeeStats = committeeStats; if (notifyRewards) { stakingRewardsContract.committeeMembershipWillChange(addr, weight, _committeeStats.totalWeight, false, true); feesAndBootstrapRewardsContract.committeeMembershipWillChange(addr, false, isCertified, isCertified, _committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize); } _committeeStats.generalCommitteeSize++; if (isCertified) _committeeStats.certifiedCommitteeSize++; _committeeStats.totalWeight = uint96(_committeeStats.totalWeight.add(weight)); CommitteeMember memory newMember = CommitteeMember({ addr: addr, weightAndCertifiedBit: packWeightCertification(weight, isCertified) }); if (entryPos < committee.length) { CommitteeMember memory removed = committee[entryPos]; unpackWeightCertification(removed.weightAndCertifiedBit); _committeeStats = removeMemberAtPos(entryPos, false, _committeeStats); committee[entryPos] = newMember; } else { committee.push(newMember); } status.inCommittee = true; status.pos = uint32(entryPos); membersStatus[addr] = status; committeeStats = _committeeStats; emit CommitteeChange(addr, weight, isCertified, true); } /// Pack a member's weight and certification to a compact uint96 representation function packWeightCertification(uint256 weight, bool certification) private pure returns (uint96 weightAndCertified) { return uint96(weight) | (certification ? CERTIFICATION_MASK : 0); } /// Unpacks a compact uint96 representation to a member's weight and certification function unpackWeightCertification(uint96 weightAndCertifiedBit) private pure returns (uint256 weight, bool certification) { return (uint256(weightAndCertifiedBit & WEIGHT_MASK), weightAndCertifiedBit & CERTIFICATION_MASK != 0); } /// Returns the weight and certification of a CommitteeMember entry function getWeightCertification(CommitteeMember memory member) private pure returns (uint256 weight, bool certification) { return unpackWeightCertification(member.weightAndCertifiedBit); } /// Returns the committee members and their weights /// @dev Private function called by getCommittee and emitCommitteeSnapshot /// @return addrs is the committee members list /// @return weights is an array of uint, indicating committee members list weight /// @return certification is an array of bool, indicating the committee members certification status function _getCommittee() private view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification) { CommitteeMember[] memory _committee = committee; addrs = new address[](_committee.length); weights = new uint[](_committee.length); certification = new bool[](_committee.length); for (uint i = 0; i < _committee.length; i++) { addrs[i] = _committee[i].addr; (weights[i], certification[i]) = getWeightCertification(_committee[i]); } } /// Returns the committee member with the minimum weight as a candidate to be removed from the committee /// @dev Private function called by qualifiesToEnterCommittee and setMaxCommitteeSize /// @return minMemberAddress is the address of the committee member with the minimum weight /// @return minMemberWeight is the weight of the committee member with the minimum weight /// @return minMemberPos is the committee array pos of the committee member with the minimum weight function _getMinCommitteeMember() private view returns ( address minMemberAddress, uint256 minMemberWeight, uint minMemberPos ){ CommitteeMember[] memory _committee = committee; minMemberPos = uint256(-1); minMemberWeight = uint256(-1); uint256 memberWeight; address memberAddress; for (uint i = 0; i < _committee.length; i++) { memberAddress = _committee[i].addr; (memberWeight,) = getWeightCertification(_committee[i]); if (memberWeight < minMemberWeight || memberWeight == minMemberWeight && memberAddress < minMemberAddress) { minMemberPos = i; minMemberWeight = memberWeight; minMemberAddress = memberAddress; } } } /// Checks if a potential candidate is qualified to join the committee /// @dev Private function called by checkAddMember and _addMember /// @param addr is the candidate committee member address /// @param weight is the candidate committee member weight /// @param _maxCommitteeSize is the maximum number of committee members /// @return qualified indicates whether the candidate committee member qualifies to join /// @return entryPos is the committee array pos allocated to the member (empty or the position of the minimum weight member) function qualifiesToEnterCommittee(address addr, uint256 weight, uint8 _maxCommitteeSize) private view returns (bool qualified, uint entryPos) { uint committeeLength = committee.length; if (committeeLength < _maxCommitteeSize) { return (true, committeeLength); } (address minMemberAddress, uint256 minMemberWeight, uint minMemberPos) = _getMinCommitteeMember(); if (weight > minMemberWeight || weight == minMemberWeight && addr > minMemberAddress) { return (true, minMemberPos); } return (false, 0); } /// Removes a member at a certain pos in the committee array /// @dev Private function called by _addMember, removeMember and setMaxCommitteeSize /// @param pos is the committee array pos to be removed /// @param clearFromList indicates whether to clear the entry in the committee array, false when overriding it with a new member /// @param _committeeStats is the current committee statistics /// @return newCommitteeStats is the updated committee committee statistics after the removal function removeMemberAtPos(uint pos, bool clearFromList, CommitteeStats memory _committeeStats) private returns (CommitteeStats memory newCommitteeStats){ CommitteeMember memory member = committee[pos]; (uint weight, bool certification) = getWeightCertification(member); stakingRewardsContract.committeeMembershipWillChange(member.addr, weight, _committeeStats.totalWeight, true, false); feesAndBootstrapRewardsContract.committeeMembershipWillChange(member.addr, true, certification, certification, _committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize); delete membersStatus[member.addr]; _committeeStats.generalCommitteeSize--; if (certification) _committeeStats.certifiedCommitteeSize--; _committeeStats.totalWeight = uint96(_committeeStats.totalWeight.sub(weight)); emit CommitteeChange(member.addr, weight, certification, false); if (clearFromList) { uint committeeLength = committee.length; if (pos < committeeLength - 1) { CommitteeMember memory last = committee[committeeLength - 1]; committee[pos] = last; membersStatus[last.addr].pos = uint32(pos); } committee.pop(); } return _committeeStats; } /* * Contracts topology / registry interface */ address electionsContract; IStakingRewards stakingRewardsContract; IFeesAndBootstrapRewards feesAndBootstrapRewardsContract; /// 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 { electionsContract = getElectionsContract(); stakingRewardsContract = IStakingRewards(getStakingRewardsContract()); feesAndBootstrapRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); } }
Imports the committee members from a previous committee contract during migration @dev initialization function called only by the initializationManager @dev does not update the reward contract to avoid incorrect notifications @param previousCommitteeContract is the address of the previous committee contract
function importMembers(ICommittee previousCommitteeContract) external override onlyInitializationAdmin { (address[] memory addrs, uint256[] memory weights, bool[] memory certification) = previousCommitteeContract.getCommittee(); for (uint i = 0; i < addrs.length; i++) { _addMember(addrs[i], weights[i], certification[i], false); } }
2,521,355
[ 1, 13347, 326, 3294, 22579, 4833, 628, 279, 2416, 3294, 22579, 6835, 4982, 6333, 225, 10313, 445, 2566, 1338, 635, 326, 10313, 1318, 225, 1552, 486, 1089, 326, 19890, 6835, 358, 4543, 11332, 9208, 225, 2416, 5580, 22579, 8924, 353, 326, 1758, 434, 326, 2416, 3294, 22579, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 915, 1930, 6918, 12, 45, 5580, 22579, 2416, 5580, 22579, 8924, 13, 3903, 3849, 1338, 17701, 4446, 288, 203, 202, 202, 12, 2867, 8526, 3778, 11755, 16, 2254, 5034, 8526, 3778, 5376, 16, 1426, 8526, 3778, 3320, 1480, 13, 273, 2416, 5580, 22579, 8924, 18, 588, 5580, 22579, 5621, 203, 202, 202, 1884, 261, 11890, 277, 273, 374, 31, 277, 411, 11755, 18, 2469, 31, 277, 27245, 288, 203, 1082, 202, 67, 1289, 4419, 12, 23305, 63, 77, 6487, 5376, 63, 77, 6487, 3320, 1480, 63, 77, 6487, 629, 1769, 203, 202, 202, 97, 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 ]
./full_match/56/0xfC652Ea2E8A373C16f3d8c5BD25E9898b9699ECB/sources/contracts/IFAllocationMaster.sol
increase new track's checkpoint count by 1
trackCheckpointCounts[trackId]++;
3,247,523
[ 1, 267, 11908, 394, 3298, 1807, 9776, 1056, 635, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 3298, 14431, 9211, 63, 4101, 548, 3737, 15, 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 ]
/** * This library file acts as model which provides * attributes for the user and the functions to * perform operations on the given data */ pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; // experimental // @title User holds all structs // for user details library User { // UserDetail holds personal // details of the user struct UserDetail { string fullName; // fullname of the user bytes32 userName; // username or url selected by the user string imgUrl; // profile image url string email; // email address of the user string location; // location of the user string description; // one line description of the user } // UserSocial holds all the urls // for the social accounts of the user struct UserSocial { string websiteUrl; // personal website of user string twitterUrl; // twitter handle of user string fbUrl; // facebook handle of user string githubUrl; // github url string dribbbleUrl; // dribbble url string linkedInUrl; // linkedIn handle of user string behanceUrl; // behance Url of user string mediumUrl; // medium url of user } // UserWorkExp holds record of // work experience for a particular location struct UserWorkExp { string company; // name of the company or organization string position; // position held in the company string dateStart; // start date string dateEnd; // end date string description; // description of the job role bool isWorking; // true if user still works here bool isDeleted; // true if work exp entry is deleted, else false } // UserEducation holds information // for all the user formal and informal // education struct UserEducation { string organization; // name of the school or organization string level; // level of qualification string dateStart; // start date string dateEnd; // end date string description; // description of the qualification bool isDeleted; // true if the education entry is deleted, else false } // UserProjects holds records all // the professional and academic projects // that the user wants to showcase struct UserProject { string name; // name of the project string shortDescription; // one line description string description; // description of the project string url; // url of the project bool isDeleted; // true if the project entry is deleted, else false } // Skills of the user struct UserSkill { bytes32[] skills; // skills of the user } // Introduction of the user struct UserIntroduction { string introduction; // introduction of the user } // Academic publication struct UserPublication { string title; // title of the paper string url; // link to the paper string description; // description of the paper bool isDeleted; // true if the current publication has been deleted } // User is struct which holds all // the details for a particular user // creating a CV on Blockvitae struct UserMain { UserDetail personal; // personal details of the user UserSocial social; // social details of the user UserWorkExp[] work; // work experience of the user UserEducation[] education; // education of the user UserProject[] projects; // projects of the user UserSkill skills; // skills of the user UserIntroduction introduction; // introduction of the user UserPublication[] publications; // publications by the user bool exists; // true everytime add new new struct address owner; // owner of the user profile } // @description // sets the values of UserDetail struct // // @param string _fullName // full name of the user // // @param bytes32 _userName // username of the user // // @param string _imgUrl // profile image url of the user // // @param string _email // email of the user // // @param string _location // (City, State) of the User // // @param string _description // One line descriprion of the user // // @return UserDetail // UserDetail struct for the given values function setUserDetail( string _fullName, bytes32 _userName, string _imgUrl, string _email, string _location, string _description ) internal pure returns(UserDetail) { UserDetail memory detail; detail.fullName = bytes(_fullName).length != 0 ? _fullName : ""; detail.userName = _userName; detail.imgUrl = _imgUrl; detail.email = _email; detail.location = _location; detail.description = _description; return detail; } // @description // sets the values of UserSocial struct // // @param string _websiteUrl // personal website url // // @param string _twitterUrl // twitter url of the user // // @param string _fbUrl // facebook url of the user // // @param string _githubUrl // github url of the user // // @param string _linkedInUrl // linked in url of the user // // @param string _behanceUrl // behance url of the user // // @param string _mediumUrl // medium url of the user // // @return UserSocial // UserSocial struct for the given values function setUserSocial( string _websiteUrl, string _twitterUrl, string _fbUrl, string _githubUrl, string _dribbbleUrl, string _linkedInUrl, string _behanceUrl, string _mediumUrl ) internal pure returns(UserSocial) { UserSocial memory social; social.twitterUrl = bytes(_twitterUrl).length != 0 ? _twitterUrl : ""; social.websiteUrl = bytes(_websiteUrl).length != 0 ? _websiteUrl : ""; social.fbUrl = bytes(_fbUrl).length != 0 ? _fbUrl : ""; social.githubUrl = bytes(_githubUrl).length != 0 ? _githubUrl : ""; social.dribbbleUrl = bytes(_dribbbleUrl).length != 0 ? _dribbbleUrl : ""; social.linkedInUrl = bytes(_linkedInUrl).length != 0 ? _linkedInUrl : ""; social.behanceUrl = bytes(_behanceUrl).length != 0 ? _behanceUrl : ""; social.mediumUrl = bytes(_mediumUrl).length != 0 ? _mediumUrl : ""; return social; } // @description // sets the values of UserProject struct // // @param string _name // name of the project // // @param string _shortDescription // One line description of the project // // @param string _description // description of the project // // @param string _url // url of the project // // @param bool _isDeleted // true if the current record has been deleted by the user // // @return UserProject // UserProject struct for the given values function setUserProject( string _name, string _shortDescription, string _description, string _url, bool _isDeleted ) internal pure returns(UserProject) { require(bytes(_name).length > 0); require(bytes(_shortDescription).length > 0); require(bytes(_description).length > 0); UserProject memory project; project.description = bytes(_description).length != 0 ? _description : ""; project.shortDescription = bytes(_shortDescription).length != 0 ? _shortDescription : ""; project.name = bytes(_name).length != 0 ? _name : ""; project.url = bytes(_url).length != 0 ? _url : ""; project.isDeleted = _isDeleted ? true : false; return project; } // @description // sets the values of UserWorkExp struct // // @param string _company // name of the company or organization // // @param string _position // position held in the given company // // @param string _dateStart // start date of the job // // @param string _dateEnd // end date of the job // // @param string _description // description of the work experience // // @param bool _isWorking // true if user still works here // // @param bool _isDeleted // true if the current record has been deleted by the user // // @return UserWorkExp // UserWorkExp struct for the given values function setUserWorkExp( string _company, string _position, string _dateStart, string _dateEnd, string _description, bool _isWorking, bool _isDeleted ) internal pure returns(UserWorkExp) { require(bytes(_company).length > 0); require(bytes(_position).length > 0); require(bytes(_dateStart).length > 0); require(bytes(_description).length > 0); UserWorkExp memory workExp; workExp.company = bytes(_company).length != 0 ? _company : ""; workExp.position = bytes(_position).length != 0 ? _position : ""; workExp.dateStart = bytes(_dateStart).length != 0 ? _dateStart : ""; workExp.dateEnd = bytes(_dateEnd).length != 0 ? _dateEnd : ""; workExp.description = bytes(_description).length != 0 ? _description : ""; workExp.isWorking = _isWorking ? true : false; workExp.isDeleted = _isDeleted ? true : false; return workExp; } // @description // sets the values of UserEducation struct // // @param string _organization // name of the organization // // @param string _level // education level held in the given organization // // @param string _dateStart // start date of the education // // @param string _dateEnd // end date of the education // // @param string _description // description of the education // // @param bool _isDeleted // true if the current record has been deleted by the user // // @return UserEducation // UserEducation struct for the given values function setUserEducation( string _organization, string _level, string _dateStart, string _dateEnd, string _description, bool _isDeleted ) internal pure returns(UserEducation) { require(bytes(_organization).length > 0); require(bytes(_level).length > 0); require(bytes(_dateStart).length > 0); require(bytes(_description).length > 0); UserEducation memory education; education.organization = bytes(_organization).length != 0 ? _organization : ""; education.level = bytes(_level).length != 0 ? _level : ""; education.dateStart = bytes(_dateStart).length != 0 ? _dateStart : ""; education.dateEnd = bytes(_dateEnd).length != 0 ? _dateEnd : ""; education.description = bytes(_description).length != 0 ? _description : ""; education.isDeleted = _isDeleted ? true : false; return education; } // @description // sets the values of UserPublication struct // // @param string _title // title of the paper // // @param string _url // link to the paper // // @param string _description // description of the paper // // @param bool _isDeleted // true if the current record has been deleted by the user // // @return UserPublication // UserPublication struct for the given values function setUserPublication( string _title, string _url, string _description, bool _isDeleted ) internal pure returns(UserPublication) { require(bytes(_title).length > 0); require(bytes(_url).length > 0); require(bytes(_description).length > 0); UserPublication memory publication; publication.title = bytes(_title).length != 0 ? _title : ""; publication.url = bytes(_url).length != 0 ? _url : ""; publication.description = bytes(_description).length != 0 ? _description : ""; publication.isDeleted = _isDeleted ? true : false; return publication; } // @description // sets the values of UserSkill struct // // @param bytes32[] _skills // a byte32 array of skills // // @return UserSkill // a UserSkill struct with given skills function setUserSkill(bytes32[] _skills) internal pure returns(UserSkill) { UserSkill memory uSkill; uSkill.skills = _skills; return uSkill; } // @description // sets the introduction in UserIntroduction struct // // @param string introduction // a short paragraph of introduction of the user // // @return UserIntroduction // a UserIntroduction struct with given introduction function setUserIntroduction(string _introduction) internal pure returns(UserIntroduction) { UserIntroduction memory uIntro; uIntro.introduction = _introduction; return uIntro; } }
UserSocial holds all the urls for the social accounts of the user
struct UserSocial { }
13,052,206
[ 1, 1299, 28795, 14798, 777, 326, 6903, 364, 326, 16702, 9484, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 2177, 28795, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2016-2019 zOS Global Limited * */ pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { // Optional functions function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20/IERC20.sol"; interface IBrokerbot { function base() external view returns (IERC20); function settings() external view returns (uint256); // @return The amount of shares bought on buying or how much in the base currency is transfered on selling function processIncoming(IERC20 token_, address from, uint256 amount, bytes calldata ref) external payable returns (uint256); } // SPDX-License-Identifier: MIT // https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/interfaces/IQuoter.sol pragma solidity ^0.8.0; interface IQuoter { function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); // solhint-disable-next-line func-name-mixedcase function WETH9() external view returns (address); } interface ISwapRouter { struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); function refundETH() external payable; } /** * SPDX-License-Identifier: LicenseRef-Aktionariat * * MIT License with Automated License Fee Payments * * Copyright (c) 2021 Aktionariat AG (aktionariat.com) * * Permission is hereby granted 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. * - All automated license fee payments integrated into this and related Software * are preserved. * * 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.8.0; import "../utils/Address.sol"; import "../ERC20/IERC20.sol"; import "./IUniswapV3.sol"; import "../utils/Ownable.sol"; import "./IBrokerbot.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; /** * A hub for payments. This allows tokens that do not support ERC 677 to enjoy similar functionality, * namely interacting with a token-handling smart contract in one transaction, without having to set an allowance first. * Instead, an allowance needs to be set only once, namely for this contract. * Further, it supports automatic conversion from Ether to the payment currency through Uniswap or the reception of Ether * using the current exchange rate as found in the chainlink oracle. */ contract PaymentHub { uint24 private constant DEFAULT_FEE = 3000; uint256 private constant DENOMINATOR = 1e8; address private constant CHF_TOKEN = 0xB4272071eCAdd69d933AdcD19cA99fe80664fc08; uint8 private constant KEEP_ETHER = 0x4; // copied from brokerbot IQuoter private immutable uniswapQuoter; ISwapRouter private immutable uniswapRouter; AggregatorV3Interface internal immutable priceFeedCHFUSD; AggregatorV3Interface internal immutable priceFeedETHUSD; constructor(IQuoter _quoter, ISwapRouter swapRouter, AggregatorV3Interface _aggregatorCHFUSD, AggregatorV3Interface _aggregatorETHUSD) { uniswapQuoter = _quoter; uniswapRouter = swapRouter; priceFeedCHFUSD = _aggregatorCHFUSD; priceFeedETHUSD = _aggregatorETHUSD; } /* * Get price in ERC20 * This is the method that the Brokerbot widget should use to quote the price to the user. * @param amountInBase The amount of the base currency for the exact output. * @param path The encoded path of the swap from erc20 to base. * @return amount quoted to pay */ function getPriceInERC20(uint256 amountInBase, bytes memory path) public returns (uint256) { return uniswapQuoter.quoteExactOutput( path, amountInBase ); } /** * Get price in Ether depding on brokerbot setting. * If keep ETH is set price is from oracle. * This is the method that the Brokerbot widget should use to quote the price to the user. * @return The price in wei. */ function getPriceInEther(uint256 amountInBase, IBrokerbot brokerBot) public returns (uint256) { if ((address(brokerBot) != address(0)) && hasSettingKeepEther(brokerBot)) { return getPriceInEtherFromOracle(amountInBase, IBrokerbot(brokerBot).base()); } else { return uniswapQuoter.quoteExactOutputSingle(uniswapQuoter.WETH9(), address(brokerBot.base()), DEFAULT_FEE, amountInBase, 0); } } /** * Price in ETH with 18 decimals */ function getPriceInEtherFromOracle(uint256 amountInBase, IERC20 base) public view returns (uint256) { if(address(base) == CHF_TOKEN) { return getLatestPriceCHFUSD() * amountInBase / getLatestPriceETHUSD(); } else { return amountInBase * DENOMINATOR / getLatestPriceETHUSD(); } } /** * Returns the latest price of eth/usd pair from chainlink with 8 decimals */ function getLatestPriceETHUSD() public view returns (uint256) { (, int256 price, , , ) = priceFeedETHUSD.latestRoundData(); return uint256(price); } /** * Returns the latest price of chf/usd pair from chainlink with 8 decimals */ function getLatestPriceCHFUSD() public view returns (uint256) { (, int256 price, , , ) = priceFeedCHFUSD.latestRoundData(); return uint256(price); } /** * Convenience method to swap ether into base and pay a target address */ function payFromEther(address recipient, uint256 amountInBase, IERC20 base) public payable { ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams( // rely on time stamp is ok, no exact time stamp needed // solhint-disable-next-line not-rely-on-time uniswapQuoter.WETH9(), address(base), DEFAULT_FEE, recipient, block.timestamp, amountInBase, msg.value, 0); ISwapRouter swapRouter = uniswapRouter; // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. uint256 amountIn = swapRouter.exactOutputSingle{value: msg.value}(params); // For exact output swaps, the amountInMaximum may not have all been spent. // If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0. if (amountIn < msg.value) { swapRouter.refundETH(); (bool success, ) = msg.sender.call{value:msg.value - amountIn}(""); // return change require(success, "Transfer failed."); } } /// @dev The calling address must approve this contract to spend its ERC20 for this function to succeed. As the amount of input ERC20 is variable, /// the calling address will need to approve for a slightly higher or infinit amount, anticipating some variance. /// @param amountOut The desired amount of baseCurrency. /// @param amountInMaximum The maximum amount of ERC20 willing to be swapped for the specified amountOut of baseCurrency. /// @param erc20In The address of the erc20 token to pay with. /// @param path The encoded path of the swap from erc20 to base. /// @param recipient The reciving address - brokerbot. /// @return amountIn The amountIn of ERC20 actually spent to receive the desired amountOut. function payFromERC20(uint256 amountOut, uint256 amountInMaximum, address erc20In, bytes memory path, address recipient) public returns (uint256 amountIn) { ISwapRouter swapRouter = uniswapRouter; // Transfer the specified `amountInMaximum` to this contract. IERC20(erc20In).transferFrom(msg.sender, address(this), amountInMaximum); // The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn) ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({ path: path, recipient: recipient, // solhint-disable-next-line not-rely-on-time deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum }); // Executes the swap, returning the amountIn actually spent. amountIn = swapRouter.exactOutput(params); // If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0. if (amountIn < amountInMaximum) { IERC20(erc20In).transfer(msg.sender, amountInMaximum - amountIn); } } ///This function appoves infinite allowance for Uniswap, this is safe as the paymenthub should never hold any token (see also recover() ). ///@dev This function needs to be called before using the PaymentHub the first time with a new ERC20 token. ///@param erc20In The erc20 addresse to approve. function approveERC20(address erc20In) external { IERC20(erc20In).approve(address(uniswapRouter), 0x8000000000000000000000000000000000000000000000000000000000000000); } function multiPay(IERC20 token, address[] calldata recipients, uint256[] calldata amounts) public { for (uint i=0; i<recipients.length; i++) { require(IERC20(token).transferFrom(msg.sender, recipients[i], amounts[i])); } } /** * Can (at least in theory) save some gas as the sender balance only is touched in one transaction. */ function multiPayAndNotify(IERC20 token, address[] calldata recipients, uint256[] calldata amounts, bytes calldata ref) external { for (uint i=0; i<recipients.length; i++) { payAndNotify(token, recipients[i], amounts[i], ref); } } // Allows to make a payment from the sender to an address given an allowance to this contract // Equivalent to xchf.transferAndCall(recipient, amountInBase) function payAndNotify(address recipient, uint256 amountInBase, bytes calldata ref) external { payAndNotify(IBrokerbot(recipient).base(), recipient, amountInBase, ref); } function payAndNotify(IERC20 token, address recipient, uint256 amount, bytes calldata ref) public { require(IERC20(token).transferFrom(msg.sender, recipient, amount)); IBrokerbot(recipient).processIncoming(token, msg.sender, amount, ref); } function payFromEtherAndNotify(IBrokerbot recipient, uint256 amountInBase, bytes calldata ref) external payable { IERC20 base = recipient.base(); // Check if the brokerbot has setting to keep ETH if (hasSettingKeepEther(recipient)) { uint256 priceInEther = getPriceInEtherFromOracle(amountInBase, base); recipient.processIncoming{value: priceInEther}(base, msg.sender, amountInBase, ref); // Pay back ETH that was overpaid if (priceInEther < msg.value) { (bool success, ) = msg.sender.call{value:msg.value - priceInEther}(""); // return change require(success, "Transfer failed."); } } else { payFromEther(address(recipient), amountInBase, base); recipient.processIncoming(base, msg.sender, amountInBase, ref); } } /*** * Pay from any ERC20 token (which has Uniswapv3 ERC20-ETH pool) and send swapped base currency to brokerbot. * The needed amount needs to be approved at the ERC20 contract beforehand */ function payFromERC20AndNotify(address recipient, uint256 amountBase, address erc20, uint256 amountInMaximum, bytes memory path, bytes calldata ref) external { IERC20 base = IBrokerbot(recipient).base(); uint256 balanceBefore = IERC20(base).balanceOf(recipient); payFromERC20(amountBase, amountInMaximum, erc20, path, recipient); uint256 balanceAfter = IERC20(base).balanceOf(recipient); require(amountBase == (balanceAfter - balanceBefore), "swap error"); IBrokerbot(recipient).processIncoming(base, msg.sender, balanceAfter - balanceBefore, ref); } /** * Checks if the recipient(brokerbot) has setting enabled to keep ether */ function hasSettingKeepEther(IBrokerbot recipient) public view returns (bool) { return recipient.settings() & KEEP_ETHER == KEEP_ETHER; } /** * In case tokens have been accidentally sent directly to this contract. * Make sure to be fast as anyone can call this! */ function recover(IERC20 ercAddress, address to, uint256 amount) external { require(ercAddress.transfer(to, amount)); } // solhint-disable-next-line no-empty-blocks receive() external payable { // Important to receive ETH refund from Uniswap } } // SPDX-License-Identifier: MIT // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol // and modified it. pragma solidity ^0.8.0; 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/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } function functionCallWithValue(address target, bytes memory data, uint256 weiValue) internal returns (bytes memory) { require(data.length == 0 || isContract(target), "transfer or contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else if (returndata.length > 0) { assembly{ revert (add (returndata, 0x20), mload (returndata)) } } else { revert("failed"); } } } // SPDX-License-Identifier: MIT // // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol // // Modifications: // - Replaced Context._msgSender() with msg.sender // - Made leaner // - Extracted interface pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor (address initialOwner) { owner = initialOwner; emit OwnershipTransferred(address(0), owner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external onlyOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } modifier onlyOwner() { require(owner == msg.sender, "not owner"); _; } }
@dev The calling address must approve this contract to spend its ERC20 for this function to succeed. As the amount of input ERC20 is variable, the calling address will need to approve for a slightly higher or infinit amount, anticipating some variance. @param amountOut The desired amount of baseCurrency. @param amountInMaximum The maximum amount of ERC20 willing to be swapped for the specified amountOut of baseCurrency. @param erc20In The address of the erc20 token to pay with. @param path The encoded path of the swap from erc20 to base. @param recipient The reciving address - brokerbot. @return amountIn The amountIn of ERC20 actually spent to receive the desired amountOut. Transfer the specified `amountInMaximum` to this contract. The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn) solhint-disable-next-line not-rely-on-time If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0.
function payFromERC20(uint256 amountOut, uint256 amountInMaximum, address erc20In, bytes memory path, address recipient) public returns (uint256 amountIn) { ISwapRouter swapRouter = uniswapRouter; IERC20(erc20In).transferFrom(msg.sender, address(this), amountInMaximum); ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({ path: path, recipient: recipient, deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum }); if (amountIn < amountInMaximum) { IERC20(erc20In).transfer(msg.sender, amountInMaximum - amountIn); } }
1,572,236
[ 1, 1986, 4440, 1758, 1297, 6617, 537, 333, 6835, 358, 17571, 2097, 4232, 39, 3462, 364, 333, 445, 358, 12897, 18, 2970, 326, 3844, 434, 810, 4232, 39, 3462, 353, 2190, 16, 326, 4440, 1758, 903, 1608, 358, 6617, 537, 364, 279, 21980, 10478, 578, 316, 926, 305, 3844, 16, 17841, 24629, 1776, 2690, 12380, 18, 225, 3844, 1182, 1021, 6049, 3844, 434, 1026, 7623, 18, 225, 3844, 382, 13528, 1021, 4207, 3844, 434, 4232, 39, 3462, 903, 310, 358, 506, 7720, 1845, 364, 326, 1269, 3844, 1182, 434, 1026, 7623, 18, 225, 6445, 71, 3462, 382, 1021, 1758, 434, 326, 6445, 71, 3462, 1147, 358, 8843, 598, 18, 225, 589, 1021, 3749, 589, 434, 326, 7720, 628, 6445, 71, 3462, 358, 1026, 18, 225, 8027, 1021, 1950, 9288, 1758, 300, 8625, 4819, 18, 327, 3844, 382, 1021, 3844, 382, 434, 4232, 39, 3462, 6013, 26515, 358, 6798, 326, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 8843, 1265, 654, 39, 3462, 12, 11890, 5034, 3844, 1182, 16, 2254, 5034, 3844, 382, 13528, 16, 1758, 6445, 71, 3462, 382, 16, 1731, 3778, 589, 16, 1758, 8027, 13, 1071, 1135, 261, 11890, 5034, 3844, 382, 13, 288, 203, 3639, 4437, 91, 438, 8259, 7720, 8259, 273, 640, 291, 91, 438, 8259, 31, 203, 3639, 467, 654, 39, 3462, 12, 12610, 3462, 382, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 382, 13528, 1769, 203, 203, 3639, 4437, 91, 438, 8259, 18, 14332, 1447, 1370, 3778, 859, 273, 203, 5411, 4437, 91, 438, 8259, 18, 14332, 1447, 1370, 12590, 203, 7734, 589, 30, 589, 16, 203, 7734, 8027, 30, 8027, 16, 203, 7734, 14096, 30, 1203, 18, 5508, 16, 203, 7734, 3844, 1182, 30, 3844, 1182, 16, 203, 7734, 3844, 382, 13528, 30, 3844, 382, 13528, 203, 5411, 15549, 203, 203, 203, 3639, 309, 261, 8949, 382, 411, 3844, 382, 13528, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 12610, 3462, 382, 2934, 13866, 12, 3576, 18, 15330, 16, 3844, 382, 13528, 300, 3844, 382, 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 ]
pragma solidity ^0.4.24; import "./interfaces/IHRSYToken.sol"; import "./interfaces/IRaceValidator.sol"; import "./WalletUser.sol"; import "../openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "../openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../openzeppelin-solidity/contracts/math/SafeMath.sol"; /** @title HorseyToken ERC721 Token @dev Horse contract - horse derives from Pausable */ contract HorseyGame is WalletUser, Pausable, Ownable { using SafeMath for uint256; /// @dev called when someone claims his HORSE from a RWRD HRSY event RewardClaimed(uint256 tokenId, address to, uint256 Amount); /// @dev called when someone claims a token event Claimed(address raceAddress, address eth_address, uint256 tokenId); /// @dev called when someone ends a feeding process event Upgraded(uint256 tokenId); /// @dev called when a horsey is renamed event Renamed(uint256 tokenId, string newName); /// @dev called when a horsey is burned event Burned(uint256 tokenId); /// @dev called when someone purchases HXP using HORSE event HXPPurchased(address account, uint256 amount); /// @dev address of the HRSYToken IHRSYToken public HRSYToken; /// @dev race winner validation access interface IRaceValidator public validator; /// @dev Maps the values table for upgrading, burning, etc mapping(bytes32 => uint256) public config; /// @dev Maps a user to his wins count, used for claiming with RWRD HRSY mapping(address => uint16) public wins; /// @dev Maps an HRSY id to the wins counter value when last claimed reward mapping(uint256 => uint16) public rewarded; /// @dev Devs cut is the amount of HORSE earned by devs through their equity uint256 devCut; uint256 constant HORSE = 10**18; /** @dev Contracts constructor Initializes token data is pausable,ownable @param tokenAddress Address of the official HRSYToken contract @param validatorAddress Address of the current contract used for race validation @param walletAddress Address of the current wallet contract */ constructor(address tokenAddress, address validatorAddress, address walletAddress) WalletUser(walletAddress) Pausable() Ownable() public { require(validatorAddress != address(0) && tokenAddress != address(0),"Invalid addresses"); HRSYToken = IHRSYToken(tokenAddress); validator = IRaceValidator(validatorAddress); //setting default values //% config["CONVRATE"] = 3; config["CONVFEE"] = 9; config["DEVEQ1"] = 10; //10% for the devs from the CONVFEE config["DEVEQ2"] = 20; //20% for the devs from operation fees config["CREATOREQ"] = 20; //20% HORSE goes to the RWRD HRSY creator //HORSE //Amount of HORSE required to claim and rename a token config["CLAIMFEE"] = 10 * HORSE; config["RENAMEFEE"] = 5 * HORSE; //Amount of HORSE sent to the player FOR EACH Reward HRSY when he wins //depends on the HRSY lvl (minimum lvl 3 required for RWRD0) config["RWRD0"] = 500 * HORSE; config["RWRD1"] = 1500 * HORSE; config["RWRD2"] = 3000 * HORSE; //Amount of HORSE required to burn a normal and a rare HRSY config["BURNFEE0"] = 2 * HORSE; config["BURNFEE1"] = 10 * HORSE; //Amount of HORSE required to lvl up an HRSY config["UPGRFEE"] = 50 * HORSE; //HXP //Burning rewards in HXP for a normal and a rare HRSY config["BURN0"] = 1000; config["BURN1"] = 5000; //Allows to multiply the reward for burning based on the bet amount. //BURNMULT is a /100 ratio config["BURNMULT"] = 100; config["MINBET"] = 0.01 ether; config["MAXBET"] = 1 ether; //minimum bet multiplier config["BETMULT"] = 200; //Upgrade costs in HXP for all lvls config["UPGR0"] = 5000; config["UPGR1"] = 200000; config["UPGR2"] = 800000; config["UPGR3"] = 1200000; //begin and start timestamps of bonus period config["BPERIODBEGIN"] = 1538517600; // October 3th 2018 config["BPERIODEND"] = 1543618800; // December 1st 2018 //bonus period multiplier in % config["BONUSMULT"] = 200; } /** @dev Change wallet address @param validatorAddress the new address */ function setValidator(address validatorAddress) external validAddress(validatorAddress) onlyOwner() { validator = IRaceValidator(validatorAddress); } /** @dev Changes the amount of horse required to upgrade a horsey @param name Name of the value to change @param newValue The new value */ function setConfigValue(bytes32 name, uint256 newValue) external onlyOwner() { config[name] = newValue; } /** @dev Owner can withdraw the current HORSE balance */ function withdraw() external onlyOwner() { if(devCut > 0) { _wallet.withdrawPool(devCut); //get all the HORSE we earned from the wallet //send them to our owner uint256 toSend = devCut; devCut = 0; _horseToken.transfer(owner(),toSend); } } /** @dev Returns horsey data of a given token @param tokenId ID of the horsey to fetch @return (race address, dna, upgradeCounter, name) */ function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string, uint32) { bytes32 dna; address race; uint32 betAmountFinney; uint8 upgradeCounter; (dna, race, betAmountFinney, upgradeCounter) = HRSYToken.horseys(tokenId); return (race,dna,upgradeCounter,HRSYToken.names(tokenId),betAmountFinney); } /** @dev Claiming HORSE from a reward HRSY @param tokenId ID of the RWRD HRSY */ function claimRWRD(uint256 tokenId) external whenNotPaused() onlyOwnerOf(tokenId) { address originalOwner = HRSYToken.owners(tokenId); //compute the amount of unclaimed wins require(rewarded[tokenId] <= wins[originalOwner],"rewarded > wins"); uint256 amount = wins[originalOwner] - rewarded[tokenId]; if (amount > 0) { uint8 upgradeCounter; (,,,upgradeCounter) = HRSYToken.horseys(tokenId); require(upgradeCounter > 1,"You must upgrade this HRSY before claiming"); //set this to the current counter to prevent claiming multiple times from same wins rewarded[tokenId] = wins[originalOwner]; uint256 horseAmount = _getSelectRWRD(upgradeCounter).mul(amount); //credit the original creator some HORSE uint256 creatorDue = horseAmount.div(100).mul(config["CREATOREQ"]); if(creatorDue > 0) { _wallet.transferFromAndTo(address(_wallet),originalOwner,creatorDue); } //credit user the HORSE _wallet.transferFromAndTo(address(_wallet),msg.sender,horseAmount.sub(creatorDue)); emit RewardClaimed(tokenId,msg.sender,horseAmount); } } /** @dev Claiming HORSE from multiple reward HRSY @param tokenIds Array of ID of the token to burn */ function claimMultRWRD(uint256[] tokenIds) external whenNotPaused() { uint256 totalHorseAmount = 0; //first try to claim from all tokens uint arrayLength = tokenIds.length; require(arrayLength <= 10, "Maximum 10 at a time"); for (uint i = 0; i < arrayLength; i++) { require(HRSYToken.ownerOf(tokenIds[i]) == msg.sender, "Caller is not owner of this token"); address originalOwner = HRSYToken.owners(tokenIds[i]); //compute the amount of unclaimed wins if(wins[originalOwner] > rewarded[tokenIds[i]]) { //admissible for rewards uint256 amount = wins[originalOwner] - rewarded[tokenIds[i]]; uint8 upgradeCounter; (,,,upgradeCounter) = HRSYToken.horseys(tokenIds[i]); require(upgradeCounter > 1,"You must upgrade this HRSY before claiming"); //set this to the current counter to prevent claiming multiple times from same wins rewarded[tokenIds[i]] = wins[originalOwner]; uint256 horseRewardAmount = 0; if(upgradeCounter == 2) { horseRewardAmount = config["RWRD0"].mul(amount); } else if(upgradeCounter == 3) { horseRewardAmount = config["RWRD1"].mul(amount); } else if(upgradeCounter == 4) { horseRewardAmount = config["RWRD2"].mul(amount); } uint256 creatorDue = horseRewardAmount.div(100).mul(config["CREATOREQ"]); if(creatorDue > 0) { _wallet.transferFromAndTo(address(_wallet),originalOwner,creatorDue); } totalHorseAmount = totalHorseAmount.add(horseRewardAmount.sub(creatorDue)); emit RewardClaimed(tokenIds[i],msg.sender,totalHorseAmount); } } if(totalHorseAmount > 0) { //credit user the HORSE _wallet.transferFromAndTo(address(_wallet),msg.sender,totalHorseAmount); } } /** @dev Allows a user to claim an HRSY for a fee in HORSE Cant be used on paused The sender has to be a winner of the race and must never have claimed a horsey from this race @param raceAddress The race's address */ function claim(address raceAddress) external whenNotPaused() { //check that the user won bytes32 winner; bool res; uint256 betAmount; uint256 totalBetAmount; (res,winner,betAmount,totalBetAmount) = validator.validateWinner(raceAddress, msg.sender); require(res,"validateWinner returned false"); //check that the user bet enough uint16 rewardHorseyCount = HRSYToken.count(msg.sender); uint256 minBet = config["MINBET"]; if(rewardHorseyCount > 0) { //the minimal bet is based on the amount of reward horseys //use the 2x function 0.01 0.02 0.04 0.08 0.16 0.32 0.64 1.25 minBet = rewardHorseyCount.mul(config["MINBET"].div(100).mul(config["BETMULT"])); } //make sure he respected the minimal bet amount require(totalBetAmount >= minBet,"You didnt bet enough and cant claim from this race!"); uint256 poolFee = config["CLAIMFEE"]; //get the HORSE from user account _processPayment(msg.sender,poolFee); //unique property is already be checked by minting function uint256 id = _generate_horsey(raceAddress, msg.sender, winner, betAmount); require(!HRSYToken.cemetery(id),"This horsey was already claimed and burned"); //add this to the users wins counter wins[msg.sender] = wins[msg.sender].add(1); emit Claimed(raceAddress, msg.sender, id); } /** @dev Allows a user to claim a list of HRSY tokens for a fee in HORSE Reduces a bit the gas cost per token Cant be used on paused The sender has to be a winner of the race and must never have claimed a horsey from this race @param raceContractIds Array of races addresses */ function claimMult(address[] raceContractIds) external whenNotPaused() { //useful variables bytes32 winner; bool res; uint256 betAmount; uint256 totalBetAmount; //first try to claim all tokens uint arrayLength = raceContractIds.length; require(arrayLength <= 10, "Maximum 10 at a time"); uint16 length = uint16(arrayLength); for (uint i = 0; i < arrayLength; i++) { //check that the user won (res,winner,betAmount,totalBetAmount) = validator.validateWinner(raceContractIds[i], msg.sender); require(res,"validateWinner returned false"); //check that the user bet enough uint16 rewardHorseyCount = HRSYToken.count(msg.sender); uint256 minBet = config["MINBET"]; if(rewardHorseyCount > 0) { //the minimal bet is based on the amount of reward horseys //use the 2x function 0.01 0.02 0.04 0.08 0.16 0.32 0.64 1.25 minBet = rewardHorseyCount.mul(config["MINBET"].div(100).mul(config["BETMULT"])); } //make sure he respected the minimal bet amount require(totalBetAmount >= minBet,"You didnt bet enough and cant claim from this race!"); //unique property is already be checked by minting function uint256 id = _generate_horsey(raceContractIds[i], msg.sender, winner, betAmount); emit Claimed(raceContractIds[i], msg.sender, id); } //add this to the users wins counter wins[msg.sender] = wins[msg.sender].add(length); //now process the payment uint256 poolFee = config["CLAIMFEE"]; //get the HORSE from user account _processPayment(msg.sender,poolFee*arrayLength); } /** @dev Allows a user to give a horsey a name or rename it This functions' cost is renamingFeePerChar * length(newname) Cant be called while paused @param tokenId ID of the horsey to rename @param newName The name to give to the horsey */ function rename(uint256 tokenId, string newName) external whenNotPaused() onlyOwnerOf(tokenId) { uint256 renamingFee = config["RENAMEFEE"].mul(bytes(newName).length); uint256 poolFee = renamingFee; //get the HORSE from user account _processPayment(msg.sender,poolFee); //store the new name HRSYToken.storeName(tokenId,newName); emit Renamed(tokenId,newName); } /** @dev Allows a user to burn a token he owns to get HORSE Cant be called while paused @param tokenId ID of the token to burn */ function burn(uint256 tokenId) external whenNotPaused() onlyOwnerOf(tokenId) { uint8 upgradeCounter; address contractId; uint32 betAmountFinney; (,contractId,betAmountFinney,upgradeCounter) = HRSYToken.horseys(tokenId); uint256 betAmount = uint256(_shiftLeft(bytes32(betAmountFinney),15)); uint amountHXP = 0; uint fee = 0; if(upgradeCounter == 0) { amountHXP = config["BURN0"]; fee = config["BURNFEE0"]; } else if(upgradeCounter == 1) { amountHXP = config["BURN1"]; fee = config["BURNFEE1"]; } else { revert("You can't burn this token"); } //if the bet is superior to minimal bet an HXP bonus could apply if((betAmount >= config["MINBET"])) { uint256 maxBonus = config["MAXBET"].div(100).mul(config["BURNMULT"]); uint burnBonus = betAmount.div(config["MAXBET"]).mul(maxBonus); //clamp the HXP bonus if(burnBonus > maxBonus) { burnBonus = maxBonus; } amountHXP = amountHXP + burnBonus; } uint32 timestamp = validator.getRaceTime(contractId); //SPECIAL CODE FOR BONUS PERIOD if((timestamp > config["BPERIODBEGIN"]) && (timestamp < config["BPERIODEND"])) { amountHXP = amountHXP.div(100).mul(config["BONUSMULT"]); } //destroy horsey HRSYToken.unstoreHorsey(tokenId); //credit this user HORSE from the HORSE fund _wallet.creditHXP(msg.sender,amountHXP); uint256 poolFee = fee; //get the HORSE from user account _processPayment(msg.sender,poolFee); emit Burned(tokenId); } /** @dev Allows a user to burn multiple tokens at once Cant be called while paused @param tokenIds Array of ID of the token to burn */ function burnMult(uint256[] tokenIds) external whenNotPaused() { //used multiple times uint8 upgradeCounter; address contractId; uint32 betAmountFinney; uint256 totalAmountHXP = 0; uint256 totalPoolFee = 0; require(tokenIds.length <= 10, "Maximum 10 at a time"); //first try to burn all tokens for (uint i = 0; i < tokenIds.length; i++) { require(HRSYToken.ownerOf(tokenIds[i]) == msg.sender, "Caller is not owner of this token"); (,contractId,betAmountFinney,upgradeCounter) = HRSYToken.horseys(tokenIds[i]); uint256 betAmount = uint256(_shiftLeft(bytes32(betAmountFinney),15)); uint amountHXP = 0; if(upgradeCounter == 0) { amountHXP = config["BURN0"]; totalPoolFee = totalPoolFee.add(config["BURNFEE0"]); } else if(upgradeCounter == 1) { amountHXP = config["BURN1"]; totalPoolFee = totalPoolFee.add(config["BURNFEE1"]); } else { revert("You can't burn this token"); } //if the bet is superior to minimal bet an HXP bonus could apply if((betAmount >= config["MINBET"])) { uint256 maxBonus = config["MAXBET"].div(100).mul(config["BURNMULT"]); uint burnBonus = betAmount.div(config["MAXBET"]).mul(maxBonus); //clamp the HXP bonus if(burnBonus > maxBonus) { burnBonus = maxBonus; } amountHXP = amountHXP + burnBonus; } uint32 timestamp = validator.getRaceTime(contractId); //SPECIAL CODE FOR BONUS PERIOD if((timestamp > config["BPERIODBEGIN"]) && (timestamp < config["BPERIODEND"])) { amountHXP = amountHXP.div(100).mul(config["BONUSMULT"]); } //destroy horsey HRSYToken.unstoreHorsey(tokenIds[i]); totalAmountHXP = totalAmountHXP.add(amountHXP); emit Burned(tokenIds[i]); } //get the HORSE from user account _processPayment(msg.sender,totalPoolFee); //credit this user HXP for all the HRSY he burned _wallet.creditHXP(msg.sender,totalAmountHXP); } /** @dev Allows to upgrade a horsey to increase its upgradeCounter value Cant be called while paused @param tokenId ID of the horsey to upgrade */ function upgrade(uint256 tokenId) external whenNotPaused() onlyOwnerOf(tokenId) { uint8 upgradeCounter; (,,,upgradeCounter) = HRSYToken.horseys(tokenId); uint amountHXP = 0; if(upgradeCounter == 0) { //create a "rare" HRSY amountHXP = config["UPGR0"]; } else if(upgradeCounter == 1) { //create a "reward" HRSY amountHXP = config["UPGR1"]; //this is a new RWRD HRSY, store the Original Owner HRSYToken.storeOwner(tokenId,msg.sender); //and increase his RWRD count HRSYToken.storeCount(msg.sender,HRSYToken.count(msg.sender)+1); } else if(upgradeCounter == 2) { //upgrade a "reward" HRSY to lvl 2 amountHXP = config["UPGR2"]; } else if(upgradeCounter == 3) { //upgrade a "reward" HRSY to lvl 3 amountHXP = config["UPGR3"]; } else { revert("token already at maximum"); } //make sure we wont lose any rewards by upgrading a HRSY with left wins to claim if(upgradeCounter >= 2) { require(rewarded[tokenId] == wins[msg.sender],"You must claim your rewards before upgrading"); } //set this to the current counter value every time a RWRD HRSY is created or upgraded to prevent claiming from past races if(upgradeCounter >= 1) { rewarded[tokenId] = wins[msg.sender]; } //update the HRSY level HRSYToken.modifyHorseyUpgradeCounter(tokenId,upgradeCounter+1); //consume the required HXP require(_wallet.balanceOfHXP(msg.sender) >= amountHXP,"Insufficient HXP funds"); _wallet.spendHXP(msg.sender,amountHXP); uint256 poolFee = config["UPGRFEE"]; //get the HORSE from user account _processPayment(msg.sender,poolFee); emit Upgraded(tokenId); } /** @dev Allows to purchase HXP using HORSE @param amount Amount of HXP to buy */ function purchaseHXP(uint256 amount) external whenNotPaused() { require(amount > 0,"You must purchase at least 1 HXP"); uint256 horseAmount = amount.div(config["CONVRATE"]); uint256 fee = (horseAmount.div(100).mul(config["CONVFEE"])); uint256 total = fee.add(horseAmount); //small part of the pool belongs to dev, store this amount here devCut = devCut.add(fee.div(100).mul(config["DEVEQ1"])); require(_wallet.balanceOf(msg.sender) >= total,"Insufficient HORSE funds"); _wallet.transferFromAndTo(msg.sender,address(_wallet),total); _wallet.creditHXP(msg.sender,amount); emit HXPPurchased(msg.sender,amount); } /** @dev Returns the right RWRD amount based on the upgradeCounter @param upgradeCounter the current amount of times the HRSY was upgraded */ function _getSelectRWRD(uint8 upgradeCounter) internal returns (uint256) { require(upgradeCounter >= 2 && upgradeCounter <= 4,"Only values between 2 and 4"); if(upgradeCounter == 2) { return config["RWRD0"]; } else if(upgradeCounter == 3) { return config["RWRD1"]; } else if(upgradeCounter == 4) { return config["RWRD2"]; } } /// @dev creates a special token id based on the race and the coin index function _makeId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); } /** @dev Internal function to generate a HRSY token we then use the ERC721 inherited minting process the dna is a bytes32 target for a keccak256. Not using blockhash finaly, a bitmask zeros the first 2 bytes for rarity traits @param race Address of the associated race @param eth_address Address of the user to receive the token @param coinIndex The index of the winning coin @param betAmount Amount bet on this horse @return ID of the token */ function _generate_horsey(address race, address eth_address, bytes32 coinIndex, uint256 betAmount) internal returns (uint256) { uint256 id = _makeId(race, eth_address, coinIndex); //generate dna and leave 0 in the rarity bit bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); //storeHorsey checks if the token exists before minting already, so we dont have to here uint32 betAmountFinney = uint32(_shiftRight(bytes32(betAmount),15)); //store the bet amount in finney not wei to save space HRSYToken.storeHorsey(eth_address,id,race,dna,betAmountFinney,0); return id; } /** @dev Helpers to process payments in HORSE and applying fees */ function _processPayment(address from, uint256 amount) internal { //get the HORSE from user account //dont process if amount is 0 (its allowed though) if(amount > 0) { //small part of the pool belongs to dev, store this amount here devCut = devCut.add(amount.div(100).mul(config["DEVEQ2"])); //fetch the HORSE from the address and credit it _wallet.transferFromAndTo(from,address(_wallet),amount); } } /// @dev shifts a bytes32 right by n positions function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { return bytes32(uint256(data).div(2 ** n)); } /// @dev shifts a bytes32 left by n positions function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { return bytes32(uint256(data).div(2 ** n)); } /// @dev requires the address to be non null modifier validAddress(address addr) { require(addr != address(0),"Address is zero"); _; } /// @dev requires that the user isnt feeding a horsey already modifier onlyOwnerOf(uint256 tokenId) { require(HRSYToken.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); _; } }
December 1st 2018
config["BPERIODEND"] = 1543618800;
13,020,852
[ 1, 758, 311, 81, 744, 404, 334, 14863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 642, 9614, 38, 28437, 4415, 11929, 273, 4711, 24, 5718, 2643, 17374, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; contract Election { //model a candidate struct Candidate{ //structure type uint id; //unsigned int string name; uint voteCount; } //store candidate mapping(uint => Candidate) public candidates; //hashmap (key value pair) //when candidate is added, we are changing the state of our contract and we are writing to the blockchain mapping(address => bool) public voters; //whether a voter has voted or not //default value of the bool is false //store candidate count uint public candidatesCount; //to keep track of number of candidates because you cannot say candidates.size // constructor constructor() public{ //this will be executed when the contract is migrated and deployed addCandidate("Candidate 1"); addCandidate("Candidate 2"); } function addCandidate(string memory _name) private { //local variable prepended with an underscore candidatesCount++; candidates[candidatesCount] = Candidate(candidatesCount, _name, 0); //instantiate a structure //vote count 0 initially } function vote(uint _candidateId) public{ //require that they have not voted before require(!voters[msg.sender]); //require function - if we get true then the following code is executed else the execution stops //simiar to //if(condition) // return //require a valid candidate require(_candidateId > 0 && _candidateId <= candidatesCount); //if the candidate votes for an invalid candidate then the gas will not be returned or if there is any bug in the code that converts valid to an invalid candidate, the user will suffer gas loss. So ensure that the contract is bug free. //if require is found false, then the gas used uptill this part will not be returned back. Ofcourse, no gas will be used for the code below because that code wont be executed. //record that voter has voted //we can get metadata which will have the data (address) of the person calling this function voters[msg.sender] = true; //sender is the account //update vote count candidates[_candidateId].voteCount ++; } }
require that they have not voted beforesimiar toif(condition) returnrequire a valid candidateif require is found false, then the gas used uptill this part will not be returned back. Ofcourse, no gas will be used for the code below because that code wont be executed.record that voter has votedwe can get metadata which will have the data (address) of the person calling this functionupdate vote count
function vote(uint _candidateId) public{ candidates[_candidateId].voteCount ++; }
2,508,962
[ 1, 6528, 716, 2898, 1240, 486, 331, 16474, 506, 617, 455, 381, 77, 297, 358, 430, 12, 4175, 13, 225, 327, 6528, 279, 923, 5500, 430, 2583, 353, 1392, 629, 16, 1508, 326, 16189, 1399, 582, 337, 737, 333, 1087, 903, 486, 506, 2106, 1473, 18, 8031, 5566, 16, 1158, 16189, 903, 506, 1399, 364, 326, 981, 5712, 2724, 716, 981, 341, 1580, 506, 7120, 18, 3366, 716, 331, 20005, 711, 331, 16474, 1814, 848, 336, 1982, 1492, 903, 1240, 326, 501, 261, 2867, 13, 434, 326, 6175, 4440, 333, 445, 2725, 12501, 1056, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 12501, 12, 11890, 389, 19188, 548, 13, 1071, 95, 203, 202, 377, 203, 1082, 203, 203, 203, 203, 203, 202, 202, 21635, 63, 67, 19188, 548, 8009, 25911, 1380, 965, 31, 203, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.18; /** Used for administrration of the VZT Token Contract */ contract Administration { // keeps track of the contract owner address public owner; // keeps track of the contract administrator address public administrator; // keeps track of hte song token exchange address public songTokenExchange; // keeps track of the royalty information contract address public royaltyInformationContract; // keeps track of whether or not the admin contract is frozen bool public administrationContractFrozen; // keeps track of the contract moderators mapping (address =&gt; bool) public moderators; event ModeratorAdded(address indexed _invoker, address indexed _newMod, bool indexed _newModAdded); event ModeratorRemoved(address indexed _invoker, address indexed _removeMod, bool indexed _modRemoved); event AdministratorAdded(address indexed _invoker, address indexed _newAdmin, bool indexed _newAdminAdded); event RoyaltyInformationContractSet(address indexed _invoker, address indexed _newRoyaltyContract, bool indexed _newRoyaltyContractSet); event SongTokenExchangeContractSet(address indexed _invoker, address indexed _newSongTokenExchangeContract, bool indexed _newSongTokenExchangeSet); function Administration() { owner = 0x79926C875f2636808de28CD73a45592587A537De; administrator = 0x79926C875f2636808de28CD73a45592587A537De; administrationContractFrozen = false; } /// @dev checks to see if the contract is frozen modifier isFrozen() { require(administrationContractFrozen); _; } /// @dev checks to see if the contract is not frozen modifier notFrozen() { require(!administrationContractFrozen); _; } /// @dev checks to see if the msg.sender is owner modifier onlyOwner() { require(msg.sender == owner); _; } /// @dev checks to see if msg.sender is owner, or admin modifier onlyAdmin() { require(msg.sender == owner || msg.sender == administrator); _; } /// @dev checks to see if msg.sender is owner, admin, or song token exchange modifier onlyAdminOrExchange() { require(msg.sender == owner || msg.sender == songTokenExchange || msg.sender == administrator); _; } /// @dev checks to see if msg.sender is privileged modifier onlyModerator() { if (msg.sender == owner) {_;} if (msg.sender == administrator) {_;} if (moderators[msg.sender]) {_;} } /// @notice used to freeze the administration contract function freezeAdministrationContract() public onlyAdmin notFrozen returns (bool frozen) { administrationContractFrozen = true; return true; } /// @notice used to unfreeze the administration contract function unfreezeAdministrationContract() public onlyAdmin isFrozen returns (bool unfrozen) { administrationContractFrozen = false; return true; } /// @notice used to set the royalty information contract function setRoyaltyInformationContract(address _royaltyInformationContract) public onlyAdmin notFrozen returns (bool set) { royaltyInformationContract = _royaltyInformationContract; RoyaltyInformationContractSet(msg.sender, _royaltyInformationContract, true); return true; } /// @notice used to set the song token exchange function setTokenExchange(address _songTokenExchange) public onlyAdmin notFrozen returns (bool set) { songTokenExchange = _songTokenExchange; SongTokenExchangeContractSet(msg.sender, _songTokenExchange, true); return true; } /// @notice used to add a moderator function addModerator(address _newMod) public onlyAdmin notFrozen returns (bool success) { moderators[_newMod] = true; ModeratorAdded(msg.sender, _newMod, true); return true; } /// @notice used to remove a moderator function removeModerator(address _removeMod) public onlyAdmin notFrozen returns (bool success) { moderators[_removeMod] = false; ModeratorRemoved(msg.sender, _removeMod, true); return true; } /// @notice used to set an administrator function setAdministrator(address _administrator) public onlyOwner notFrozen returns (bool success) { administrator = _administrator; AdministratorAdded(msg.sender, _administrator, true); return true; } /// @notice used to transfer contract ownership function transferOwnership(address _newOwner) public onlyOwner notFrozen returns (bool success) { owner = _newOwner; return true; } } 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) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b &lt;= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c &gt;= a); return c; } } /** Version: 1.0.1 */ contract Vezt is Administration { using SafeMath for uint256; uint256 public totalSupply; uint8 public decimals; string public name; string public symbol; bool public tokenTransfersFrozen; bool public tokenMintingEnabled; bool public contractLaunched; mapping (address =&gt; uint256) public balances; mapping (address =&gt; mapping (address =&gt; uint256)) public allowed; event Transfer(address indexed _sender, address indexed _recipient, uint256 _amount); event Approve(address indexed _owner, address indexed _spender, uint256 _amount); event LaunchContract(address indexed _launcher, bool _launched); event FreezeTokenTransfers(address indexed _invoker, bool _frozen); event ThawTokenTransfers(address indexed _invoker, bool _thawed); event MintTokens(address indexed _minter, uint256 _amount, bool indexed _minted); event TokenMintingDisabled(address indexed _invoker, bool indexed _disabled); event TokenMintingEnabled(address indexed _invoker, bool indexed _enabled); event SongTokenAdded(address indexed _songTokenAddress, bool indexed _songTokenAdded); event SongTokenRemoved(address indexed _songTokenAddress, bool indexed _songTokenRemoved); function Vezt() { name = &quot;Vezt&quot;; symbol = &quot;VZT&quot;; decimals = 18; totalSupply = 125000000000000000000000000; balances[0x79926C875f2636808de28CD73a45592587A537De] = balances[0x79926C875f2636808de28CD73a45592587A537De].add(totalSupply); tokenTransfersFrozen = true; tokenMintingEnabled = false; contractLaunched = false; } /** @dev Used by admin to send bulk amount of transfers, primary purpose to replay tx from the crowdfund to make it easier to do bulk sending @notice Can also be used for general bulk transfers via the associated python script */ function transactionReplay(address _receiver, uint256 _amount) public onlyOwner returns (bool replayed) { require(transferCheck(msg.sender, _receiver, _amount)); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_receiver] = balances[_receiver].add(_amount); Transfer(msg.sender, _receiver, _amount); return true; } /** @notice Used to launch the contract */ function launchContract() public onlyOwner returns (bool launched) { require(!contractLaunched); tokenTransfersFrozen = false; tokenMintingEnabled = true; contractLaunched = true; LaunchContract(msg.sender, true); return true; } /** @notice Used to disable token minting */ function disableTokenMinting() public onlyOwner returns (bool disabled) { tokenMintingEnabled = false; TokenMintingDisabled(msg.sender, true); return true; } /** @notice Used to enable token minting */ function enableTokenMinting() public onlyOwner returns (bool enabled) { tokenMintingEnabled = true; TokenMintingEnabled(msg.sender, true); return true; } /** @notice Used to freeze token transfers */ function freezeTokenTransfers() public onlyOwner returns (bool frozen) { tokenTransfersFrozen = true; FreezeTokenTransfers(msg.sender, true); return true; } /** @notice Used to thaw token tra4nsfers */ function thawTokenTransfers() public onlyOwner returns (bool thawed) { tokenTransfersFrozen = false; ThawTokenTransfers(msg.sender, true); return true; } /** @notice Used to transfer funds */ function transfer(address _receiver, uint256 _amount) public returns (bool transferred) { require(transferCheck(msg.sender, _receiver, _amount)); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_receiver] = balances[_receiver].add(_amount); Transfer(msg.sender, _receiver, _amount); return true; } /** @notice Used to transfer funds on behalf of someone */ function transferFrom(address _owner, address _receiver, uint256 _amount) public returns (bool transferred) { require(allowed[_owner][msg.sender] &gt;= _amount); require(transferCheck(_owner, _receiver, _amount)); allowed[_owner][msg.sender] = allowed[_owner][msg.sender].sub(_amount); balances[_owner] = balances[_owner].sub(_amount); balances[_receiver] = balances[_receiver].add(_amount); Transfer(_owner, _receiver, _amount); return true; } /** @notice Used to approve someone to spend funds on your behalf */ function approve(address _spender, uint256 _amount) public returns (bool approved) { require(_amount &gt; 0); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_amount); Approve(msg.sender, _spender, _amount); return true; } /** @notice Used to burn tokens */ function tokenBurner(uint256 _amount) public onlyOwner returns (bool burned) { require(_amount &gt; 0); require(totalSupply.sub(_amount) &gt;= 0); require(balances[msg.sender] &gt;= _amount); require(balances[msg.sender].sub(_amount) &gt;= 0); totalSupply = totalSupply.sub(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); Transfer(msg.sender, 0, _amount); return true; } /** @notice Used to mint new tokens */ function tokenFactory(uint256 _amount) public onlyOwner returns (bool minted) { // this calls the token minter function which is used to do a sanity check of the parameters being passed in require(tokenMinter(_amount, msg.sender)); totalSupply = totalSupply.add(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); Transfer(0, msg.sender, _amount); return true; } // Internals /** @dev Low level function used to do a sanity check of minting params */ function tokenMinter(uint256 _amount, address _sender) internal view returns (bool valid) { require(tokenMintingEnabled); require(_amount &gt; 0); require(_sender != address(0x0)); require(totalSupply.add(_amount) &gt; 0); require(totalSupply.add(_amount) &gt; totalSupply); require(balances[_sender].add(_amount) &gt; 0); require(balances[_sender].add(_amount) &gt; balances[_sender]); return true; } /** @dev Prevents people from sending to a a null address @notice Low level function used to do a sanity check of transfer parameters */ function transferCheck(address _sender, address _receiver, uint256 _amount) internal view returns (bool valid) { require(!tokenTransfersFrozen); require(_amount &gt; 0); require(_receiver != address(0)); require(balances[_sender] &gt;= _amount); // added check require(balances[_sender].sub(_amount) &gt;= 0); require(balances[_receiver].add(_amount) &gt; 0); require(balances[_receiver].add(_amount) &gt; balances[_receiver]); return true; } // Getters /** @notice Used to retrieve total supply */ function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } /** @notice Used to retrieve balance of a user */ function balanceOf(address _person) public view returns (uint256 _balanceOf) { return balances[_person]; } /** @notice Used to retrieve the allowed balance of someone */ function allowance(address _owner, address _spender) public view returns (uint256 _allowance) { return allowed[_owner][_spender]; } }
@dev checks to see if msg.sender is privileged
modifier onlyModerator() { }
7,308,404
[ 1, 12366, 358, 2621, 309, 1234, 18, 15330, 353, 11334, 2423, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 1338, 1739, 7385, 1435, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xA0F7f51836069dbF1f60eC06A49dda404F9De45c/sources/ERC721Upstream.sol
* @notice Put a token up for sale. @param tokenId The unique id of the NFT. @param price The Ether price being asked (1 is 1x10^18)./
function offer(uint256 tokenId, uint256 price) public { require(_msgSender() == ownerOf(tokenId), "You do not own this token"); if(price == 0) orderBook[tokenId] = Order(address(0), price); else orderBook[tokenId] = Order(_msgSender(), price); }
9,279,921
[ 1, 6426, 279, 1147, 731, 364, 272, 5349, 18, 225, 1147, 548, 1021, 3089, 612, 434, 326, 423, 4464, 18, 225, 6205, 1021, 512, 1136, 6205, 3832, 19279, 261, 21, 353, 404, 92, 2163, 66, 2643, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10067, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 6205, 13, 1071, 288, 203, 3639, 2583, 24899, 3576, 12021, 1435, 422, 3410, 951, 12, 2316, 548, 3631, 315, 6225, 741, 486, 4953, 333, 1147, 8863, 203, 203, 3639, 309, 12, 8694, 422, 374, 13, 203, 5411, 1353, 9084, 63, 2316, 548, 65, 273, 4347, 12, 2867, 12, 20, 3631, 6205, 1769, 203, 3639, 469, 203, 5411, 1353, 9084, 63, 2316, 548, 65, 273, 4347, 24899, 3576, 12021, 9334, 6205, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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: AGPL-3.0 pragma solidity ^0.8.2; import "./IEverscale.sol"; pragma experimental ABIEncoderV2; interface IBridge is IEverscale { struct Round { uint32 end; uint32 ttl; uint32 relays; uint32 requiredSignatures; } function updateMinimumRequiredSignatures(uint32 _minimumRequiredSignatures) external; function setConfiguration(EverscaleAddress calldata _roundRelaysConfiguration) external; function updateRoundTTL(uint32 _roundTTL) external; function isRelay( uint32 round, address candidate ) external view returns (bool); function isBanned( address candidate ) external view returns (bool); function isRoundRotten( uint32 round ) external view returns (bool); function verifySignedEverscaleEvent( bytes memory payload, bytes[] memory signatures ) external view returns (uint32); function setRoundRelays( bytes calldata payload, bytes[] calldata signatures ) external; function forceRoundRelays( uint160[] calldata _relays, uint32 roundEnd ) external; function banRelays( address[] calldata _relays ) external; function unbanRelays( address[] calldata _relays ) external; function pause() external; function unpause() external; function setRoundSubmitter(address _roundSubmitter) external; event EmergencyShutdown(bool active); event UpdateMinimumRequiredSignatures(uint32 value); event UpdateRoundTTL(uint32 value); event UpdateRoundRelaysConfiguration(EverscaleAddress configuration); event UpdateRoundSubmitter(address _roundSubmitter); event NewRound(uint32 indexed round, Round meta); event RoundRelay(uint32 indexed round, address indexed relay); event BanRelay(address indexed relay, bool status); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; pragma experimental ABIEncoderV2; interface IERC20Metadata { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; interface IEverscale { struct EverscaleAddress { int128 wid; uint256 addr; } struct EverscaleEvent { uint64 eventTransactionLt; uint32 eventTimestamp; bytes eventData; int8 configurationWid; uint256 configurationAddress; int8 eventContractWid; uint256 eventContractAddress; address proxy; uint32 round; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; interface IStrategy { function vault() external view returns (address); function want() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() external view returns (uint256); function withdraw(uint256 _amountNeeded) external returns (uint256 _loss); function migrate(address newStrategy) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "./IVaultBasic.sol"; interface IVault is IVaultBasic { enum ApproveStatus { NotRequired, Required, Approved, Rejected } struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalSkim; uint256 totalLoss; address rewardsManager; EverscaleAddress rewards; } struct PendingWithdrawalParams { uint256 amount; uint256 bounty; uint256 timestamp; ApproveStatus approveStatus; } struct PendingWithdrawalId { address recipient; uint256 id; } struct WithdrawalPeriodParams { uint256 total; uint256 considered; } function initialize( address _token, address _bridge, address _governance, uint _targetDecimals, EverscaleAddress memory _rewards ) external; function withdrawGuardian() external view returns (address); function pendingWithdrawalsPerUser(address user) external view returns (uint); function pendingWithdrawals( address user, uint id ) external view returns (PendingWithdrawalParams memory); function pendingWithdrawalsTotal() external view returns (uint); function managementFee() external view returns (uint256); function performanceFee() external view returns (uint256); function strategies( address strategyId ) external view returns (StrategyParams memory); function withdrawalQueue() external view returns (address[20] memory); function withdrawLimitPerPeriod() external view returns (uint256); function undeclaredWithdrawLimit() external view returns (uint256); function withdrawalPeriods( uint256 withdrawalPeriodId ) external view returns (WithdrawalPeriodParams memory); function depositLimit() external view returns (uint256); function debtRatio() external view returns (uint256); function totalDebt() external view returns (uint256); function lastReport() external view returns (uint256); function lockedProfit() external view returns (uint256); function lockedProfitDegradation() external view returns (uint256); function setWithdrawGuardian(address _withdrawGuardian) external; function setStrategyRewards( address strategyId, EverscaleAddress memory _rewards ) external; function setLockedProfitDegradation(uint256 degradation) external; function setDepositLimit(uint256 limit) external; function setPerformanceFee(uint256 fee) external; function setManagementFee(uint256 fee) external; function setWithdrawLimitPerPeriod(uint256 _withdrawLimitPerPeriod) external; function setUndeclaredWithdrawLimit(uint256 _undeclaredWithdrawLimit) external; function setWithdrawalQueue(address[20] memory queue) external; function setPendingWithdrawalBounty(uint256 id, uint256 bounty) external; function deposit( EverscaleAddress memory recipient, uint256 amount, PendingWithdrawalId memory pendingWithdrawalId ) external; function deposit( EverscaleAddress memory recipient, uint256[] memory amount, PendingWithdrawalId[] memory pendingWithdrawalId ) external; function depositToFactory( uint128 amount, int8 wid, uint256 user, uint256 creditor, uint256 recipient, uint128 tokenAmount, uint128 tonAmount, uint8 swapType, uint128 slippageNumerator, uint128 slippageDenominator, bytes memory level3 ) external; function saveWithdraw( bytes memory payload, bytes[] memory signatures ) external returns ( bool instantWithdrawal, PendingWithdrawalId memory pendingWithdrawalId ); function saveWithdraw( bytes memory payload, bytes[] memory signatures, uint bounty ) external; function cancelPendingWithdrawal( uint256 id, uint256 amount, EverscaleAddress memory recipient, uint bounty ) external; function withdraw( uint256 id, uint256 amountRequested, address recipient, uint256 maxLoss, uint bounty ) external returns(uint256); function addStrategy( address strategyId, uint256 _debtRatio, uint256 minDebtPerHarvest, uint256 maxDebtPerHarvest, uint256 _performanceFee ) external; function updateStrategyDebtRatio( address strategyId, uint256 _debtRatio ) external; function updateStrategyMinDebtPerHarvest( address strategyId, uint256 minDebtPerHarvest ) external; function updateStrategyMaxDebtPerHarvest( address strategyId, uint256 maxDebtPerHarvest ) external; function updateStrategyPerformanceFee( address strategyId, uint256 _performanceFee ) external; function migrateStrategy( address oldVersion, address newVersion ) external; function revokeStrategy( address strategyId ) external; function revokeStrategy() external; function totalAssets() external view returns (uint256); function debtOutstanding(address strategyId) external view returns (uint256); function debtOutstanding() external view returns (uint256); function creditAvailable(address strategyId) external view returns (uint256); function creditAvailable() external view returns (uint256); function availableDepositLimit() external view returns (uint256); function expectedReturn(address strategyId) external view returns (uint256); function report( uint256 profit, uint256 loss, uint256 _debtPayment ) external returns (uint256); function skim(address strategyId) external; function forceWithdraw( PendingWithdrawalId memory pendingWithdrawalId ) external; function forceWithdraw( PendingWithdrawalId[] memory pendingWithdrawalId ) external; function setPendingWithdrawalApprove( PendingWithdrawalId memory pendingWithdrawalId, ApproveStatus approveStatus ) external; function setPendingWithdrawalApprove( PendingWithdrawalId[] memory pendingWithdrawalId, ApproveStatus[] memory approveStatus ) external; event PendingWithdrawalUpdateBounty(address recipient, uint256 id, uint256 bounty); event PendingWithdrawalCancel(address recipient, uint256 id, uint256 amount); event PendingWithdrawalForce(address recipient, uint256 id); event PendingWithdrawalCreated( address recipient, uint256 id, uint256 amount, bytes32 payloadId ); event PendingWithdrawalWithdraw( address recipient, uint256 id, uint256 requestedAmount, uint256 redeemedAmount ); event PendingWithdrawalUpdateApproveStatus( address recipient, uint256 id, ApproveStatus approveStatus ); event UpdateWithdrawLimitPerPeriod(uint256 withdrawLimitPerPeriod); event UpdateUndeclaredWithdrawLimit(uint256 undeclaredWithdrawLimit); event UpdateDepositLimit(uint256 depositLimit); event UpdatePerformanceFee(uint256 performanceFee); event UpdateManagementFee(uint256 managenentFee); event UpdateWithdrawGuardian(address withdrawGuardian); event UpdateWithdrawalQueue(address[20] queue); event StrategyUpdateDebtRatio(address indexed strategy, uint256 debtRatio); event StrategyUpdateMinDebtPerHarvest(address indexed strategy, uint256 minDebtPerHarvest); event StrategyUpdateMaxDebtPerHarvest(address indexed strategy, uint256 maxDebtPerHarvest); event StrategyUpdatePerformanceFee(address indexed strategy, uint256 performanceFee); event StrategyMigrated(address indexed oldVersion, address indexed newVersion); event StrategyRevoked(address indexed strategy); event StrategyRemovedFromQueue(address indexed strategy); event StrategyAddedToQueue(address indexed strategy); event StrategyReported( address indexed strategy, uint256 gain, uint256 loss, uint256 debtPaid, uint256 totalGain, uint256 totalSkim, uint256 totalLoss, uint256 totalDebt, uint256 debtAdded, uint256 debtRatio ); event StrategyAdded( address indexed strategy, uint256 debtRatio, uint256 minDebtPerHarvest, uint256 maxDebtPerHarvest, uint256 performanceFee ); event StrategyUpdateRewards( address strategyId, int128 wid, uint256 addr ); event UserDeposit( address sender, int128 recipientWid, uint256 recipientAddr, uint256 amount, address withdrawalRecipient, uint256 withdrawalId, uint256 bounty ); event FactoryDeposit( uint128 amount, int8 wid, uint256 user, uint256 creditor, uint256 recipient, uint128 tokenAmount, uint128 tonAmount, uint8 swapType, uint128 slippageNumerator, uint128 slippageDenominator, bytes1 separator, bytes level3 ); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "../IEverscale.sol"; interface IVaultBasic is IEverscale { struct WithdrawalParams { EverscaleAddress sender; uint256 amount; address recipient; uint32 chainId; } function bridge() external view returns (address); function configuration() external view returns (EverscaleAddress memory); function withdrawalIds(bytes32) external view returns (bool); function rewards() external view returns (EverscaleAddress memory); function governance() external view returns (address); function guardian() external view returns (address); function management() external view returns (address); function token() external view returns (address); function targetDecimals() external view returns (uint256); function tokenDecimals() external view returns (uint256); function depositFee() external view returns (uint256); function withdrawFee() external view returns (uint256); function emergencyShutdown() external view returns (bool); function apiVersion() external view returns (string memory api_version); function setDepositFee(uint _depositFee) external; function setWithdrawFee(uint _withdrawFee) external; function setConfiguration(EverscaleAddress memory _configuration) external; function setGovernance(address _governance) external; function acceptGovernance() external; function setGuardian(address _guardian) external; function setManagement(address _management) external; function setRewards(EverscaleAddress memory _rewards) external; function setEmergencyShutdown(bool active) external; function deposit( EverscaleAddress memory recipient, uint256 amount ) external; function decodeWithdrawalEventData( bytes memory eventData ) external view returns(WithdrawalParams memory); function sweep(address _token) external; // Events event Deposit( uint256 amount, int128 wid, uint256 addr ); event InstantWithdrawal( bytes32 payloadId, address recipient, uint256 amount ); event UpdateBridge(address bridge); event UpdateConfiguration(int128 wid, uint256 addr); event UpdateTargetDecimals(uint256 targetDecimals); event UpdateRewards(int128 wid, uint256 addr); event UpdateDepositFee(uint256 fee); event UpdateWithdrawFee(uint256 fee); event UpdateGovernance(address governance); event UpdateManagement(address management); event NewPendingGovernance(address governance); event UpdateGuardian(address guardian); event EmergencyShutdown(bool active); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; pragma experimental ABIEncoderV2; library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libraries/Math.sol"; import "../interfaces/vault/IVault.sol"; import "../interfaces/IBridge.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IERC20Metadata.sol"; import "./VaultHelpers.sol"; string constant API_VERSION = '0.1.7'; /// @title Vault contract. Entry point for the Octus bridge cross chain token transfers. /// @dev Fork of the Yearn Vault V2 contract, rewritten in Solidity. /// @author https://github.com/broxus contract Vault is IVault, VaultHelpers { using SafeERC20 for IERC20; function initialize( address _token, address _bridge, address _governance, uint _targetDecimals, EverscaleAddress memory _rewards ) external override initializer { bridge = _bridge; emit UpdateBridge(bridge); governance = _governance; emit UpdateGovernance(governance); rewards_ = _rewards; emit UpdateRewards(rewards_.wid, rewards_.addr); performanceFee = 0; emit UpdatePerformanceFee(0); managementFee = 0; emit UpdateManagementFee(0); withdrawFee = 0; emit UpdateWithdrawFee(0); depositFee = 0; emit UpdateDepositFee(0); token = _token; tokenDecimals = IERC20Metadata(token).decimals(); targetDecimals = _targetDecimals; } /** @notice Vault API version. Used to track the deployed version of this contract. @return api_version Current API version */ function apiVersion() external override pure returns (string memory api_version) { return API_VERSION; } /** @notice Set deposit fee. Must be less than `MAX_BPS`. This may be called only by `governance` or `management`. @param _depositFee Deposit fee, must be less than `MAX_BPS / 2`. */ function setDepositFee( uint _depositFee ) external override onlyGovernanceOrManagement { require(_depositFee <= MAX_BPS / 2); depositFee = _depositFee; emit UpdateDepositFee(depositFee); } /** @notice Set withdraw fee. Must be less than `MAX_BPS`. This may be called only by `governance` or `management` @param _withdrawFee Withdraw fee, must be less than `MAX_BPS / 2`. */ function setWithdrawFee( uint _withdrawFee ) external override onlyGovernanceOrManagement { require(_withdrawFee <= MAX_BPS / 2); withdrawFee = _withdrawFee; emit UpdateWithdrawFee(withdrawFee); } /// @notice Set configuration_ address. /// @param _configuration The address to use for configuration_. function setConfiguration( EverscaleAddress memory _configuration ) external override onlyGovernance { configuration_ = _configuration; emit UpdateConfiguration(configuration_.wid, configuration_.addr); } /// @notice Nominate new address to use as a governance. /// The change does not go into effect immediately. This function sets a /// pending change, and the governance address is not updated until /// the proposed governance address has accepted the responsibility. /// This may only be called by the `governance`. /// @param _governance The address requested to take over Vault governance. function setGovernance( address _governance ) external override onlyGovernance { pendingGovernance = _governance; emit NewPendingGovernance(pendingGovernance); } /// @notice Once a new governance address has been proposed using `setGovernance`, /// this function may be called by the proposed address to accept the /// responsibility of taking over governance for this contract. /// This may only be called by the `pendingGovernance`. function acceptGovernance() external override onlyPendingGovernance { governance = pendingGovernance; emit UpdateGovernance(governance); } /// @notice Changes the management address. /// This may only be called by `governance` /// @param _management The address to use for management. function setManagement( address _management ) external override onlyGovernance { management = _management; emit UpdateManagement(management); } /// @notice Changes the address of `guardian`. /// This may only be called by `governance` or `guardian`. /// @param _guardian The new guardian address to use. function setGuardian( address _guardian ) external override onlyGovernanceOrGuardian { guardian = _guardian; emit UpdateGuardian(guardian); } /// @notice Changes the address of `withdrawGuardian`. /// This may only be called by `governance` or `withdrawGuardian`. /// @param _withdrawGuardian The new withdraw guardian address to use. function setWithdrawGuardian( address _withdrawGuardian ) external override onlyGovernanceOrWithdrawGuardian { withdrawGuardian = _withdrawGuardian; emit UpdateWithdrawGuardian(withdrawGuardian); } /// @notice Set strategy rewards_ recipient address. /// This may only be called by the `governance` or strategy rewards_ manager. /// @param strategyId Strategy address. /// @param _rewards Rewards recipient. function setStrategyRewards( address strategyId, EverscaleAddress memory _rewards ) external override onlyGovernanceOrStrategyRewardsManager(strategyId) strategyExists(strategyId) { _strategyRewardsUpdate(strategyId, _rewards); emit StrategyUpdateRewards(strategyId, _rewards.wid, _rewards.addr); } /// @notice Set address to receive rewards_ (fees, gains, etc) /// This may be called only by `governance` /// @param _rewards Rewards receiver in Everscale network function setRewards( EverscaleAddress memory _rewards ) external override onlyGovernance { rewards_ = _rewards; emit UpdateRewards(rewards_.wid, rewards_.addr); } /// @notice Changes the locked profit degradation /// @param degradation The rate of degradation in percent per second scaled to 1e18 function setLockedProfitDegradation( uint256 degradation ) external override onlyGovernance { require(degradation <= DEGRADATION_COEFFICIENT); lockedProfitDegradation = degradation; } /// @notice Changes the maximum amount of `token` that can be deposited in this Vault /// Note, this is not how much may be deposited by a single depositor, /// but the maximum amount that may be deposited across all depositors. /// This may be called only by `governance` /// @param limit The new deposit limit to use. function setDepositLimit( uint256 limit ) external override onlyGovernance { depositLimit = limit; emit UpdateDepositLimit(depositLimit); } /// @notice Changes the value of `performanceFee`. /// Should set this value below the maximum strategist performance fee. /// This may only be called by `governance`. /// @param fee The new performance fee to use. function setPerformanceFee( uint256 fee ) external override onlyGovernance { require(fee <= MAX_BPS / 2); performanceFee = fee; emit UpdatePerformanceFee(performanceFee); } /// @notice Changes the value of `managementFee`. /// This may only be called by `governance`. /// @param fee The new management fee to use. function setManagementFee( uint256 fee ) external override onlyGovernance { require(fee <= MAX_BPS); managementFee = fee; emit UpdateManagementFee(managementFee); } /// @notice Changes the value of `withdrawLimitPerPeriod` /// This may only be called by `governance` /// @param _withdrawLimitPerPeriod The new withdraw limit per period to use. function setWithdrawLimitPerPeriod( uint256 _withdrawLimitPerPeriod ) external override onlyGovernance { withdrawLimitPerPeriod = _withdrawLimitPerPeriod; emit UpdateWithdrawLimitPerPeriod(withdrawLimitPerPeriod); } /// @notice Changes the value of `undeclaredWithdrawLimit` /// This may only be called by `governance` /// @param _undeclaredWithdrawLimit The new undeclared withdraw limit to use. function setUndeclaredWithdrawLimit( uint256 _undeclaredWithdrawLimit ) external override onlyGovernance { undeclaredWithdrawLimit = _undeclaredWithdrawLimit; emit UpdateUndeclaredWithdrawLimit(undeclaredWithdrawLimit); } /// @notice Activates or deactivates Vault emergency mode, where all Strategies go into full withdrawal. /// During emergency shutdown: /// - Deposits are disabled /// - Withdrawals are disabled (all types of withdrawals) /// - Each Strategy must pay back their debt as quickly as reasonable to minimally affect their position /// - Only `governance` may undo Emergency Shutdown /// This may only be called by `governance` or `guardian`. /// @param active If `true`, the Vault goes into Emergency Shutdown. If `false`, the Vault goes back into /// Normal Operation. function setEmergencyShutdown( bool active ) external override { if (active) { require(msg.sender == guardian || msg.sender == governance); } else { require(msg.sender == governance); } emergencyShutdown = active; emit EmergencyShutdown(active); } /// @notice Changes `withdrawalQueue` /// This may only be called by `governance` function setWithdrawalQueue( address[20] memory queue ) external override onlyGovernanceOrManagement { withdrawalQueue_ = queue; emit UpdateWithdrawalQueue(withdrawalQueue_); } /** @notice Changes pending withdrawal bounty for specific pending withdrawal @param id Pending withdrawal ID. @param bounty The new value for pending withdrawal bounty. */ function setPendingWithdrawalBounty( uint256 id, uint256 bounty ) public override pendingWithdrawalOpened(PendingWithdrawalId(msg.sender, id)) { PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(PendingWithdrawalId(msg.sender, id)); require(bounty <= pendingWithdrawal.amount); _pendingWithdrawalBountyUpdate(PendingWithdrawalId(msg.sender, id), bounty); } /// @notice Returns the total quantity of all assets under control of this /// Vault, whether they're loaned out to a Strategy, or currently held in /// the Vault. /// @return The total assets under control of this Vault. function totalAssets() external view override returns (uint256) { return _totalAssets(); } function _deposit( EverscaleAddress memory recipient, uint256 amount ) internal { IERC20(token).safeTransferFrom(msg.sender, address(this), amount); uint256 fee = _calculateMovementFee(amount, depositFee); _transferToEverscale(recipient, amount - fee); if (fee > 0) _transferToEverscale(rewards_, fee); } /// @notice Deposits `token` into the Vault, leads to producing corresponding token /// on the Everscale side. /// @param recipient Recipient in the Everscale network /// @param amount Amount of `token` to deposit function deposit( EverscaleAddress memory recipient, uint256 amount ) public override onlyEmergencyDisabled respectDepositLimit(amount) nonReentrant { _deposit(recipient, amount); emit UserDeposit(msg.sender, recipient.wid, recipient.addr, amount, address(0), 0, 0); } /// @notice Same as regular `deposit`, but fills pending withdrawal. /// Pending withdrawal recipient receives `pendingWithdrawal.amount - pendingWithdrawal.bounty`. /// Deposit author receives `amount + pendingWithdrawal.bounty`. /// @param recipient Deposit recipient in the Everscale network. /// @param amount Amount of tokens to deposit. /// @param pendingWithdrawalId Pending withdrawal ID to fill. function deposit( EverscaleAddress memory recipient, uint256 amount, PendingWithdrawalId memory pendingWithdrawalId ) public override onlyEmergencyDisabled respectDepositLimit(amount) nonReentrant pendingWithdrawalApproved(pendingWithdrawalId) pendingWithdrawalOpened(pendingWithdrawalId) { PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId); require(amount >= pendingWithdrawal.amount); _deposit(recipient, amount); // Send bounty as additional transfer _transferToEverscale(recipient, pendingWithdrawal.bounty); uint redeemedAmount = pendingWithdrawal.amount - pendingWithdrawal.bounty; _pendingWithdrawalAmountReduce( pendingWithdrawalId, pendingWithdrawal.amount ); IERC20(token).safeTransfer( pendingWithdrawalId.recipient, redeemedAmount ); emit UserDeposit( msg.sender, recipient.wid, recipient.addr, amount, pendingWithdrawalId.recipient, pendingWithdrawalId.id, pendingWithdrawal.bounty ); } /** @notice Multicall for `deposit`. Fills multiple pending withdrawals at once. @param recipient Deposit recipient in the Everscale network. @param amount List of amount */ function deposit( EverscaleAddress memory recipient, uint256[] memory amount, PendingWithdrawalId[] memory pendingWithdrawalId ) external override { require(amount.length == pendingWithdrawalId.length); for (uint i = 0; i < amount.length; i++) { deposit(recipient, amount[i], pendingWithdrawalId[i]); } } function depositToFactory( uint128 amount, int8 wid, uint256 user, uint256 creditor, uint256 recipient, uint128 tokenAmount, uint128 tonAmount, uint8 swapType, uint128 slippageNumerator, uint128 slippageDenominator, bytes memory level3 ) external override onlyEmergencyDisabled respectDepositLimit(amount) { require( tokenAmount <= amount && swapType < 2 && user != 0 && recipient != 0 && creditor != 0 && slippageNumerator < slippageDenominator ); IERC20(token).safeTransferFrom(msg.sender, address(this), amount); uint256 fee = _calculateMovementFee(amount, depositFee); if (fee > 0) _transferToEverscale(rewards_, fee); emit FactoryDeposit( uint128(convertToTargetDecimals(amount - fee)), wid, user, creditor, recipient, tokenAmount, tonAmount, swapType, slippageNumerator, slippageDenominator, 0x07, level3 ); } /** @notice Save withdrawal receipt. If Vault has enough tokens and withdrawal passes the limits, then it's executed immediately. Otherwise it's saved as a pending withdrawal. @param payload Withdrawal receipt. Bytes encoded `struct EverscaleEvent`. @param signatures List of relay's signatures. See not on `Bridge.verifySignedEverscaleEvent`. @return instantWithdrawal Boolean, was withdrawal instantly filled or saved as a pending withdrawal. @return pendingWithdrawalId Pending withdrawal ID. `(address(0), 0)` if no pending withdrawal was created. */ function saveWithdraw( bytes memory payload, bytes[] memory signatures ) public override onlyEmergencyDisabled withdrawalNotSeenBefore(payload) returns (bool instantWithdrawal, PendingWithdrawalId memory pendingWithdrawalId) { require( IBridge(bridge).verifySignedEverscaleEvent(payload, signatures) == 0, "Vault: signatures verification failed" ); // Decode Everscale event (EverscaleEvent memory _event) = abi.decode(payload, (EverscaleEvent)); require( _event.configurationWid == configuration_.wid && _event.configurationAddress == configuration_.addr ); bytes32 payloadId = keccak256(payload); // Decode event data WithdrawalParams memory withdrawal = decodeWithdrawalEventData(_event.eventData); require(withdrawal.chainId == _getChainID()); // Ensure withdrawal fee uint256 fee = _calculateMovementFee(withdrawal.amount, withdrawFee); if (fee > 0) _transferToEverscale(rewards_, fee); // Consider withdrawal period limit WithdrawalPeriodParams memory withdrawalPeriod = _withdrawalPeriod(_event.eventTimestamp); _withdrawalPeriodIncreaseTotalByTimestamp(_event.eventTimestamp, withdrawal.amount); bool withdrawalLimitsPassed = _withdrawalPeriodCheckLimitsPassed(withdrawal.amount, withdrawalPeriod); // Withdrawal is less than limits and Vault's token balance is enough for instant withdrawal if (withdrawal.amount <= _vaultTokenBalance() && withdrawalLimitsPassed) { IERC20(token).safeTransfer(withdrawal.recipient, withdrawal.amount - fee); emit InstantWithdrawal(payloadId, withdrawal.recipient, withdrawal.amount - fee); return (true, PendingWithdrawalId(address(0), 0)); } // Save withdrawal as a pending uint256 id = _pendingWithdrawalCreate( withdrawal.recipient, withdrawal.amount - fee, _event.eventTimestamp ); emit PendingWithdrawalCreated(withdrawal.recipient, id, withdrawal.amount - fee, payloadId); pendingWithdrawalId = PendingWithdrawalId(withdrawal.recipient, id); if (!withdrawalLimitsPassed) { _pendingWithdrawalApproveStatusUpdate(pendingWithdrawalId, ApproveStatus.Required); } return (false, pendingWithdrawalId); } /** @notice Save withdrawal receipt, same as `saveWithdraw(bytes payload, bytes[] signatures)`, but allows to immediately set up bounty. @param payload Withdrawal receipt. Bytes encoded `struct EverscaleEvent`. @param signatures List of relay's signatures. See not on `Bridge.verifySignedEverscaleEvent`. @param bounty New value for pending withdrawal bounty. */ function saveWithdraw( bytes memory payload, bytes[] memory signatures, uint bounty ) external override { ( bool instantWithdraw, PendingWithdrawalId memory pendingWithdrawalId ) = saveWithdraw(payload, signatures); if (!instantWithdraw) { PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId); require (bounty <= pendingWithdrawal.amount); _pendingWithdrawalBountyUpdate(pendingWithdrawalId, bounty); } } /** @notice Cancel pending withdrawal partially or completely. This may only be called by pending withdrawal recipient. @param id Pending withdrawal ID @param amount Amount to cancel, should be less or equal than pending withdrawal amount @param recipient Tokens recipient, in Everscale network @param bounty New value for bounty */ function cancelPendingWithdrawal( uint256 id, uint256 amount, EverscaleAddress memory recipient, uint bounty ) external override onlyEmergencyDisabled pendingWithdrawalApproved(PendingWithdrawalId(msg.sender, id)) pendingWithdrawalOpened(PendingWithdrawalId(msg.sender, id)) { PendingWithdrawalId memory pendingWithdrawalId = PendingWithdrawalId(msg.sender, id); PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId); require(amount > 0 && amount <= pendingWithdrawal.amount); _transferToEverscale(recipient, amount); _pendingWithdrawalAmountReduce(pendingWithdrawalId, amount); emit PendingWithdrawalCancel(msg.sender, id, amount); setPendingWithdrawalBounty(id, bounty); } /** @notice Withdraws the calling account's pending withdrawal from this Vault. @param id Pending withdrawal ID. @param amountRequested Amount of tokens to be withdrawn. @param recipient The address to send the redeemed tokens. @param maxLoss The maximum acceptable loss to sustain on withdrawal. If a loss is specified, up to that amount of tokens may be burnt to cover losses on withdrawal. @param bounty New value for bounty. @return amountAdjusted The quantity of tokens redeemed. */ function withdraw( uint256 id, uint256 amountRequested, address recipient, uint256 maxLoss, uint256 bounty ) external override onlyEmergencyDisabled pendingWithdrawalOpened(PendingWithdrawalId(msg.sender, id)) pendingWithdrawalApproved(PendingWithdrawalId(msg.sender, id)) returns(uint256 amountAdjusted) { PendingWithdrawalId memory pendingWithdrawalId = PendingWithdrawalId(msg.sender, id); PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId); require( amountRequested > 0 && amountRequested <= pendingWithdrawal.amount && bounty <= pendingWithdrawal.amount - amountRequested ); _pendingWithdrawalBountyUpdate(pendingWithdrawalId, bounty); amountAdjusted = amountRequested; if (amountAdjusted > _vaultTokenBalance()) { uint256 totalLoss = 0; for (uint i = 0; i < withdrawalQueue_.length; i++) { address strategyId = withdrawalQueue_[i]; // We're done withdrawing if (strategyId == address(0)) break; uint256 vaultBalance = _vaultTokenBalance(); uint256 amountNeeded = amountAdjusted - vaultBalance; // Don't withdraw more than the debt so that Strategy can still // continue to work based on the profits it has // This means that user will lose out on any profits that each // Strategy in the queue would return on next harvest, benefiting others amountNeeded = Math.min( amountNeeded, _strategy(strategyId).totalDebt ); // Nothing to withdraw from this Strategy, try the next one if (amountNeeded == 0) continue; // Force withdraw value from each Strategy in the order set by governance uint256 loss = IStrategy(strategyId).withdraw(amountNeeded); uint256 withdrawn = _vaultTokenBalance() - vaultBalance; // Withdrawer incurs any losses from liquidation if (loss > 0) { amountAdjusted -= loss; totalLoss += loss; _strategyReportLoss(strategyId, loss); } // Reduce the Strategy's debt by the value withdrawn ("realized returns") // This doesn't add to returns as it's not earned by "normal means" _strategyTotalDebtReduce(strategyId, withdrawn); } require(_vaultTokenBalance() >= amountAdjusted); // This loss protection is put in place to revert if losses from // withdrawing are more than what is considered acceptable. require( totalLoss <= maxLoss * (amountAdjusted + totalLoss) / MAX_BPS, "Vault: loss too high" ); } IERC20(token).safeTransfer(recipient, amountAdjusted); _pendingWithdrawalAmountReduce(pendingWithdrawalId, amountRequested); emit PendingWithdrawalWithdraw( pendingWithdrawalId.recipient, pendingWithdrawalId.id, amountRequested, amountAdjusted ); return amountAdjusted; } /** @notice Add a Strategy to the Vault This may only be called by `governance` @param strategyId The address of the Strategy to add. @param _debtRatio The share of the total assets in the `vault that the `strategy` has access to. @param minDebtPerHarvest Lower limit on the increase of debt since last harvest. @param maxDebtPerHarvest Upper limit on the increase of debt since last harvest. @param _performanceFee The fee the strategist will receive based on this Vault's performance. */ function addStrategy( address strategyId, uint256 _debtRatio, uint256 minDebtPerHarvest, uint256 maxDebtPerHarvest, uint256 _performanceFee ) external override onlyGovernance onlyEmergencyDisabled strategyNotExists(strategyId) { require(strategyId != address(0)); require(IStrategy(strategyId).vault() == address(this)); require(IStrategy(strategyId).want() == token); require(debtRatio + _debtRatio <= MAX_BPS); require(minDebtPerHarvest <= maxDebtPerHarvest); require(_performanceFee <= MAX_BPS / 2); _strategyCreate(strategyId, StrategyParams({ performanceFee: _performanceFee, activation: block.timestamp, debtRatio: _debtRatio, minDebtPerHarvest: minDebtPerHarvest, maxDebtPerHarvest: maxDebtPerHarvest, lastReport: block.timestamp, totalDebt: 0, totalGain: 0, totalSkim: 0, totalLoss: 0, rewardsManager: address(0), rewards: rewards_ })); emit StrategyAdded(strategyId, _debtRatio, minDebtPerHarvest, maxDebtPerHarvest, _performanceFee); _debtRatioIncrease(_debtRatio); } /** @notice Change the quantity of assets `strategy` may manage. This may be called by `governance` or `management`. @param strategyId The Strategy to update. @param _debtRatio The quantity of assets `strategy` may now manage. */ function updateStrategyDebtRatio( address strategyId, uint256 _debtRatio ) external override onlyGovernanceOrManagement strategyExists(strategyId) { StrategyParams memory strategy = _strategy(strategyId); _debtRatioReduce(strategy.debtRatio); _strategyDebtRatioUpdate(strategyId, _debtRatio); _debtRatioIncrease(debtRatio); require(debtRatio <= MAX_BPS); emit StrategyUpdateDebtRatio(strategyId, _debtRatio); } function updateStrategyMinDebtPerHarvest( address strategyId, uint256 minDebtPerHarvest ) external override onlyGovernanceOrManagement strategyExists(strategyId) { StrategyParams memory strategy = _strategy(strategyId); require(strategy.maxDebtPerHarvest >= minDebtPerHarvest); _strategyMinDebtPerHarvestUpdate(strategyId, minDebtPerHarvest); emit StrategyUpdateMinDebtPerHarvest(strategyId, minDebtPerHarvest); } function updateStrategyMaxDebtPerHarvest( address strategyId, uint256 maxDebtPerHarvest ) external override onlyGovernanceOrManagement strategyExists(strategyId) { StrategyParams memory strategy = _strategy(strategyId); require(strategy.minDebtPerHarvest <= maxDebtPerHarvest); _strategyMaxDebtPerHarvestUpdate(strategyId, maxDebtPerHarvest); emit StrategyUpdateMaxDebtPerHarvest(strategyId, maxDebtPerHarvest); } function updateStrategyPerformanceFee( address strategyId, uint256 _performanceFee ) external override onlyGovernance strategyExists(strategyId) { require(_performanceFee <= MAX_BPS / 2); performanceFee = _performanceFee; emit StrategyUpdatePerformanceFee(strategyId, _performanceFee); } function migrateStrategy( address oldVersion, address newVersion ) external override onlyGovernance strategyExists(oldVersion) strategyNotExists(newVersion) { } function revokeStrategy( address strategyId ) external override onlyStrategyOrGovernanceOrGuardian(strategyId) { _strategyRevoke(strategyId); emit StrategyRevoked(strategyId); } function revokeStrategy() external override onlyStrategyOrGovernanceOrGuardian(msg.sender) { _strategyRevoke(msg.sender); emit StrategyRevoked(msg.sender); } function debtOutstanding( address strategyId ) external view override returns (uint256) { return _strategyDebtOutstanding(strategyId); } function debtOutstanding() external view override returns (uint256) { return _strategyDebtOutstanding(msg.sender); } function creditAvailable( address strategyId ) external view override returns (uint256) { return _strategyCreditAvailable(strategyId); } function creditAvailable() external view override returns (uint256) { return _strategyCreditAvailable(msg.sender); } function availableDepositLimit() external view override returns (uint256) { if (depositLimit > _totalAssets()) { return depositLimit - _totalAssets(); } return 0; } function expectedReturn( address strategyId ) external override view returns (uint256) { return _strategyExpectedReturn(strategyId); } function _assessFees( address strategyId, uint256 gain ) internal returns (uint256) { StrategyParams memory strategy = _strategy(strategyId); // Just added, no fees to assess if (strategy.activation == block.timestamp) return 0; uint256 duration = block.timestamp - strategy.lastReport; require(duration > 0); // Can't call twice within the same block if (gain == 0) return 0; // The fees are not charged if there hasn't been any gains reported uint256 management_fee = ( strategy.totalDebt - IStrategy(strategyId).delegatedAssets() ) * duration * managementFee / MAX_BPS / SECS_PER_YEAR; uint256 strategist_fee = (gain * strategy.performanceFee) / MAX_BPS; uint256 performance_fee = (gain * performanceFee) / MAX_BPS; uint256 total_fee = management_fee + strategist_fee + performance_fee; // Fee if (total_fee > gain) { strategist_fee = strategist_fee * gain / total_fee; performance_fee = performance_fee * gain / total_fee; management_fee = management_fee * gain / total_fee; total_fee = gain; } if (strategist_fee > 0) { _transferToEverscale(strategy.rewards, strategist_fee); } if (performance_fee + management_fee > 0) { _transferToEverscale(rewards_, performance_fee + management_fee); } return total_fee; } /** @notice Reports the amount of assets the calling Strategy has free (usually in terms of ROI). The performance fee is determined here, off of the strategy's profits (if any), and sent to governance. The strategist's fee is also determined here (off of profits), to be handled according to the strategist on the next harvest. This may only be called by a Strategy managed by this Vault. @dev For approved strategies, this is the most efficient behavior. The Strategy reports back what it has free, then Vault "decides" whether to take some back or give it more. Note that the most it can take is `gain + _debtPayment`, and the most it can give is all of the remaining reserves. Anything outside of those bounds is abnormal behavior. All approved strategies must have increased diligence around calling this function, as abnormal behavior could become catastrophic. @param gain Amount Strategy has realized as a gain on it's investment since its last report, and is free to be given back to Vault as earnings @param loss Amount Strategy has realized as a loss on it's investment since its last report, and should be accounted for on the Vault's balance sheet. The loss will reduce the debtRatio. The next time the strategy will harvest, it will pay back the debt in an attempt to adjust to the new debt limit. @param _debtPayment Amount Strategy has made available to cover outstanding debt @return Amount of debt outstanding (if totalDebt > debtLimit or emergency shutdown). */ function report( uint256 gain, uint256 loss, uint256 _debtPayment ) external override strategyExists(msg.sender) returns (uint256) { if (loss > 0) _strategyReportLoss(msg.sender, loss); uint256 totalFees = _assessFees(msg.sender, gain); _strategyTotalGainIncrease(msg.sender, gain); // Compute the line of credit the Vault is able to offer the Strategy (if any) uint256 credit = _strategyCreditAvailable(msg.sender); // Outstanding debt the Strategy wants to take back from the Vault (if any) // debtOutstanding <= strategy.totalDebt uint256 debt = _strategyDebtOutstanding(msg.sender); uint256 debtPayment = Math.min(_debtPayment, debt); if (debtPayment > 0) { _strategyTotalDebtReduce(msg.sender, debtPayment); debt -= debtPayment; } // Update the actual debt based on the full credit we are extending to the Strategy // or the returns if we are taking funds back // NOTE: credit + self.strategies_[msg.sender].totalDebt is always < self.debtLimit // NOTE: At least one of `credit` or `debt` is always 0 (both can be 0) if (credit > 0) { _strategyTotalDebtIncrease(msg.sender, credit); } // Give/take balance to Strategy, based on the difference between the reported gains // (if any), the debt payment (if any), the credit increase we are offering (if any), // and the debt needed to be paid off (if any) // NOTE: This is just used to adjust the balance of tokens between the Strategy and // the Vault based on the Strategy's debt limit (as well as the Vault's). uint256 totalAvailable = gain + debtPayment; if (totalAvailable < credit) { // credit surplus, give to Strategy IERC20(token).safeTransfer(msg.sender, credit - totalAvailable); } else if (totalAvailable > credit) { // credit deficit, take from Strategy IERC20(token).safeTransferFrom(msg.sender, address(this), totalAvailable - credit); } else { // don't do anything because it is balanced } // Profit is locked and gradually released per block // NOTE: compute current locked profit and replace with sum of current and new uint256 lockedProfitBeforeLoss = _calculateLockedProfit() + gain - totalFees; if (lockedProfitBeforeLoss > loss) { lockedProfit = lockedProfitBeforeLoss - loss; } else { lockedProfit = 0; } _strategyLastReportUpdate(msg.sender); StrategyParams memory strategy = _strategy(msg.sender); emit StrategyReported( msg.sender, gain, loss, debtPayment, strategy.totalGain, strategy.totalSkim, strategy.totalLoss, strategy.totalDebt, credit, strategy.debtRatio ); if (strategy.debtRatio == 0 || emergencyShutdown) { // Take every last penny the Strategy has (Emergency Exit/revokeStrategy) // NOTE: This is different than `debt` in order to extract *all* of the returns return IStrategy(msg.sender).estimatedTotalAssets(); } else { return debt; } } /** @notice Skim strategy gain to the `rewards_` address. This may only be called by `governance` or `management` @param strategyId Strategy address to skim. */ function skim( address strategyId ) external override onlyGovernanceOrManagement strategyExists(strategyId) { uint amount = strategies_[strategyId].totalGain - strategies_[strategyId].totalSkim; require(amount > 0); strategies_[strategyId].totalSkim += amount; _transferToEverscale(rewards_, amount); } /** @notice Removes tokens from this Vault that are not the type of token managed by this Vault. This may be used in case of accidentally sending the wrong kind of token to this Vault. Tokens will be sent to `governance`. This will fail if an attempt is made to sweep the tokens that this Vault manages. This may only be called by `governance`. @param _token The token to transfer out of this vault. */ function sweep( address _token ) external override onlyGovernance { require(token != _token); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(governance, amount); } /** @notice Force user's pending withdraw. Works only if Vault has enough tokens on its balance. This may only be called by wrapper. @param pendingWithdrawalId Pending withdrawal ID */ function forceWithdraw( PendingWithdrawalId memory pendingWithdrawalId ) public override onlyEmergencyDisabled pendingWithdrawalOpened(pendingWithdrawalId) pendingWithdrawalApproved(pendingWithdrawalId) { PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId); IERC20(token).safeTransfer(pendingWithdrawalId.recipient, pendingWithdrawal.amount); _pendingWithdrawalAmountReduce(pendingWithdrawalId, pendingWithdrawal.amount); emit PendingWithdrawalForce(pendingWithdrawalId.recipient, pendingWithdrawalId.id); } /** @notice Multicall for `forceWithdraw` @param pendingWithdrawalId List of pending withdrawal IDs */ function forceWithdraw( PendingWithdrawalId[] memory pendingWithdrawalId ) external override { for (uint i = 0; i < pendingWithdrawalId.length; i++) { forceWithdraw(pendingWithdrawalId[i]); } } /** @notice Set approve status for pending withdrawal. Pending withdrawal must be in `Required` (1) approve status, so approve status can be set only once. If Vault has enough tokens on its balance - withdrawal will be filled immediately. This may only be called by `governance` or `withdrawGuardian`. @param pendingWithdrawalId Pending withdrawal ID. @param approveStatus Approve status. Must be `Approved` (2) or `Rejected` (3). */ function setPendingWithdrawalApprove( PendingWithdrawalId memory pendingWithdrawalId, ApproveStatus approveStatus ) public override onlyGovernanceOrWithdrawGuardian pendingWithdrawalOpened(pendingWithdrawalId) { PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId); require(pendingWithdrawal.approveStatus == ApproveStatus.Required); require( approveStatus == ApproveStatus.Approved || approveStatus == ApproveStatus.Rejected ); _pendingWithdrawalApproveStatusUpdate(pendingWithdrawalId, approveStatus); // Fill approved withdrawal if (approveStatus == ApproveStatus.Approved && pendingWithdrawal.amount <= _vaultTokenBalance()) { _pendingWithdrawalAmountReduce(pendingWithdrawalId, pendingWithdrawal.amount); IERC20(token).safeTransfer( pendingWithdrawalId.recipient, pendingWithdrawal.amount ); emit PendingWithdrawalWithdraw( pendingWithdrawalId.recipient, pendingWithdrawalId.id, pendingWithdrawal.amount, pendingWithdrawal.amount ); } // Update withdrawal period considered amount _withdrawalPeriodIncreaseConsideredByTimestamp( pendingWithdrawal.timestamp, pendingWithdrawal.amount ); } /** @notice Multicall for `setPendingWithdrawalApprove`. @param pendingWithdrawalId List of pending withdrawals IDs. @param approveStatus List of approve statuses. */ function setPendingWithdrawalApprove( PendingWithdrawalId[] memory pendingWithdrawalId, ApproveStatus[] memory approveStatus ) external override { require(pendingWithdrawalId.length == approveStatus.length); for (uint i = 0; i < pendingWithdrawalId.length; i++) { setPendingWithdrawalApprove(pendingWithdrawalId[i], approveStatus[i]); } } function _transferToEverscale( EverscaleAddress memory recipient, uint256 _amount ) internal { uint256 amount = convertToTargetDecimals(_amount); emit Deposit(amount, recipient.wid, recipient.addr); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "../libraries/Math.sol"; import "../interfaces/IStrategy.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./VaultStorage.sol"; abstract contract VaultHelpers is VaultStorage { modifier onlyGovernance() { require(msg.sender == governance); _; } modifier onlyPendingGovernance() { require(msg.sender == pendingGovernance); _; } modifier onlyStrategyOrGovernanceOrGuardian(address strategyId) { require(msg.sender == strategyId || msg.sender == governance || msg.sender == guardian); _; } modifier onlyGovernanceOrManagement() { require(msg.sender == governance || msg.sender == management); _; } modifier onlyGovernanceOrGuardian() { require(msg.sender == governance || msg.sender == guardian); _; } modifier onlyGovernanceOrWithdrawGuardian() { require(msg.sender == governance || msg.sender == withdrawGuardian); _; } modifier onlyGovernanceOrStrategyRewardsManager(address strategyId) { require(msg.sender == governance || msg.sender == strategies_[strategyId].rewardsManager); _; } modifier pendingWithdrawalOpened( PendingWithdrawalId memory pendingWithdrawalId ) { PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId); require(pendingWithdrawal.amount > 0, "Vault: pending withdrawal closed"); _; } modifier pendingWithdrawalApproved( PendingWithdrawalId memory pendingWithdrawalId ) { PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId); require( pendingWithdrawal.approveStatus == ApproveStatus.NotRequired || pendingWithdrawal.approveStatus == ApproveStatus.Approved, "Vault: pending withdrawal not approved" ); _; } modifier strategyExists(address strategyId) { StrategyParams memory strategy = _strategy(strategyId); require(strategy.activation > 0, "Vault: strategy not exists"); _; } modifier strategyNotExists(address strategyId) { StrategyParams memory strategy = _strategy(strategyId); require(strategy.activation == 0, "Vault: strategy exists"); _; } modifier respectDepositLimit(uint amount) { require( _totalAssets() + amount <= depositLimit, "Vault: respect the deposit limit" ); _; } modifier onlyEmergencyDisabled() { require(!emergencyShutdown, "Vault: emergency mode enabled"); _; } modifier withdrawalNotSeenBefore(bytes memory payload) { bytes32 withdrawalId = keccak256(payload); require(!withdrawalIds[withdrawalId], "Vault: withdraw payload already seen"); _; withdrawalIds[withdrawalId] = true; } function decodeWithdrawalEventData( bytes memory eventData ) public view override returns(WithdrawalParams memory) { ( int8 sender_wid, uint256 sender_addr, uint128 amount, uint160 recipient, uint32 chainId ) = abi.decode( eventData, (int8, uint256, uint128, uint160, uint32) ); return WithdrawalParams({ sender: EverscaleAddress(sender_wid, sender_addr), amount: convertFromTargetDecimals(amount), recipient: address(recipient), chainId: chainId }); } //8b d8 db 88 88 88 888888888888 //`8b d8' d88b 88 88 88 88 // `8b d8' d8'`8b 88 88 88 88 // `8b d8' d8' `8b 88 88 88 88 // `8b d8' d8YaaaaY8b 88 88 88 88 // `8b d8' d8""""""""8b 88 88 88 88 // `888' d8' `8b Y8a. .a8P 88 88 // `8' d8' `8b `"Y8888Y"' 88888888888 88 function _vaultTokenBalance() internal view returns (uint256) { return IERC20(token).balanceOf(address(this)); } function _debtRatioReduce( uint256 amount ) internal { debtRatio -= amount; } function _debtRatioIncrease( uint256 amount ) internal { debtRatio += amount; } function _totalAssets() internal view returns (uint256) { return _vaultTokenBalance() + totalDebt; } function _calculateLockedProfit() internal view returns (uint256) { uint256 lockedFundsRatio = (block.timestamp - lastReport) * lockedProfitDegradation; if (lockedFundsRatio < DEGRADATION_COEFFICIENT) { uint256 _lockedProfit = lockedProfit; return _lockedProfit - (lockedFundsRatio * _lockedProfit / DEGRADATION_COEFFICIENT); } else { return 0; } } function convertFromTargetDecimals( uint256 amount ) public view returns (uint256) { if (targetDecimals == tokenDecimals) { return amount; } else if (targetDecimals > tokenDecimals) { return amount / 10 ** (targetDecimals - tokenDecimals); } else { return amount * 10 ** (tokenDecimals - targetDecimals); } } function convertToTargetDecimals( uint256 amount ) public view returns (uint256) { if (targetDecimals == tokenDecimals) { return amount; } else if (targetDecimals > tokenDecimals) { return amount * 10 ** (targetDecimals - tokenDecimals); } else { return amount / 10 ** (tokenDecimals - targetDecimals); } } function _calculateMovementFee( uint256 amount, uint256 fee ) internal pure returns (uint256) { if (fee == 0) return 0; return amount * fee / MAX_BPS; } // ad88888ba 888888888888 88888888ba db 888888888888 88888888888 ,ad8888ba, 8b d8 //d8" "8b 88 88 "8b d88b 88 88 d8"' `"8b Y8, ,8P //Y8, 88 88 ,8P d8'`8b 88 88 d8' Y8, ,8P //`Y8aaaaa, 88 88aaaaaa8P' d8' `8b 88 88aaaaa 88 "8aa8" // `"""""8b, 88 88""""88' d8YaaaaY8b 88 88""""" 88 88888 `88' // `8b 88 88 `8b d8""""""""8b 88 88 Y8, 88 88 //Y8a a8P 88 88 `8b d8' `8b 88 88 Y8a. .a88 88 // "Y88888P" 88 88 `8b d8' `8b 88 88888888888 `"Y88888P" 88 function _strategy( address strategyId ) internal view returns (StrategyParams memory) { return strategies_[strategyId]; } function _strategyCreate( address strategyId, StrategyParams memory strategyParams ) internal { strategies_[strategyId] = strategyParams; } function _strategyRewardsUpdate( address strategyId, EverscaleAddress memory _rewards ) internal { strategies_[strategyId].rewards = _rewards; } function _strategyDebtRatioUpdate( address strategyId, uint256 debtRatio ) internal { strategies_[strategyId].debtRatio = debtRatio; } function _strategyLastReportUpdate( address strategyId ) internal { strategies_[strategyId].lastReport = block.timestamp; lastReport = block.timestamp; } function _strategyTotalDebtReduce( address strategyId, uint256 debtPayment ) internal { strategies_[strategyId].totalDebt -= debtPayment; totalDebt -= debtPayment; } function _strategyTotalDebtIncrease( address strategyId, uint256 credit ) internal { strategies_[strategyId].totalDebt += credit; totalDebt += credit; } function _strategyDebtOutstanding( address strategyId ) internal view returns (uint256) { StrategyParams memory strategy = _strategy(strategyId); if (debtRatio == 0) return strategy.totalDebt; uint256 strategy_debtLimit = strategy.debtRatio * _totalAssets() / MAX_BPS; if (emergencyShutdown) { return strategy.totalDebt; } else if (strategy.totalDebt <= strategy_debtLimit) { return 0; } else { return strategy.totalDebt - strategy_debtLimit; } } function _strategyCreditAvailable( address strategyId ) internal view returns (uint256) { if (emergencyShutdown) return 0; uint256 vault_totalAssets = _totalAssets(); // Cant extend Strategies debt until total amount of pending withdrawals is more than Vault's total assets if (pendingWithdrawalsTotal >= vault_totalAssets) return 0; uint256 vault_debtLimit = debtRatio * vault_totalAssets / MAX_BPS; uint256 vault_totalDebt = totalDebt; StrategyParams memory strategy = _strategy(strategyId); uint256 strategy_debtLimit = strategy.debtRatio * vault_totalAssets / MAX_BPS; // Exhausted credit line if (strategy_debtLimit <= strategy.totalDebt || vault_debtLimit <= vault_totalDebt) return 0; // Start with debt limit left for the Strategy uint256 available = strategy_debtLimit - strategy.totalDebt; // Adjust by the global debt limit left available = Math.min(available, vault_debtLimit - vault_totalDebt); // Can only borrow up to what the contract has in reserve // NOTE: Running near 100% is discouraged available = Math.min(available, IERC20(token).balanceOf(address(this))); // Adjust by min and max borrow limits (per harvest) // NOTE: min increase can be used to ensure that if a strategy has a minimum // amount of capital needed to purchase a position, it's not given capital // it can't make use of yet. // NOTE: max increase is used to make sure each harvest isn't bigger than what // is authorized. This combined with adjusting min and max periods in // `BaseStrategy` can be used to effect a "rate limit" on capital increase. if (available < strategy.minDebtPerHarvest) { return 0; } else { return Math.min(available, strategy.maxDebtPerHarvest); } } function _strategyTotalGainIncrease( address strategyId, uint256 amount ) internal { strategies_[strategyId].totalGain += amount; } function _strategyExpectedReturn( address strategyId ) internal view returns (uint256) { StrategyParams memory strategy = _strategy(strategyId); uint256 timeSinceLastHarvest = block.timestamp - strategy.lastReport; uint256 totalHarvestTime = strategy.lastReport - strategy.activation; if (timeSinceLastHarvest > 0 && totalHarvestTime > 0 && IStrategy(strategyId).isActive()) { return strategy.totalGain * timeSinceLastHarvest / totalHarvestTime; } else { return 0; } } function _strategyDebtRatioReduce( address strategyId, uint256 amount ) internal { strategies_[strategyId].debtRatio -= amount; debtRatio -= amount; } function _strategyRevoke( address strategyId ) internal { _strategyDebtRatioReduce(strategyId, strategies_[strategyId].debtRatio); } function _strategyMinDebtPerHarvestUpdate( address strategyId, uint256 minDebtPerHarvest ) internal { strategies_[strategyId].minDebtPerHarvest = minDebtPerHarvest; } function _strategyMaxDebtPerHarvestUpdate( address strategyId, uint256 maxDebtPerHarvest ) internal { strategies_[strategyId].maxDebtPerHarvest = maxDebtPerHarvest; } function _strategyReportLoss( address strategyId, uint256 loss ) internal { StrategyParams memory strategy = _strategy(strategyId); uint256 totalDebt = strategy.totalDebt; // Loss can only be up the amount of debt issued to strategy require(loss <= totalDebt); // Also, make sure we reduce our trust with the strategy by the amount of loss if (debtRatio != 0) { // if vault with single strategy that is set to EmergencyOne // NOTE: The context to this calculation is different than the calculation in `_reportLoss`, // this calculation intentionally approximates via `totalDebt` to avoid manipulable results // NOTE: This calculation isn't 100% precise, the adjustment is ~10%-20% more severe due to EVM math uint256 ratio_change = Math.min( loss * debtRatio / totalDebt, strategy.debtRatio ); _strategyDebtRatioReduce(strategyId, ratio_change); } // Finally, adjust our strategy's parameters by the loss strategies_[strategyId].totalLoss += loss; _strategyTotalDebtReduce(strategyId, loss); } //88888888ba 88888888888 888b 88 88888888ba, 88 888b 88 ,ad8888ba, //88 "8b 88 8888b 88 88 `"8b 88 8888b 88 d8"' `"8b //88 ,8P 88 88 `8b 88 88 `8b 88 88 `8b 88 d8' //88aaaaaa8P' 88aaaaa 88 `8b 88 88 88 88 88 `8b 88 88 //88""""""' 88""""" 88 `8b 88 88 88 88 88 `8b 88 88 88888 //88 88 88 `8b 88 88 8P 88 88 `8b 88 Y8, 88 //88 88 88 `8888 88 .a8P 88 88 `8888 Y8a. .a88 //88 88888888888 88 `888 88888888Y"' 88 88 `888 `"Y88888P" function _pendingWithdrawal( PendingWithdrawalId memory pendingWithdrawalId ) internal view returns (PendingWithdrawalParams memory) { return pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id]; } function _pendingWithdrawalCreate( address recipient, uint256 amount, uint256 timestamp ) internal returns (uint256 pendingWithdrawalId) { pendingWithdrawalId = pendingWithdrawalsPerUser[recipient]; pendingWithdrawalsPerUser[recipient]++; pendingWithdrawals_[recipient][pendingWithdrawalId] = PendingWithdrawalParams({ amount: amount, timestamp: timestamp, bounty: 0, approveStatus: ApproveStatus.NotRequired }); pendingWithdrawalsTotal += amount; return pendingWithdrawalId; } function _pendingWithdrawalBountyUpdate( PendingWithdrawalId memory pendingWithdrawalId, uint bounty ) internal { pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id].bounty = bounty; emit PendingWithdrawalUpdateBounty(pendingWithdrawalId.recipient, pendingWithdrawalId.id, bounty); } function _pendingWithdrawalAmountReduce( PendingWithdrawalId memory pendingWithdrawalId, uint amount ) internal { pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id].amount -= amount; pendingWithdrawalsTotal -= amount; } function _pendingWithdrawalApproveStatusUpdate( PendingWithdrawalId memory pendingWithdrawalId, ApproveStatus approveStatus ) internal { pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id].approveStatus = approveStatus; emit PendingWithdrawalUpdateApproveStatus( pendingWithdrawalId.recipient, pendingWithdrawalId.id, approveStatus ); } //88888888ba 88888888888 88888888ba 88 ,ad8888ba, 88888888ba, //88 "8b 88 88 "8b 88 d8"' `"8b 88 `"8b //88 ,8P 88 88 ,8P 88 d8' `8b 88 `8b //88aaaaaa8P' 88aaaaa 88aaaaaa8P' 88 88 88 88 88 //88""""""' 88""""" 88""""88' 88 88 88 88 88 //88 88 88 `8b 88 Y8, ,8P 88 8P //88 88 88 `8b 88 Y8a. .a8P 88 .a8P //88 88888888888 88 `8b 88 `"Y8888Y"' 88888888Y"' function _withdrawalPeriodDeriveId( uint256 timestamp ) internal pure returns (uint256) { return timestamp / WITHDRAW_PERIOD_DURATION_IN_SECONDS; } function _withdrawalPeriod( uint256 timestamp ) internal view returns (WithdrawalPeriodParams memory) { return withdrawalPeriods_[_withdrawalPeriodDeriveId(timestamp)]; } function _withdrawalPeriodIncreaseTotalByTimestamp( uint256 timestamp, uint256 amount ) internal { uint withdrawalPeriodId = _withdrawalPeriodDeriveId(timestamp); withdrawalPeriods_[withdrawalPeriodId].total += amount; } function _withdrawalPeriodIncreaseConsideredByTimestamp( uint256 timestamp, uint256 amount ) internal { uint withdrawalPeriodId = _withdrawalPeriodDeriveId(timestamp); withdrawalPeriods_[withdrawalPeriodId].considered += amount; } function _withdrawalPeriodCheckLimitsPassed( uint amount, WithdrawalPeriodParams memory withdrawalPeriod ) internal view returns (bool) { return amount < undeclaredWithdrawLimit && amount + withdrawalPeriod.total - withdrawalPeriod.considered < withdrawLimitPerPeriod; } function _getChainID() internal view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./../interfaces/vault/IVault.sol"; abstract contract VaultStorage is IVault, Initializable, ReentrancyGuard { uint256 constant MAX_BPS = 10_000; uint256 constant WITHDRAW_PERIOD_DURATION_IN_SECONDS = 60 * 60 * 24; // 24 hours uint256 constant SECS_PER_YEAR = 31_556_952; // 365.2425 days // Bridge // - Bridge address, used to verify relay's signatures. Read more on `saveWithdraw` address public override bridge; // - Bridge EVER-EVM event configuration // NOTE: Some variables have "_" postfix and not declared as a "public override" // Instead they have explicit corresponding getter // It's a compiler issue, described here - https://github.com/ethereum/solidity/issues/11826 EverscaleAddress configuration_; function configuration() external view override returns (EverscaleAddress memory) { return configuration_; } // - Withdrawal receipt IDs, used to prevent double spending mapping(bytes32 => bool) public override withdrawalIds; // - Rewards address in Everscale, receives fees, gains, etc EverscaleAddress rewards_; function rewards() external view override returns (EverscaleAddress memory) { return rewards_; } // Pending withdrawals // - Counter pending withdrawals per user mapping(address => uint) public override pendingWithdrawalsPerUser; // - Pending withdrawal details mapping(address => mapping(uint256 => PendingWithdrawalParams)) pendingWithdrawals_; function pendingWithdrawals( address user, uint256 id ) external view override returns (PendingWithdrawalParams memory) { return pendingWithdrawals_[user][id]; } // - Total amount of `token` in pending withdrawal status uint public override pendingWithdrawalsTotal; // Ownership // - Governance address public override governance; // - Pending governance, used for 2-step governance transfer address pendingGovernance; // - Guardian, responsible for security actions address public override guardian; // - Withdraw guardian, responsible for approving / rejecting some of the withdrawals address public override withdrawGuardian; // - Management, responsible for managing strategies address public override management; // Token // - Vault's token address public override token; // - Decimals on corresponding token in the Everscale network uint256 public override targetDecimals; // - Decimals of `token` uint256 public override tokenDecimals; // Fees // - Deposit fee, in BPS uint256 public override depositFee; // - Withdraw fee, in BPS uint256 public override withdrawFee; // - Management fee, in BPS uint256 public override managementFee; // - Performance fee, in BPS uint256 public override performanceFee; // Strategies // - Strategies registry mapping(address => StrategyParams) strategies_; function strategies( address strategyId ) external view override returns (StrategyParams memory) { return strategies_[strategyId]; } uint256 constant DEGRADATION_COEFFICIENT = 10**18; // - SET_SIZE can be any number but having it in power of 2 will be more gas friendly and collision free. // - Make sure SET_SIZE is greater than 20 uint256 constant SET_SIZE = 32; // - Ordering that `withdraw` uses to determine which strategies to pull funds from // Does *NOT* have to match the ordering of all the current strategies that // exist, but it is recommended that it does or else withdrawal depth is // limited to only those inside the queue. // Ordering is determined by governance, and should be balanced according // to risk, slippage, and/or volatility. Can also be ordered to increase the // withdrawal speed of a particular Strategy. // The first time a zero address is encountered, it stops withdrawing // Maximum amount of strategies in withdrawal queue = 20 address[20] withdrawalQueue_; function withdrawalQueue() external view override returns (address[20] memory) { return withdrawalQueue_; } // Security // - Emergency shutdown, most of operations are unavailable in emergency mode bool public override emergencyShutdown; // - Withdraw limit per period uint256 public override withdrawLimitPerPeriod; // - Undeclared withdraw limit uint256 public override undeclaredWithdrawLimit; // - Withdrawal periods. Each period is `WITHDRAW_PERIOD_DURATION_IN_SECONDS` seconds long. // If some period has reached the `withdrawalLimitPerPeriod` - all the future // withdrawals in this period require manual approve, see note on `setPendingWithdrawalsApprove` mapping(uint256 => WithdrawalPeriodParams) withdrawalPeriods_; function withdrawalPeriods( uint256 withdrawalPeriodId ) external view override returns (WithdrawalPeriodParams memory) { return withdrawalPeriods_[withdrawalPeriodId]; } // Vault // - Limit for `totalAssets` the Vault can hold uint256 public override depositLimit; // - Debt ratio for the Vault across al strategies (<= MAX_BPS) uint256 public override debtRatio; // - Amount of all tokens that all strategies have borrowed uint256 public override totalDebt; // - block.timestamp of last report uint256 public override lastReport; // - How much profit is locked and cant be withdrawn uint256 public override lockedProfit; // - Rate per block of degradation. DEGRADATION_COEFFICIENT is 100% per block uint256 public override lockedProfitDegradation; }
credit surplus, give to Strategy
if (totalAvailable < credit) {
6,186,375
[ 1, 20688, 5056, 10103, 16, 8492, 358, 19736, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 4963, 5268, 411, 12896, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.4 <0.6.0; import './AOLibrary.sol'; import './TheAO.sol'; import './IAOSetting.sol'; import './INameFactory.sol'; import './IAOSettingAttribute.sol'; import './IAOSettingValue.sol'; import './INameTAOPosition.sol'; import './INameAccountRecovery.sol'; /** * @title AOSettingUpdate * * This contract purpose is to update existing Setting Value */ contract AOSettingUpdate is TheAO { address public nameFactoryAddress; address public nameAccountRecoveryAddress; address public aoSettingAttributeAddress; address public aoSettingValueAddress; address public aoSettingAddress; INameFactory internal _nameFactory; INameTAOPosition internal _nameTAOPosition; INameAccountRecovery internal _nameAccountRecovery; IAOSettingAttribute internal _aoSettingAttribute; IAOSettingValue internal _aoSettingValue; IAOSetting internal _aoSetting; struct UpdateSignature { uint8 signatureV; bytes32 signatureR; bytes32 signatureS; } // Mapping from settingId to UpdateSignature mapping (uint256 => UpdateSignature) public updateSignatures; // Mapping from updateHashKey to it's settingId mapping (bytes32 => uint256) public updateHashLookup; // Event to be broadcasted to public when a proposed update for a setting is created event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId); // Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved); // Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _nameAccountRecoveryAddress, address _aoSettingAttributeAddress, address _aoSettingValueAddress, address _aoSettingAddress ) public { setNameFactoryAddress(_nameFactoryAddress); setNameTAOPositionAddress(_nameTAOPositionAddress); setNameAccountRecoveryAddress(_nameAccountRecoveryAddress); setAOSettingAttributeAddress(_aoSettingAttributeAddress); setAOSettingValueAddress(_aoSettingValueAddress); setAOSettingAddress(_aoSettingAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Only allowed if sender's Name is not compromised */ modifier senderNameNotCompromised() { require (!_nameAccountRecovery.isCompromised(_nameFactory.ethAddressToNameId(msg.sender))); _; } /** * @dev Check if sender can update setting */ modifier canUpdate(address _proposalTAOId) { require ( AOLibrary.isTAO(_proposalTAOId) && _nameFactory.ethAddressToNameId(msg.sender) != address(0) && !_nameAccountRecovery.isCompromised(_nameFactory.ethAddressToNameId(msg.sender)) ); _; } /** * @dev Check whether or not setting is of type address */ modifier isAddressSetting(uint256 _settingId) { (uint8 ADDRESS_SETTING_TYPE,,,,) = _aoSetting.getSettingTypes(); // Make sure the setting type is address require (_aoSetting.settingTypeLookup(_settingId) == ADDRESS_SETTING_TYPE); _; } /** * @dev Check whether or not setting is of type bool */ modifier isBoolSetting(uint256 _settingId) { (, uint8 BOOL_SETTING_TYPE,,,) = _aoSetting.getSettingTypes(); // Make sure the setting type is bool require (_aoSetting.settingTypeLookup(_settingId) == BOOL_SETTING_TYPE); _; } /** * @dev Check whether or not setting is of type bytes32 */ modifier isBytesSetting(uint256 _settingId) { (,, uint8 BYTES_SETTING_TYPE,,) = _aoSetting.getSettingTypes(); // Make sure the setting type is bytes32 require (_aoSetting.settingTypeLookup(_settingId) == BYTES_SETTING_TYPE); _; } /** * @dev Check whether or not setting is of type string */ modifier isStringSetting(uint256 _settingId) { (,,, uint8 STRING_SETTING_TYPE,) = _aoSetting.getSettingTypes(); // Make sure the setting type is string require (_aoSetting.settingTypeLookup(_settingId) == STRING_SETTING_TYPE); _; } /** * @dev Check whether or not setting is of type uint256 */ modifier isUintSetting(uint256 _settingId) { (,,,, uint8 UINT_SETTING_TYPE) = _aoSetting.getSettingTypes(); // Make sure the setting type is uint256 require (_aoSetting.settingTypeLookup(_settingId) == UINT_SETTING_TYPE); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO sets NameFactory address * @param _nameFactoryAddress The address of NameFactory */ function setNameFactoryAddress(address _nameFactoryAddress) public onlyTheAO { require (_nameFactoryAddress != address(0)); nameFactoryAddress = _nameFactoryAddress; _nameFactory = INameFactory(_nameFactoryAddress); } /** * @dev The AO sets NameTAOPosition address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = INameTAOPosition(_nameTAOPositionAddress); } /** * @dev The AO set the NameAccountRecovery Address * @param _nameAccountRecoveryAddress The address of NameAccountRecovery */ function setNameAccountRecoveryAddress(address _nameAccountRecoveryAddress) public onlyTheAO { require (_nameAccountRecoveryAddress != address(0)); nameAccountRecoveryAddress = _nameAccountRecoveryAddress; _nameAccountRecovery = INameAccountRecovery(nameAccountRecoveryAddress); } /** * @dev The AO sets AOSettingAttribute address * @param _aoSettingAttributeAddress The address of AOSettingAttribute */ function setAOSettingAttributeAddress(address _aoSettingAttributeAddress) public onlyTheAO { require (_aoSettingAttributeAddress != address(0)); aoSettingAttributeAddress = _aoSettingAttributeAddress; _aoSettingAttribute = IAOSettingAttribute(_aoSettingAttributeAddress); } /** * @dev The AO sets AOSettingValue address * @param _aoSettingValueAddress The address of AOSettingValue */ function setAOSettingValueAddress(address _aoSettingValueAddress) public onlyTheAO { require (_aoSettingValueAddress != address(0)); aoSettingValueAddress = _aoSettingValueAddress; _aoSettingValue = IAOSettingValue(_aoSettingValueAddress); } /** * @dev The AO sets AOSetting address * @param _aoSettingAddress The address of AOSetting */ function setAOSettingAddress(address _aoSettingAddress) public onlyTheAO { require (_aoSettingAddress != address(0)); aoSettingAddress = _aoSettingAddress; _aoSetting = IAOSetting(_aoSettingAddress); } /***** PUBLIC METHODS *****/ /** * @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _signatureV The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureR The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureS The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _extraData Catch-all string value to be stored if exist */ function updateAddressSetting( uint256 _settingId, address _newValue, address _proposalTAOId, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS, string memory _extraData) public canUpdate(_proposalTAOId) isAddressSetting(_settingId) { // Verify and store update address signature require (_verifyAndStoreUpdateAddressSignature(_settingId, _newValue, _proposalTAOId, _signatureV, _signatureR, _signatureS)); // Store the setting state data require (_aoSettingAttribute.update(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _extraData)); // Store the value as pending value _aoSettingValue.setPendingValue(_settingId, _newValue, false, '', '', 0); // Store the update hash key lookup _storeUpdateAddressHashLookup(_settingId, _newValue, _proposalTAOId, _extraData); emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bool value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _signatureV The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureR The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureS The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _extraData Catch-all string value to be stored if exist */ function updateBoolSetting( uint256 _settingId, bool _newValue, address _proposalTAOId, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS, string memory _extraData) public canUpdate(_proposalTAOId) isBoolSetting(_settingId) { // Verify and store update bool signature require (_verifyAndStoreUpdateBoolSignature(_settingId, _newValue, _proposalTAOId, _signatureV, _signatureR, _signatureS)); // Store the setting state data require (_aoSettingAttribute.update(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _extraData)); // Store the value as pending value _aoSettingValue.setPendingValue(_settingId, address(0), _newValue, '', '', 0); // Store the update hash key lookup _storeUpdateBoolHashLookup(_settingId, _newValue, _proposalTAOId, _extraData); emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bytes32 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _signatureV The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureR The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureS The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _extraData Catch-all string value to be stored if exist */ function updateBytesSetting( uint256 _settingId, bytes32 _newValue, address _proposalTAOId, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS, string memory _extraData) public canUpdate(_proposalTAOId) isBytesSetting(_settingId) { // Verify and store update bytes32 signature require (_verifyAndStoreUpdateBytesSignature(_settingId, _newValue, _proposalTAOId, _signatureV, _signatureR, _signatureS)); // Store the setting state data require (_aoSettingAttribute.update(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _extraData)); // Store the value as pending value _aoSettingValue.setPendingValue(_settingId, address(0), false, _newValue, '', 0); // Store the update hash key lookup _storeUpdateBytesHashLookup(_settingId, _newValue, _proposalTAOId, _extraData); emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new string value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _signatureV The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureR The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureS The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _extraData Catch-all string value to be stored if exist */ function updateStringSetting( uint256 _settingId, string memory _newValue, address _proposalTAOId, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS, string memory _extraData) public canUpdate(_proposalTAOId) isStringSetting(_settingId) { // Verify and store update string signature require (_verifyAndStoreUpdateStringSignature(_settingId, _newValue, _proposalTAOId, _signatureV, _signatureR, _signatureS)); // Store the setting state data require (_aoSettingAttribute.update(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _extraData)); // Store the value as pending value _aoSettingValue.setPendingValue(_settingId, address(0), false, '', _newValue, 0); // Store the update hash key lookup _storeUpdateStringHashLookup(_settingId, _newValue, _proposalTAOId, _extraData); emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new uint256 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _signatureV The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureR The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _signatureS The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _extraData Catch-all string value to be stored if exist */ function updateUintSetting( uint256 _settingId, uint256 _newValue, address _proposalTAOId, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS, string memory _extraData) public canUpdate(_proposalTAOId) isUintSetting(_settingId) { // Verify and store update uint256 signature require (_verifyAndStoreUpdateUintSignature(_settingId, _newValue, _proposalTAOId, _signatureV, _signatureR, _signatureS)); // Store the setting state data require (_aoSettingAttribute.update(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _extraData)); // Store the value as pending value _aoSettingValue.setPendingValue(_settingId, address(0), false, '', '', _newValue); // Store the update hash key lookup _storeUpdateUintHashLookup(_settingId, _newValue, _proposalTAOId, _extraData); emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _approved Whether to approve or reject */ function approveSettingUpdate(uint256 _settingId, bool _approved) public senderIsName senderNameNotCompromised { // Make sure setting exist require (_aoSetting.settingTypeLookup(_settingId) > 0); address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); (,,, address _proposalTAOId,,) = _aoSettingAttribute.getSettingState(_settingId); require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved)); emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingUpdate(uint256 _settingId) public senderIsName senderNameNotCompromised { // Make sure setting exist require (_aoSetting.settingTypeLookup(_settingId) > 0); address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate)); (,,, address _associatedTAOId,,,,,) = _aoSettingAttribute.getSettingData(_settingId); require (_aoSettingValue.movePendingToSetting(_settingId)); emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate); } /***** Internal Method *****/ /** * @dev Verify the signature for the address update and store the signature info * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _v The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _r The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _s The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @return true if valid, false otherwise */ function _verifyAndStoreUpdateAddressSignature( uint256 _settingId, address _newValue, address _proposalTAOId, uint8 _v, bytes32 _r, bytes32 _s ) internal returns (bool) { bytes32 _hash = keccak256(abi.encodePacked(address(this), _settingId, _proposalTAOId, _newValue, _nameFactory.ethAddressToNameId(msg.sender))); if (ecrecover(_hash, _v, _r, _s) != msg.sender) { return false; } _storeUpdateSignature(_settingId, _v, _r, _s); return true; } /** * @dev Verify the signature for the bool update and store the signature info * @param _settingId The ID of the setting to be updated * @param _newValue The new bool value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _v The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _r The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _s The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @return true if valid, false otherwise */ function _verifyAndStoreUpdateBoolSignature( uint256 _settingId, bool _newValue, address _proposalTAOId, uint8 _v, bytes32 _r, bytes32 _s ) internal returns (bool) { bytes32 _hash = keccak256(abi.encodePacked(address(this), _settingId, _proposalTAOId, _newValue, _nameFactory.ethAddressToNameId(msg.sender))); if (ecrecover(_hash, _v, _r, _s) != msg.sender) { return false; } _storeUpdateSignature(_settingId, _v, _r, _s); return true; } /** * @dev Verify the signature for the bytes32 update and store the signature info * @param _settingId The ID of the setting to be updated * @param _newValue The new bytes32 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _v The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _r The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _s The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @return true if valid, false otherwise */ function _verifyAndStoreUpdateBytesSignature( uint256 _settingId, bytes32 _newValue, address _proposalTAOId, uint8 _v, bytes32 _r, bytes32 _s ) internal returns (bool) { bytes32 _hash = keccak256(abi.encodePacked(address(this), _settingId, _proposalTAOId, _newValue, _nameFactory.ethAddressToNameId(msg.sender))); if (ecrecover(_hash, _v, _r, _s) != msg.sender) { return false; } _storeUpdateSignature(_settingId, _v, _r, _s); return true; } /** * @dev Verify the signature for the string update and store the signature info * @param _settingId The ID of the setting to be updated * @param _newValue The new string value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _v The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _r The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _s The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @return true if valid, false otherwise */ function _verifyAndStoreUpdateStringSignature( uint256 _settingId, string memory _newValue, address _proposalTAOId, uint8 _v, bytes32 _r, bytes32 _s ) internal returns (bool) { bytes32 _hash = keccak256(abi.encodePacked(address(this), _settingId, _proposalTAOId, _newValue, _nameFactory.ethAddressToNameId(msg.sender))); if (ecrecover(_hash, _v, _r, _s) != msg.sender) { return false; } _storeUpdateSignature(_settingId, _v, _r, _s); return true; } /** * @dev Verify the signature for the uint256 update and store the signature info * @param _settingId The ID of the setting to be updated * @param _newValue The new uint256 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _v The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _r The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _s The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @return true if valid, false otherwise */ function _verifyAndStoreUpdateUintSignature( uint256 _settingId, uint256 _newValue, address _proposalTAOId, uint8 _v, bytes32 _r, bytes32 _s ) public returns (bool) { bytes32 _hash = keccak256(abi.encodePacked(address(this), _settingId, _proposalTAOId, _newValue, _nameFactory.ethAddressToNameId(msg.sender))); if (ecrecover(_hash, _v, _r, _s) != msg.sender) { return false; } _storeUpdateSignature(_settingId, _v, _r, _s); return true; } /** * @dev Store the update hash lookup for this address setting * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _extraData Catch-all string value to be stored if exist */ function _storeUpdateAddressHashLookup( uint256 _settingId, address _newValue, address _proposalTAOId, string memory _extraData) internal { // Store the update hash key lookup (address _addressValue,,,,) = _aoSettingValue.settingValue(_settingId); updateHashLookup[keccak256(abi.encodePacked(address(this), _proposalTAOId, _addressValue, _newValue, _extraData, _settingId))] = _settingId; } /** * @dev Store the update hash lookup for this bool setting * @param _settingId The ID of the setting to be updated * @param _newValue The new bool value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _extraData Catch-all string value to be stored if exist */ function _storeUpdateBoolHashLookup( uint256 _settingId, bool _newValue, address _proposalTAOId, string memory _extraData) internal { // Store the update hash key lookup (, bool _boolValue,,,) = _aoSettingValue.settingValue(_settingId); updateHashLookup[keccak256(abi.encodePacked(address(this), _proposalTAOId, _boolValue, _newValue, _extraData, _settingId))] = _settingId; } /** * @dev Store the update hash lookup for this bytes32 setting * @param _settingId The ID of the setting to be updated * @param _newValue The new bytes32 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _extraData Catch-all string value to be stored if exist */ function _storeUpdateBytesHashLookup( uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string memory _extraData) internal { // Store the update hash key lookup (,, bytes32 _bytesValue,,) = _aoSettingValue.settingValue(_settingId); updateHashLookup[keccak256(abi.encodePacked(address(this), _proposalTAOId, _bytesValue, _newValue, _extraData, _settingId))] = _settingId; } /** * @dev Store the update hash lookup for this string setting * @param _settingId The ID of the setting to be updated * @param _newValue The new string value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _extraData Catch-all string value to be stored if exist */ function _storeUpdateStringHashLookup( uint256 _settingId, string memory _newValue, address _proposalTAOId, string memory _extraData) internal { // Store the update hash key lookup (,,, string memory _stringValue,) = _aoSettingValue.settingValue(_settingId); updateHashLookup[keccak256(abi.encodePacked(address(this), _proposalTAOId, _stringValue, _newValue, _extraData, _settingId))] = _settingId; } /** * @dev Store the update hash lookup for this uint256 setting * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _extraData Catch-all string value to be stored if exist */ function _storeUpdateUintHashLookup( uint256 _settingId, uint256 _newValue, address _proposalTAOId, string memory _extraData) internal { // Store the update hash key lookup (,,,, uint256 _uintValue) = _aoSettingValue.settingValue(_settingId); updateHashLookup[keccak256(abi.encodePacked(address(this), _proposalTAOId, _uintValue, _newValue, _extraData, _settingId))] = _settingId; } /** * @dev Actual storing the UpdateSignature info * @param _settingId The ID of the setting to be updated * @param _v The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _r The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate * @param _s The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate */ function _storeUpdateSignature(uint256 _settingId, uint8 _v, bytes32 _r, bytes32 _s) internal { UpdateSignature storage _updateSignature = updateSignatures[_settingId]; _updateSignature.signatureV = _v; _updateSignature.signatureR = _r; _updateSignature.signatureS = _s; } }
* @dev Check whether or not setting is of type string/ Make sure the setting type is string
modifier isStringSetting(uint256 _settingId) { (,,, uint8 STRING_SETTING_TYPE,) = _aoSetting.getSettingTypes(); require (_aoSetting.settingTypeLookup(_settingId) == STRING_SETTING_TYPE); _; }
13,033,992
[ 1, 1564, 2856, 578, 486, 3637, 353, 434, 618, 533, 19, 4344, 3071, 326, 3637, 618, 353, 533, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 20597, 9962, 5568, 12, 11890, 5034, 389, 8920, 548, 13, 288, 203, 202, 202, 12, 16408, 16, 2254, 28, 9469, 67, 1090, 12239, 67, 2399, 16, 13, 273, 389, 6033, 5568, 18, 588, 5568, 2016, 5621, 203, 202, 202, 6528, 261, 67, 6033, 5568, 18, 8920, 559, 6609, 24899, 8920, 548, 13, 422, 9469, 67, 1090, 12239, 67, 2399, 1769, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x8D2C372317524a8Af5313883434411fd3DAE55d9/sources/contracts/lib/FulfillmentApplier.sol
* @dev Internal pure function to aggregate a group of consideration items using supplied directives on which component items are candidates for aggregation, skipping items on orders that are not available. @param advancedOrders The orders to aggregate consideration items from. @param considerationComponents An array of FulfillmentComponent structs indicating the order index and item index of each candidate consideration item for aggregation. @param execution The execution to apply the aggregation to./ Utilize assembly in order to efficiently aggregate the items.
) internal pure { function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } let fulfillmentHeadPtr := add(considerationComponents, OneWord) let orderIndex := mload(mload(fulfillmentHeadPtr)) function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } let orderPtr := mload( add(add(advancedOrders, OneWord), mul(orderIndex, OneWord)) let considerationArrPtr := mload( mload(orderPtr), let itemIndex := mload( function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } let considerationItemPtr := mload( add(considerationArrPtr, OneWord), mul(itemIndex, OneWord) let amount := 0 let errorBuffer := 0 function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } let receivedItem := mload(execution) mstore(receivedItem, mload(considerationItemPtr)) mstore( mstore( mstore( let dataHash := keccak256( let endPtr := add( for {} lt(fulfillmentHeadPtr, endPtr) {} { fulfillmentHeadPtr := add(fulfillmentHeadPtr, OneWord) orderIndex := mload(mload(fulfillmentHeadPtr)) function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } orderPtr := mload( if iszero( function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } considerationArrPtr := mload( mload(orderPtr), itemIndex := mload(add(mload(fulfillmentHeadPtr), OneWord)) function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } considerationItemPtr := mload( add(considerationArrPtr, OneWord), mul(itemIndex, OneWord) let amountPtr := add( let newAmount := add(amount, mload(amountPtr)) errorBuffer := or( amount := newAmount mstore(amountPtr, 0) if iszero( eq( eq( function _aggregateValidFulfillmentConsiderationItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory considerationComponents, Execution memory execution assembly { function throwInvalidFulfillmentComponentData() { mstore(0, InvalidFulfillmentComponentData_error_signature) revert(0, InvalidFulfillmentComponentData_error_len) } function throwOverflow() { mstore(0, Panic_error_signature) mstore(Panic_error_offset, Panic_arithmetic) revert(0, Panic_error_length) } if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } ) add( OrderParameters_consideration_head_offset ) ) add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { let amountPtr := add(considerationItemPtr, Common_amount_offset) amount := mload(amountPtr) errorBuffer := iszero(amount) mstore(amountPtr, 0) } add(receivedItem, Common_token_offset), mload(add(considerationItemPtr, Common_token_offset)) ) add(receivedItem, Common_identifier_offset), mload(add(considerationItemPtr, Common_identifier_offset)) ) add(receivedItem, ReceivedItem_recipient_offset), mload( add( considerationItemPtr, ConsiderationItem_recipient_offset ) ) ) receivedItem, ReceivedItem_CommonParams_size ) considerationComponents, mul(mload(considerationComponents), OneWord) ) if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) mload(add(orderPtr, AdvancedOrder_numerator_offset)) ) { continue } add( OrderParameters_consideration_head_offset ) ) if iszero(lt(itemIndex, mload(considerationArrPtr))) { throwInvalidFulfillmentComponentData() } add( ) ) considerationItemPtr, Common_amount_offset ) errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) and( mload( add( considerationItemPtr, ConsiderItem_recipient_offset ) ), mload( add( receivedItem, ReceivedItem_recipient_offset ) ) ), dataHash, keccak256( considerationItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { throwInvalidFulfillmentComponentData() } } mstore(add(receivedItem, Common_amount_offset), amount) if errorBuffer { if eq(errorBuffer, 1) { mstore(0, MissingItemAmount_error_signature) revert(0, MissingItemAmount_error_len) } } if errorBuffer { if eq(errorBuffer, 1) { mstore(0, MissingItemAmount_error_signature) revert(0, MissingItemAmount_error_len) } } throwOverflow() }
877,842
[ 1, 3061, 16618, 445, 358, 7047, 279, 1041, 434, 5260, 367, 1516, 1377, 1450, 4580, 13877, 603, 1492, 1794, 1516, 854, 7965, 1377, 364, 10163, 16, 14195, 1516, 603, 11077, 716, 854, 486, 2319, 18, 225, 16111, 16528, 1850, 1021, 11077, 358, 7047, 5260, 367, 27573, 1516, 628, 18, 225, 5260, 367, 7171, 1922, 526, 434, 478, 332, 5935, 475, 1841, 8179, 27573, 11193, 326, 1353, 770, 471, 761, 770, 27573, 434, 1517, 5500, 5260, 367, 761, 364, 27573, 10163, 18, 225, 4588, 4202, 1021, 4588, 358, 2230, 326, 10163, 358, 18, 19, 3564, 554, 19931, 316, 1353, 358, 14382, 715, 7047, 326, 1516, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 2713, 16618, 288, 203, 565, 445, 389, 18573, 1556, 23747, 5935, 475, 9054, 3585, 367, 3126, 12, 203, 3639, 27451, 2448, 8526, 3778, 16111, 16528, 16, 203, 3639, 478, 332, 5935, 475, 1841, 8526, 3778, 5260, 367, 7171, 16, 203, 3639, 8687, 3778, 4588, 203, 3639, 19931, 288, 203, 5411, 445, 604, 1941, 23747, 5935, 475, 1841, 751, 1435, 288, 203, 7734, 312, 2233, 12, 20, 16, 1962, 23747, 5935, 475, 1841, 751, 67, 1636, 67, 8195, 13, 203, 203, 7734, 15226, 12, 20, 16, 1962, 23747, 5935, 475, 1841, 751, 67, 1636, 67, 1897, 13, 203, 5411, 289, 203, 203, 5411, 445, 604, 15526, 1435, 288, 203, 7734, 312, 2233, 12, 20, 16, 21040, 67, 1636, 67, 8195, 13, 203, 203, 7734, 312, 2233, 12, 23144, 67, 1636, 67, 3348, 16, 21040, 67, 297, 16368, 13, 203, 203, 7734, 15226, 12, 20, 16, 21040, 67, 1636, 67, 2469, 13, 203, 5411, 289, 203, 203, 203, 203, 5411, 309, 353, 7124, 12, 5618, 12, 1019, 1016, 16, 312, 945, 12, 27080, 16528, 20349, 288, 203, 7734, 604, 1941, 23747, 5935, 475, 1841, 751, 1435, 203, 5411, 289, 203, 203, 5411, 262, 203, 203, 7734, 527, 12, 203, 10792, 4347, 2402, 67, 8559, 3585, 367, 67, 1978, 67, 3348, 203, 7734, 262, 203, 5411, 262, 203, 203, 7734, 527, 12, 81, 945, 12, 2706, 5935, 475, 1414, 5263, 3631, 478, 332, 5935, 475, 67, 1726, 1016, 67, 3348, 13, 203, 5411, 262, 203, 203, 5411, 309, 353, 7124, 12, 5618, 12, 1726, 1016, 2 ]
pragma solidity ^ 0.4 .24; library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns(uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns(uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns(uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns(uint256) { require(b != 0); return a % b; } } contract Ownable { address 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; } } interface IERC20 { function totalSupply() external view returns(uint256); function balanceOf(address who) external view returns(uint256); function allowance(address owner, address spender) external view returns(uint256); function transfer(address to, uint256 value) external returns(bool); function approve(address spender, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns(uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns(uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns(uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns(bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns(bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns(bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns(bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns(bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } contract FlychatToken is ERC20, ERC20Detailed, ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); uint256 public constant INITIAL_SUPPLY = 6000000000 * (10 ** uint256(decimals())); uint256 public constant INITIAL_SUPPLY2 = 14000000000 * (10 ** uint256(decimals())); uint256 public rate = 10000000; enum CrowdsaleStage { presale, ico } CrowdsaleStage public stage = CrowdsaleStage.presale; bool public allowbuy = false; bool public endbuy = false; uint256 public preallocation = 2400000000 * (10 ** uint256(18)); uint256 public icoallocation = 9600000000 * (10 ** uint256(18)); uint256 public minbuy = 10000000000000000; uint256 public availableonpresale = preallocation; uint256 public availableonico = icoallocation; constructor(address wallet) public ERC20Detailed("FlychatToken", "FLY", 18) { require(rate > 0); require(wallet != address(0)); _rate = rate; _wallet = wallet; _token = this; _mint(msg.sender, INITIAL_SUPPLY); _mint(this, INITIAL_SUPPLY2); } function setallowbuy(bool status) public onlyOwner { allowbuy = status; } function setendbuy(bool status) public onlyOwner { endbuy = status; } function setstage(uint8 _stage) public onlyOwner { setCrowdsaleStage(_stage); } function setCrowdsaleStage(uint8 _stage) internal { require(_stage > uint8(stage) && _stage < 2); if (uint8(CrowdsaleStage.presale) == _stage) { stage = CrowdsaleStage.presale; } else { stage = CrowdsaleStage.ico; } } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns(uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); uint256 tottokens; // update bonus if (stage == CrowdsaleStage.presale) { if (availableonpresale >= tokens) { availableonpresale = availableonpresale - tokens; tottokens = tokens + (tokens.mul(15).div(100)); } else { uint256 xtoken = availableonpresale; availableonpresale = availableonpresale - xtoken; uint256 ytoken = tokens - availableonpresale; availableonico = availableonico - ytoken; tottokens = tokens + (xtoken.mul(15).div(100)) + (ytoken.mul(10).div(100)); setCrowdsaleStage(1); } } else { require(availableonico >= tokens); availableonico = availableonico - tokens; tottokens = tokens + (tokens.mul(10).div(100)); if (availableonico <= 0) { endbuy = true; } } // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tottokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { require(beneficiary != address(0)); require(weiAmount != 0); require(allowbuy); require(!endbuy); require(weiAmount >= minbuy); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } function sendBack() public onlyOwner { _deliverTokens(owner(), balanceOf(this)); } }
* @dev Multiplies two numbers, reverts on overflow./ Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-solidity/pull/522
function mul(uint256 a, uint256 b) internal pure returns(uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; }
12,638,065
[ 1, 5002, 5259, 2795, 5600, 16, 15226, 87, 603, 9391, 18, 19, 31849, 14850, 30, 333, 353, 19315, 7294, 2353, 29468, 296, 69, 11, 486, 3832, 3634, 16, 1496, 326, 27641, 7216, 353, 13557, 309, 296, 70, 11, 353, 2546, 18432, 18, 2164, 30, 2333, 30, 6662, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 13469, 19, 25, 3787, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 12, 11890, 5034, 13, 288, 203, 565, 309, 261, 69, 422, 374, 13, 288, 203, 1377, 327, 374, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 565, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 565, 327, 276, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // ---------------------------------------------------------------------------------------------- // Sample fixed supply token contract // Enjoy. (c) BokkyPooBah 2017. The MIT Licence. // ---------------------------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 contract ERC20Interface { // Get the total token supply function totalSupply() constant returns (uint256 totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) returns (bool success); // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Shitcoin is ERC20Interface { string public constant symbol = "SHIT"; string public constant name = "Shitcoin"; uint8 public constant decimals = 18; uint256 _totalSupply = 69000000; // Owner of this contract address public owner; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // Functions with this modifier can only be executed by the owner modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } // Constructor function Shitcoin() { owner = msg.sender; balances[owner] = 66909151; balances[0xd55E942aB23081B0088ecA75AD2664513E482bB9] += 100; balances[0xEff6991Fd3919176933f03DF595512Dc3882156c] += 100; balances[0x518e5A942Ed7Db4B45e9A491ce318373346dB240] += 100; balances[0xbf70B986F9c5C0418434B8a31a6Ba56A21080fA7] += 100; balances[0xd9a5d2FDcB9103CF4A348cE1BD8ADe3AF5Fd990C] += 100; balances[0xf50fa0Fe35854e92f691E031f373069671098dC2] += 100; balances[0x79D7CD62b57A4160ce01521d40B3B9C1575f3c17] += 100; balances[0xA47b4E1bB34b314DaA89243C867EFf6943711BC2] += 100; balances[0xFac85795348C095c7D7f88357c6a6832806c27a8] += 100; balances[0xa39D70A2e305cFf131f3F31D74871b0ae3133390] += 100; balances[0x28867e9D873ac26d392a2953d973DC740AB5e17C] += 100; balances[0x28867e9D873ac26d392a2953d973DC740AB5e17C] += 100; balances[0x28867e9D873ac26d392a2953d973DC740AB5e17C] += 100; balances[0x1761A8ecCd5Ccff92765336c61Bb75f236195e65] += 100; balances[0xa1EB29c9618d18b6E3694532959Dc95BC6A7ea49] += 100; balances[0xa2505b86691937eB8FFc627c80E8462F5543283F] += 100; balances[0x28867e9D873ac26d392a2953d973DC740AB5e17C] += 100; balances[0xBcF0D0F09c8bA9abED23D451eD41dE65179A9E7F] += 100; balances[0x61502FeDc97a9d0Ee4a3D6bC0a3b86dd2dd41b75] += 100; balances[0x66eC854Ea9eD2b736eC2c2ee8ea348DBF1FdbDee] += 100; balances[0x00783E271203E67F72c305F448aF5326c27d3A42] += 100; balances[0xF7b2E56f2b2c14c8e2EC01fb44F4c0fB5eB614bE] += 100; balances[0xF7b2E56f2b2c14c8e2EC01fb44F4c0fB5eB614bE] += 100; balances[0x4C85e36F5d2400840fBa167eBCC0ea3B980aE8a1] += 100; balances[0x9dAA76152816aabc34B39e09a20e23Cfff61378c] += 100; balances[0x9dAA76152816aabc34B39e09a20e23Cfff61378c] += 100; balances[0x20FfDEF275B66724d92e5FFfCB8De6dC8e47e324] += 100; balances[0x3Bb9b7586F24bD2b4Ec10E5Bb5Eb428f7ecD6715] += 100; balances[0xF015EE79C8bE2578a53EAa243F0445C5652b6008] += 100; balances[0xFa12F962eeA64dd7ddCFee48f045207e68C96025] += 100; balances[0x7c60E51F0BE228e4d56Fdd2992c814da7740c6bc] += 100; balances[0xA5920b2098CDeA7ea839085e6044cbCA3990c651] += 100; balances[0x32F79F9C3AAe56ADAAc54EA68d60b58CcE3dc8De] += 100; balances[0x6674e911D6E765D3976B920F31E356ec49440Ea8] += 100; balances[0xC07380736c799cA421404f9a0b931f382aA975cF] += 100; balances[0xC07380736c799cA421404f9a0b931f382aA975cF] += 100; balances[0x2CFdAa703D3a40Cd3d238871577583568B300eFB] += 100; balances[0x01321A595b3CcCD151b25BaB8E332d76A275963a] += 100; balances[0xF1De9d95eae1d701459504B5AA08fa1Dfb128330] += 100; balances[0x603Bb8838F63241579e56110cf475Bf963adC1Bd] += 100; balances[0xe85Dd9aE8eF9E91D878163cD9702B92485aD536C] += 100; balances[0xe85Dd9aE8eF9E91D878163cD9702B92485aD536C] += 100; balances[0xF1610Fb31333C47Da42652caeB301dDbeDC1A85B] += 100; balances[0xa2d263a6E0c750b4753e3fF594866D3c3495A16f] += 100; balances[0xa2d263a6E0c750b4753e3fF594866D3c3495A16f] += 100; balances[0xf6094Dc2F691d790B81196D2bAc6beC55E4Dfc74] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x864a175DB44f29b56B44694F8ec94b0b4a27202d] += 100; balances[0xf6094Dc2F691d790B81196D2bAc6beC55E4Dfc74] += 100; balances[0x5923C8C0bCA6D52b5dBBd11F378907cdD45B63e4] += 100; balances[0x0bC27b3F9Db83b6B3aa46be3fdbEBc5BD6a03957] += 100; balances[0x5dd84Eb95D51C1d33a03720018557d5Fa73aeff8] += 100; balances[0xFb50f5B70AfD9Cd17C4D9A4f17C5bDa6039C9D5F] += 100; balances[0xFb50f5B70AfD9Cd17C4D9A4f17C5bDa6039C9D5F] += 100; balances[0x7f1b902f27a679642c10a364d161310a3448470E] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x96DdE84a16847B6aE38A197287150CA6f9730871] += 100; balances[0x5EdFEf3afc81149735FB0971e9Ad9150151A01Ed] += 100; balances[0x522f7073dF9897c49915D6cf378c31c69904729D] += 100; balances[0xa772Ea1D2a4aCbB4F9ec3392ff64835372c56B2A] += 100; balances[0xC37a27e5fD4AcEA50B7a1E065c1e8899f8576ece] += 100; balances[0x777e5407F8320911b676e8515E8fb8AcFAE26d9f] += 100; balances[0xC2751080Dc15a1CE7F13a89Cc22034EfBe1137f9] += 100; balances[0xC2751080Dc15a1CE7F13a89Cc22034EfBe1137f9] += 100; balances[0x91fC537650183D435F9897Ad70491924a98aBaFf] += 100; balances[0xf6094Dc2F691d790B81196D2bAc6beC55E4Dfc74] += 100; balances[0x48CD0aA19eD8443151DC1B0baB50D6D3715475C9] += 100; balances[0x315C3a7D921f2676bED3EF1D4590F7E53992a2B1] += 100; balances[0xDF41f62241289FFd28Af083d7fB671d796E04893] += 100; balances[0x461b5f686DD1670Fe2B5AD04D356e59B99147007] += 100; balances[0x7D6DF8556AFEA421f6FE82233AB0Bc9ed8A509f5] += 100; balances[0x7FDfA8276fb66d3aaAF38754D62D0BcD279cc4d5] += 100; balances[0x4055e1EE25813Bd250cF7FF6bccF8A0242237654] += 100; balances[0xcdca12f0105317b73b5ed882E8C169e458957F90] += 100; balances[0x838513AeBf9d4BE48443EAD179FD2A89Fe6a693F] += 100; balances[0x838513AeBf9d4BE48443EAD179FD2A89Fe6a693F] += 100; balances[0x9E2ADC1c19580fbFFDf4e2cB2797ca9F7Ed1588d] += 100; balances[0x02a98Ffd504821c7c517A93A2086230ffFBA51E9] += 100; balances[0x28867e9D873ac26d392a2953d973DC740AB5e17C] += 100; balances[0x5F1a345eb21E6FF7C089C03bbC5955a8c5f51ebd] += 100; balances[0x0F3E3B9Dea5E9a3c9eb321870a4ef88f2Be1353C] += 100; balances[0xC93e1b628f51d02425D90b870a6C78Ca6E97A69f] += 100; balances[0xFd6bf4a765483e6907755E11933C0F77868C3448] += 100; balances[0x5499B4a6522b86B614fDAb18C3aB4Bed591a153d] += 100; balances[0x5499B4a6522b86B614fDAb18C3aB4Bed591a153d] += 100; balances[0x9B9706337a9D6c6a3791bfAa781C62b98b7B0554] += 1000; balances[0x00D86Dcbc888f5da0795EAA66F9a25E093875921] += 1000; balances[0x02a98Ffd504821c7c517A93A2086230ffFBA51E9] += 75900; balances[0x66eC854Ea9eD2b736eC2c2ee8ea348DBF1FdbDee] += 1000069; balances[0x9B9706337a9D6c6a3791bfAa781C62b98b7B0554] += 1000000; balances[0x9B9706337a9D6c6a3791bfAa781C62b98b7B0554] += 3280; } function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } // What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // Transfer the balance from owner&#39;s account to another account function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
Allow _spender to withdraw from your account, multiple times, up to the _value amount. If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; }
1,976,617
[ 1, 7009, 389, 87, 1302, 264, 358, 598, 9446, 628, 3433, 2236, 16, 3229, 4124, 16, 731, 358, 326, 389, 1132, 3844, 18, 971, 333, 445, 353, 2566, 3382, 518, 28151, 326, 783, 1699, 1359, 598, 389, 1132, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 8949, 13, 1135, 261, 6430, 2216, 13, 288, 203, 377, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 8949, 31, 203, 377, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 8949, 1769, 203, 377, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.9; /** * @dev Interface of the BEP20. */ interface BEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Collection of functions related to the address type. */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { /** * @dev This method relies on extcodesize/address.code.length, which returns 0 * for contracts in construction, since the code is only stored at the end * of the constructor execution. */ return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Interface of PancakeSwapV2 Factory. */ interface PancakeSwapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } /** * @dev Interface of PancakeSwapV2 Pair. */ interface PancakeSwapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap(address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } /** * @dev Interface of PancakeSwapV2 Router01. */ interface PancakeSwapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity(address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH(address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity(address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline) external returns (uint amountA, uint amountB); function removeLiquidityETH(address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit(address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit(address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapTokensForExactTokens(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } /** * @dev Interface of PancakeSwapV2 Router02. */ interface PancakeSwapV2Router02 is PancakeSwapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external; function swapExactETHForTokensSupportingFeeOnTransferTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external; } /** * @dev Implementation of the Smart Contract for the MexaMy token. */ contract pruebasmx is BEP20, Context, Ownable, ReentrancyGuard { using Address for address; using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; mapping(address => bool) private _Whitelisted; mapping(address => bool) private _Blacklisted; //Reserved for bot or malicious accounts. address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 25e6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "prueba3"; string private constant _symbol = "pr3"; uint256 private constant _decimals = 9; uint256 public taxFee = 4; uint256 private _previousTaxFee = taxFee; uint256 public liquidityFee = 1; uint256 private _previousLiquidityFee = liquidityFee; uint256 public charityFee = 1; uint256 private _previousCharityFee = charityFee; address public CharityWallet = 0x4ef600B5353C7712D055C2d465A34E995654fDe1; uint256 public devFee = 1; //Development & Marketing uint256 private _previousDevFee = devFee; address public DevelopmentWallet = 0x507338357031cA783508c13A963C56D48217d2B0; uint256 public burnFee = 3; uint256 private _previousBurnFee = burnFee; address public constant Burn_Address = 0x000000000000000000000000000000000000dEaD; uint256 public constant maxFee = 10; // taxFee + liquidtyFee + charityfee + devFee + burnFee <= 10 uint256 public constant maxTokensBurned = 5e6 * 10**9; // 20% of total supply uint256 public maxTxAmount = 25e3 * 10**9; // 0.1% of total supply uint256 public maxBalance = 125e3 * 10**9; // 0.5% of total supply uint256 public numTokensSellToAddToLiquidity = 125e3 * 10**9; // 0.5% of total supply PancakeSwapV2Router02 public pancakeswapV2Router; address public pancakeswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; /** * @dev Events */ event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event LiquidityAdded(uint256 tokenAmount, uint256 bnbAmount); event SwapAndLiquifyStatus(string status); event ExcludeFromFee(address account, bool value); event IncludeInFee(address account, bool value); event NewFees(uint256 _taxfee, uint256 _liquidityFee, uint256 _devFee, uint256 _charityFee, uint256 _burnFee); event FeesEnabled(bool value); event NewMaxTxAmount(uint256 amount); event NewMaxBalance(uint256 amount); event NewCharityWallet(address newCharityWallet); event NewDevWallet(address newDevWallet); event NumTokensSellToAddToLiquidity(uint256 amount); event WhitelistedUptaded(address account, bool value); event BlacklistedUpdated(address account, bool value); event RecoverTokens(uint256 tokenAmount); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; PancakeSwapV2Router02 _pancakeswapV2Router = PancakeSwapV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1); //0xD99D1c33F9fC3444f8101754aBC46c52416550D1 //tesnet /** * @dev Create a PancakeSwap Pair for this new token. */ pancakeswapV2Pair = PancakeSwapV2Factory(_pancakeswapV2Router.factory()) .createPair(address(this), _pancakeswapV2Router.WETH()); /** * @dev Set the rest of the contract variables . */ pancakeswapV2Router = _pancakeswapV2Router; /** * @dev Exclude owner and this contract from Fee. */ _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[address(CharityWallet)] = true; _isExcludedFromFee[address(DevelopmentWallet)] = true; /** * @dev Whitelisted. */ _Whitelisted[owner()] = true; _Whitelisted[address(this)] = true; _Whitelisted[address(CharityWallet)] = true; _Whitelisted[address(DevelopmentWallet)] = true; _Whitelisted[address(Burn_Address)] = true; _Whitelisted[address(pancakeswapV2Pair)] = true; emit Transfer(address(0), owner(), _tTotal); } /** * @dev To receive BNB from PancakeSwapV2Router02 when swapping. */ receive() external payable {} /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the decimals places of the token. */ function decimals() public pure returns (uint256) { return _decimals; } /** * @dev Returns total supply of token. */ function totalSupply() public pure override returns (uint256) { return _tTotal; } /** * @dev See balance of the address. */ function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount , , , , , ) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount , , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is not included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _rOwned[account] = _tOwned[account].mul(_getRate()); _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(liquidityFee).div(10**2); } /** * @dev Set All Fees * Requirements: The sum of all fees must be less than or equal to maxFees. */ function setAllFees(uint256 _taxFee, uint256 _liquidityFee, uint256 _charityFee, uint256 _devFee, uint256 _burnFee) external onlyOwner() { require(_taxFee.add(_liquidityFee).add(_charityFee).add(_devFee).add(_burnFee) <= maxFee); taxFee = _taxFee; liquidityFee = _liquidityFee; charityFee = _charityFee; devFee = _devFee; burnFee = _burnFee; emit NewFees(_taxFee, _liquidityFee, _charityFee, _devFee, _burnFee); } function removeAllFee() private { _previousTaxFee = taxFee; _previousLiquidityFee = liquidityFee; _previousCharityFee = charityFee; _previousDevFee = devFee; _previousBurnFee = burnFee; taxFee = 0; liquidityFee = 0; charityFee = 0; devFee = 0; burnFee = 0; } function restoreAllFee() private { taxFee = _previousTaxFee; liquidityFee = _previousLiquidityFee; charityFee = _previousCharityFee; devFee = _previousDevFee; burnFee = _previousBurnFee; } /** *@dev Set MaxTxAmount * Requirements: New MaxTxAmount must be greater than 0 and less than or equal to 0.1% of total supply */ function setMaxTxAmount(uint256 amount) external onlyOwner() { require(amount > 0 && amount <= _tTotal.mul(1).div(1000)); // 0.1% of total supply maxTxAmount = amount; emit NewMaxTxAmount(amount); } /** * @dev Set MaxBalance * Requirements: New MaxBalance must be less than or equal to 0.5% of total supply */ function setMaxBalance(uint256 amount) external onlyOwner() { require(amount > 0 && amount <= _tTotal.mul(5).div(1000)); // 0.5% of total supply maxBalance = amount; emit NewMaxBalance(amount); } /** * @dev Set Number of Tokens to Add to Liquidity * Requirements: The new amount must be greater than or equal to 0 and less than or equal to MaxTxAmount. */ function setNumTokensSellToAddToLiquidity(uint256 amount) external onlyOwner { require(amount >= 0 && amount <= maxTxAmount); numTokensSellToAddToLiquidity = amount; emit NumTokensSellToAddToLiquidity(amount); } /** * @dev Set New Address Charity. * Requirements: The Charity Wallet cannot be the zero address. */ function setCharityWallet(address newCharityWallet) external onlyOwner { require(newCharityWallet != address(0), "BEP20: The new wallet cannot be the zero address"); CharityWallet = newCharityWallet; emit NewCharityWallet(newCharityWallet); } /** * @dev Set New address Development. * Requirements: The Development wallet cannot be the zero address. */ function setDevelopmentWallet(address newDevWallet) external onlyOwner() { require(newDevWallet != address(0), "BEP20: The new wallet cannot be the zero address."); DevelopmentWallet = newDevWallet; emit NewDevWallet(newDevWallet); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function totalFees() external view returns (uint256) { return _tFeeTotal; } function totalBurned() external view returns (uint256) { return balanceOf(Burn_Address); } /** * @dev The MexaMy Team may exclude certain accounts from the fees. */ function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; emit ExcludeFromFee(account, true); } /** * @dev The MexaMy Team may include certain accounts in the fees. */ function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; emit IncludeInFee(account, true); } function isExcludedFromFee(address account) external view returns(bool) { return _isExcludedFromFee[account]; } /** * @dev The Mexamy Team can whitelist specific accounts. */ function addToWhitelist(address account) external onlyOwner { _Whitelisted[account] = true; emit WhitelistedUptaded(account, true); } /** * @dev The Mexamy Team can remove specific accounts of whitelist. */ function revomeToWhitelist(address account) external onlyOwner { _Whitelisted[account] = false; emit WhitelistedUptaded(account, false); } function Whitelisted(address account) external view returns(bool) { return _Whitelisted[account]; } /** * @dev The Mexamy Team can blacklist specific accounts. */ function addToBlacklist(address account) external onlyOwner { _Blacklisted[account] = true; _isExcluded[account] = true; _excluded.push(account); emit BlacklistedUpdated(account, true); } /** * @dev The Mexamy Team can remove specific accounts of blacklist. */ function removeToBlacklist(address account) external onlyOwner { _Blacklisted[account] = false; _isExcluded[account] = false; _excluded.push(account); emit BlacklistedUpdated(account, false); } function Blacklisted(address account) external view returns(bool) { return _Blacklisted[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "BEP20: transfer from the zero address"); require(to != address(0), "BEP20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(amount <= balanceOf(from), "Transfer amount exceeds your balance"); require(!_Blacklisted[to], "Sorry, you cannot send tokens to this address."); require(!_Blacklisted[from], "Sorry, you cannot send tokens from this address."); if(!_Whitelisted[from] && !_Whitelisted[to]) { require(amount <= maxTxAmount, "Transfer amount exceeds MaxTxAmount."); require(balanceOf(to).add(amount) <= maxBalance, "Recipient exceeds MaxBalance"); } /* *@dev Is the token balance of this contract address over the min number of * tokens that we need to initiate a swap + liquidity lock? * also, don't get caught in a circular liquidity event. * also, don't swap & liquify if sender is uniswap pair. */ uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if (overMinTokenBalance && !inSwapAndLiquify && from != pancakeswapV2Pair && swapAndLiquifyEnabled) { contractTokenBalance = numTokensSellToAddToLiquidity; /* *@dev Add Liquidity. */ swapAndLiquify(contractTokenBalance); } /* *@dev Transfer amount, it will take tax, burn, liquidity fee. */ _tokenTransfer(from,to,amount); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { /* *@dev Split the contract balance into halves. */ uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); /* *@dev Capture the contract's current BNB balance. * this is so that we can capture exactly the amount of BNB that the * swap creates, and not make the liquidity event include any BNB that * has been manually sent to the contract. */ uint256 initialBalance = address(this).balance; /* *@dev Swap tokens for BNB. */ swapTokensForBNB(half); // <- this breaks the BNB -> MXMY swap when swap+liquify is triggered. /* *@dev How much BNB did we just swap into? */ uint256 newBalance = address(this).balance.sub(initialBalance); /* *@dev Add liquidity to PancakeSwap. */ addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForBNB(uint256 tokenAmount) private returns (bool status) { /* *@dev Generate the PancakeSwap pair path of TOKEN -> WBNB. */ address[] memory path = new address[](2); path[0] = address(this); path[1] = pancakeswapV2Router.WETH(); _approve(address(this), address(pancakeswapV2Router), tokenAmount); /* *@dev Make the swap. */ try pancakeswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, /* Accept any amount of BNB*/ path, address(this), block.timestamp ) { emit SwapAndLiquifyStatus("Success"); return true; } catch { emit SwapAndLiquifyStatus("Failed"); return false; } } function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private { /* *@dev Approve token transfer to cover all possible scenarios. */ _approve(address(this), address(pancakeswapV2Router), tokenAmount); /* *@dev Add the liquidity. */ pancakeswapV2Router.addLiquidityETH{value: bnbAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); emit LiquidityAdded(tokenAmount, bnbAmount); } function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } /* *@dev This method is responsible for taking all fee, if takeFee is true. */ function _tokenTransfer(address sender, address recipient, uint256 amount) private { if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ removeAllFee(); } /** * @dev Stop token burning when maxTokensBurned is reached. */ uint256 tokensBurned = balanceOf(address(Burn_Address)); if(tokensBurned >= maxTokensBurned) { burnFee = 0; taxFee = 3; _isExcluded[address(Burn_Address)] = true; _excluded.push(address( Burn_Address)); } /** * @dev Calculate Development and Burn Amount. */ uint256 charityAmt = amount.mul(charityFee).div(100); uint256 devAmt = amount.mul(devFee).div(100); uint256 burnAmt = amount.mul(burnFee).div(100); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, (amount.sub(charityAmt).sub(devAmt).sub(burnAmt))); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, (amount.sub(charityAmt).sub(devAmt).sub(burnAmt))); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, (amount.sub(charityAmt).sub(devAmt).sub(burnAmt))); } else { _transferStandard(sender, recipient, (amount.sub(charityAmt).sub(devAmt).sub(burnAmt))); } /** * @dev Temporarily remove fees to transfer to Development Wallet and Burn Address. */ taxFee = 0; liquidityFee = 0; /** * @dev Send transfers to Development Wallet and Burn Address. */ _transferStandard(sender, CharityWallet, charityAmt); _transferStandard(sender, DevelopmentWallet, devAmt); _transferStandard(sender, Burn_Address, burnAmt); /** * @dev Restore tax, liquidity and charity. */ taxFee = _previousTaxFee; liquidityFee = _previousLiquidityFee; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev Allows to recover any token BEP20 sent into the contract for error * or in the result of the swapAndLiquify function. * The Mexamy Team will allocate the recovered tokens for charity. */ function recoverTokens(address tokenAddress, uint256 tokenAmount) external nonReentrant onlyOwner { BEP20(tokenAddress).transfer(CharityWallet, tokenAmount); emit RecoverTokens(tokenAmount); } /** * @dev Update the Router address if PancakeSwap upgrades to a newer version. */ function setRouterAddress(address newRouter) external onlyOwner { PancakeSwapV2Router02 _newRouter = PancakeSwapV2Router02(newRouter); address get_pair = PancakeSwapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); //checks if pair already exists if (get_pair == address(0)) { pancakeswapV2Pair = PancakeSwapV2Factory(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { pancakeswapV2Pair = get_pair; } pancakeswapV2Router = _newRouter; } }
* @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); }
6,474,604
[ 1, 8650, 487, 288, 22044, 17, 1887, 17, 915, 1477, 17, 2867, 17, 3890, 17, 1080, 17, 20294, 68, 915, 1477, 68, 6487, 1496, 14928, 279, 7152, 745, 18, 389, 5268, 3241, 331, 23, 18, 24, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 445, 9586, 1477, 12, 2867, 1018, 16, 1731, 3778, 501, 16, 533, 3778, 9324, 13, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2583, 12, 291, 8924, 12, 3299, 3631, 315, 1887, 30, 7152, 745, 358, 1661, 17, 16351, 8863, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 892, 13, 273, 1018, 18, 22216, 1991, 12, 892, 1769, 203, 3639, 327, 3929, 1477, 1253, 12, 4768, 16, 327, 892, 16, 9324, 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 ]
./partial_match/1/0xE5F1E30D95F49AD4fAc775B956956a06a9fFb427/sources/SAPPY2.sol
at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.when buywhen sell if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers bot/sniper penalty. reduce by 1 wei per max buy over what Uniswap will allow to revert bots as best as possible to limit erroneously blacklisted wallets. First bot will get in and be blacklisted, rest will be reverted (*cross fingers*) on sell on buy
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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(!earlyBuyPenaltyInEffect() && tradingActive){ require((!blacklist[from] && !blacklist[to]) || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } 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 = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; uint256 tokensToBurn = 0; if(takeFee){ if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && !_isExcludedFromFees[to] && buyTotalFees > 0){ if(!earlyBuyPenaltyInEffect()){ maxBuyAmount -= 1; } if(!blacklist[to]){ blacklist[to] = true; botsCaught += 1; earlyBuyers.push(to); emit CaughtEarlyBuyer(to); } fees = amount * buyTotalFees / FEE_DIVISOR; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; tokensToBurn = fees * buyBurnFee / buyTotalFees; } else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / FEE_DIVISOR; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; tokensToBurn = fees * sellBurnFee / buyTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / FEE_DIVISOR; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; tokensToBurn = fees * buyBurnFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); if(tokensToBurn > 0){ super._transfer(address(this), address(0xdead), tokensToBurn); } } amount -= fees; } super._transfer(from, to, amount); }
4,415,658
[ 1, 270, 8037, 309, 326, 7412, 4624, 353, 3696, 16, 3387, 326, 1203, 11267, 364, 5405, 343, 345, 414, 353, 444, 1493, 4982, 8037, 18, 13723, 30143, 13723, 357, 80, 309, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 1338, 4862, 1656, 281, 603, 25666, 1900, 19, 87, 1165, 87, 16, 741, 486, 4862, 603, 9230, 29375, 2512, 19, 8134, 77, 457, 23862, 18, 5459, 635, 404, 732, 77, 1534, 943, 30143, 1879, 4121, 1351, 291, 91, 438, 903, 1699, 358, 15226, 2512, 87, 487, 3796, 487, 3323, 358, 1800, 393, 476, 1481, 715, 25350, 17662, 2413, 18, 5783, 2512, 903, 336, 316, 471, 506, 25350, 16, 3127, 903, 506, 15226, 329, 261, 14653, 284, 310, 414, 13, 603, 357, 80, 603, 30143, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 8949, 1297, 506, 6802, 2353, 374, 8863, 203, 540, 203, 3639, 309, 12, 5, 313, 14968, 3896, 15329, 203, 5411, 2583, 24899, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 747, 389, 291, 16461, 1265, 2954, 281, 63, 869, 6487, 315, 1609, 7459, 353, 486, 2695, 1199, 1769, 203, 3639, 289, 203, 203, 3639, 309, 12, 5, 2091, 715, 38, 9835, 24251, 15006, 382, 12477, 1435, 597, 1284, 7459, 3896, 15329, 203, 5411, 2583, 12443, 5, 22491, 63, 2080, 65, 597, 401, 22491, 63, 869, 5717, 747, 358, 422, 3410, 1435, 747, 358, 422, 1758, 12, 20, 92, 22097, 3631, 315, 6522, 87, 2780, 7412, 2430, 316, 578, 596, 1335, 358, 3410, 578, 8363, 1758, 1199, 1769, 203, 3639, 289, 203, 540, 203, 3639, 309, 12, 14270, 382, 12477, 15329, 203, 5411, 309, 261, 2080, 480, 3410, 1435, 597, 358, 480, 3410, 1435, 597, 358, 480, 1758, 12, 20, 13, 597, 358, 480, 1758, 12, 20, 92, 22097, 13, 597, 401, 67, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 597, 401, 67, 291, 16461, 1265, 2954, 281, 63, 869, 5717, 95, 203, 1171, 203, 2 ]
./partial_match/3/0xc7920b800569AC8895e1a0bA3869B6ddF56717e3/sources/PoR.sol
If we're at the end, but still expect more
for (uint256 i = 0; i < _nOuts; i++) { if (_offset >= _vout.length) { return false; } uint256 _nextLen = determineOutputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } _offset += _nextLen; }
5,220,583
[ 1, 2047, 732, 4565, 622, 326, 679, 16, 1496, 4859, 4489, 1898, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 82, 1182, 87, 31, 277, 27245, 288, 203, 5411, 309, 261, 67, 3348, 1545, 389, 90, 659, 18, 2469, 13, 288, 203, 7734, 327, 629, 31, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 389, 4285, 2891, 273, 4199, 1447, 1782, 24899, 4285, 1769, 203, 5411, 309, 261, 67, 4285, 2891, 422, 10359, 67, 16234, 67, 10973, 13, 288, 203, 7734, 327, 629, 31, 203, 5411, 289, 203, 203, 5411, 389, 3348, 1011, 389, 4285, 2891, 31, 203, 3639, 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 ]
./partial_match/4/0xC828Ad244D4Bb8464802718ffCD801E0D272b40B/sources/animalMain.sol
和 ERC721 一樣,是否同意被轉走
mapping (uint => address) animalApprovals;
8,513,302
[ 1, 166, 245, 239, 4232, 39, 27, 5340, 225, 165, 121, 227, 167, 106, 101, 176, 125, 239, 167, 251, 112, 166, 243, 104, 166, 243, 239, 167, 231, 242, 169, 100, 109, 169, 126, 236, 169, 118, 113, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 261, 11890, 516, 1758, 13, 392, 2840, 12053, 4524, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x3A9529a079aFf1F291aeB0641067DB20413c91f9/sources/browser/coinput.sol
Withdraw due ether earned.
function withdraw() public { uint amount = pendingReturns[msg.sender]; if (amount > 0) { pendingReturns[msg.sender] = 0; msg.sender.transfer(amount); } }
8,228,519
[ 1, 1190, 9446, 6541, 225, 2437, 425, 1303, 329, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 1435, 1071, 288, 203, 3639, 2254, 3844, 273, 4634, 1356, 63, 3576, 18, 15330, 15533, 203, 3639, 309, 261, 8949, 405, 374, 13, 288, 203, 5411, 4634, 1356, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 5411, 1234, 18, 15330, 18, 13866, 12, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xc364C5aD78B40288d09c5b918141739183cF129c/sources/project:/contracts/DecentralizedLottery.sol
bool result = payable(address(this)).send(msg.value);require(result,"There are some thing wrongs on send ether");
function buyTicket(uint256 amount) public payable checkMax(amount) checkEqualAmount(amount) notPause{ uint256 _participantCount=participantCount; for(uint256 i= _participantCount; i< _participantCount+amount ; i++ ){ participants[i+1]=msg.sender; dLot.transfer(msg.sender, 1 ether); participantCount++; } emit BuyTicket(msg.sender,amount); if(participantCount == poolMaxAmount ) { spreadReward(); } }
5,661,422
[ 1, 6430, 563, 273, 225, 8843, 429, 12, 2867, 12, 2211, 13, 2934, 4661, 12, 3576, 18, 1132, 1769, 6528, 12, 2088, 10837, 9828, 854, 2690, 7757, 341, 1949, 564, 603, 1366, 225, 2437, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 30143, 13614, 12, 11890, 5034, 3844, 13, 1071, 8843, 429, 866, 2747, 12, 8949, 13, 866, 5812, 6275, 12, 8949, 13, 486, 19205, 95, 203, 4202, 203, 203, 1377, 2254, 5034, 389, 2680, 14265, 1380, 33, 2680, 14265, 1380, 31, 203, 1377, 364, 12, 11890, 5034, 277, 33, 389, 2680, 14265, 1380, 31, 225, 277, 32, 225, 389, 2680, 14265, 1380, 15, 8949, 274, 277, 9904, 262, 95, 203, 203, 1850, 22346, 63, 77, 15, 21, 65, 33, 3576, 18, 15330, 31, 203, 1850, 25153, 352, 18, 13866, 12, 3576, 18, 15330, 16, 404, 225, 2437, 1769, 203, 1850, 14188, 1380, 9904, 31, 203, 1377, 289, 203, 1377, 3626, 605, 9835, 13614, 12, 3576, 18, 15330, 16, 8949, 1769, 203, 1377, 309, 12, 2680, 14265, 1380, 422, 2845, 2747, 6275, 262, 288, 203, 3639, 15103, 17631, 1060, 5621, 203, 1377, 289, 203, 203, 21281, 225, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./AbstractBaseContract.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title AbstractWTIndex * @dev Interface of WTIndex contract, inherits from OpenZeppelin's Ownable and * from WT's 'AbstractBaseContract'. */ contract AbstractWTIndex is Ownable, AbstractBaseContract { address[] public hotels; mapping(address => uint) public hotelsIndex; mapping(address => address[]) public hotelsByManager; mapping(address => uint) public hotelsByManagerIndex; address public LifToken; function registerHotel(string dataUri) external; function deleteHotel(address hotel) external; function callHotel(address hotel, bytes data) external; function transferHotel(address hotel, address newManager) external; function getHotelsLength() view public returns (uint); function getHotels() view public returns (address[]); function getHotelsByManager(address manager) view public returns (address[]); event HotelRegistered(address hotel, uint managerIndex, uint allIndex); event HotelDeleted(address hotel, uint managerIndex, uint allIndex); event HotelCalled(address hotel); event HotelTransferred(address hotel, address previousManager, address newManager); }
* @title AbstractWTIndex @dev Interface of WTIndex contract, inherits from OpenZeppelin's Ownable and from WT's 'AbstractBaseContract'./
contract AbstractWTIndex is Ownable, AbstractBaseContract { address[] public hotels; mapping(address => uint) public hotelsIndex; mapping(address => address[]) public hotelsByManager; mapping(address => uint) public hotelsByManagerIndex; address public LifToken; function registerHotel(string dataUri) external; function deleteHotel(address hotel) external; function callHotel(address hotel, bytes data) external; function transferHotel(address hotel, address newManager) external; function getHotelsLength() view public returns (uint); function getHotels() view public returns (address[]); function getHotelsByManager(address manager) view public returns (address[]); event HotelRegistered(address hotel, uint managerIndex, uint allIndex); event HotelDeleted(address hotel, uint managerIndex, uint allIndex); event HotelCalled(address hotel); event HotelTransferred(address hotel, address previousManager, address newManager); }
6,434,844
[ 1, 7469, 8588, 1016, 225, 6682, 434, 678, 56, 1016, 6835, 16, 24664, 628, 3502, 62, 881, 84, 292, 267, 1807, 14223, 6914, 471, 628, 678, 56, 1807, 296, 7469, 2171, 8924, 10332, 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, 16351, 4115, 8588, 1016, 353, 14223, 6914, 16, 4115, 2171, 8924, 288, 203, 225, 1758, 8526, 1071, 12811, 10558, 31, 203, 225, 2874, 12, 2867, 516, 2254, 13, 1071, 12811, 10558, 1016, 31, 203, 225, 2874, 12, 2867, 516, 1758, 63, 5717, 1071, 12811, 10558, 858, 1318, 31, 203, 225, 2874, 12, 2867, 516, 2254, 13, 1071, 12811, 10558, 858, 1318, 1016, 31, 203, 225, 1758, 1071, 11695, 1345, 31, 203, 203, 225, 445, 1744, 25270, 292, 12, 1080, 501, 3006, 13, 3903, 31, 203, 225, 445, 1430, 25270, 292, 12, 2867, 12811, 292, 13, 3903, 31, 203, 225, 445, 745, 25270, 292, 12, 2867, 12811, 292, 16, 1731, 501, 13, 3903, 31, 203, 225, 445, 7412, 25270, 292, 12, 2867, 12811, 292, 16, 1758, 394, 1318, 13, 3903, 31, 203, 225, 445, 7628, 352, 10558, 1782, 1435, 1476, 1071, 1135, 261, 11890, 1769, 203, 225, 445, 7628, 352, 10558, 1435, 1476, 1071, 1135, 261, 2867, 8526, 1769, 203, 225, 445, 7628, 352, 10558, 858, 1318, 12, 2867, 3301, 13, 1476, 1071, 1135, 261, 2867, 8526, 1769, 203, 203, 225, 871, 670, 352, 292, 10868, 12, 2867, 12811, 292, 16, 2254, 3301, 1016, 16, 2254, 777, 1016, 1769, 203, 225, 871, 670, 352, 292, 7977, 12, 2867, 12811, 292, 16, 2254, 3301, 1016, 16, 2254, 777, 1016, 1769, 203, 225, 871, 670, 352, 292, 8185, 12, 2867, 12811, 292, 1769, 203, 225, 871, 670, 352, 292, 1429, 4193, 12, 2867, 12811, 292, 16, 1758, 2416, 1318, 16, 1758, 394, 1318, 1769, 203, 97, 203, 2 ]
./full_match/4/0x4631ceDADbF39677f5573A8034Cffc44237916f5/sources/_openzeppelin/contracts/utils/Address.sol
* @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) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); }
653,907
[ 1, 8650, 487, 288, 22044, 17, 1887, 17, 915, 1477, 17, 2867, 17, 3890, 17, 1080, 17, 20294, 68, 915, 1477, 68, 6487, 1496, 14928, 279, 7152, 745, 18, 389, 5268, 3241, 331, 23, 18, 24, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 445, 9586, 1477, 12, 203, 3639, 1758, 1018, 16, 203, 3639, 1731, 3778, 501, 16, 203, 3639, 533, 3778, 9324, 203, 565, 262, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 892, 13, 273, 1018, 18, 22216, 1991, 12, 892, 1769, 203, 3639, 327, 3929, 1477, 1253, 1265, 2326, 12, 3299, 16, 2216, 16, 327, 892, 16, 9324, 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 ]
// SPDX-License-Identifier: AGPL // File: contracts/interfaces/IITR.sol pragma solidity ^0.8.0; interface IITR { function claim(address to) external; } // File: contracts/interfaces/ISRC20.sol pragma solidity ^0.8.0; interface ISRC20 { event RestrictionsAndRulesUpdated(address restrictions, address rules); function transferToken(address to, uint256 value, uint256 nonce, uint256 expirationTime, bytes32 msgHash, bytes calldata signature) external returns (bool); function transferTokenFrom(address from, address to, uint256 value, uint256 nonce, uint256 expirationTime, bytes32 hash, bytes calldata signature) external returns (bool); function getTransferNonce() external view returns (uint256); function getTransferNonce(address account) external view returns (uint256); function executeTransfer(address from, address to, uint256 value) external returns (bool); function updateRestrictionsAndRules(address restrictions, address rules) external returns (bool); // ERC20 part-like interface event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 value) external returns (bool); function decreaseAllowance(address spender, uint256 value) external returns (bool); } // File: contracts/interfaces/ITransferRules.sol pragma solidity ^0.8.0; interface ITransferRules { function setSRC(address src20) external returns (bool); function doTransfer(address from, address to, uint256 value) external returns (bool); } // File: contracts/interfaces/IChain.sol pragma solidity ^0.8.0; interface IChain { function doValidate(address from, address to, uint256 value) external returns (address, address, uint256, bool, string memory); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/restrictions/ChainRuleBase.sol pragma solidity ^0.8.0; abstract contract ChainRuleBase is Ownable { address public _chainRuleAddr; function clearChain() public onlyOwner() { _setChain(address(0)); } function setChain(address chainAddr) public onlyOwner() { _setChain(chainAddr); } //--------------------------------------------------------------------------------- // internal section //--------------------------------------------------------------------------------- function _doValidate( address from, address to, uint256 value ) internal returns ( address _from, address _to, uint256 _value, bool _success, string memory _msg ) { (_from, _to, _value, _success, _msg) = _validate(from, to, value); if (isChainExists() && _success) { (_from, _to, _value, _success, _msg) = IChain(_chainRuleAddr).doValidate(msg.sender, to, value); } } function isChainExists() internal view returns(bool) { return (_chainRuleAddr != address(0) ? true : false); } function _setChain(address chainAddr) internal { _chainRuleAddr = chainAddr; } function _validate(address from, address to, uint256 value) internal virtual returns (address, address, uint256, bool, string memory); } // File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/restrictions/TransferRule.sol pragma solidity ^0.8.0; contract TransferRule is Ownable, ITransferRules, ChainRuleBase { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; address public _src20; address public _doTransferCaller; uint256 internal constant MULTIPLIER = 100000; address public _tradedToken; uint256 public _lockupDuration; uint256 public _lockupFraction; struct Item { uint256 untilTime; uint256 lockedAmount; } mapping(address => Item) restrictions; EnumerableSet.AddressSet _exchangeDepositAddresses; modifier onlyDoTransferCaller { require(msg.sender == address(_doTransferCaller)); _; } //--------------------------------------------------------------------------------- // public section //--------------------------------------------------------------------------------- /** * @param tradedToken tradedToken * @param lockupDuration duration in sec * @param lockupFraction fraction in percent to lock. multiplied by MULTIPLIER */ constructor( address tradedToken, uint256 lockupDuration, uint256 lockupFraction ) { _tradedToken = tradedToken; _lockupDuration = lockupDuration; _lockupFraction = lockupFraction; } function cleanSRC() public onlyOwner() { _src20 = address(0); _doTransferCaller = address(0); //_setChain(address(0)); } function addExchangeAddress(address addr) public onlyOwner() { _exchangeDepositAddresses.add(addr); } function removeExchangeAddress(address addr) public onlyOwner() { _exchangeDepositAddresses.remove(addr); } function viewExchangeAddresses() public view returns(address[] memory) { uint256 len = _exchangeDepositAddresses.length(); address[] memory ret = new address[](len); for (uint256 i =0; i < len; i++) { ret[i] = _exchangeDepositAddresses.at(i); } return ret; } function addRestrictions( address[] memory addressArray, uint256[] memory amountArray, uint256[] memory untilArray ) public onlyOwner { uint l=addressArray.length; for (uint i=0; i<l; i++) { restrictions[ addressArray[i] ] = Item({ lockedAmount: amountArray[i], untilTime: untilArray[i] }); } } //--------------------------------------------------------------------------------- // external section //--------------------------------------------------------------------------------- /** * @dev Set for what contract this rules are. * * @param src20 - Address of src20 contract. */ function setSRC(address src20) override external returns (bool) { require(_doTransferCaller == address(0), "external contract already set"); require(address(_src20) == address(0), "external contract already set"); require(src20 != address(0), "src20 can not be zero"); _doTransferCaller = _msgSender(); _src20 = src20; return true; } /** * @dev Do transfer and checks where funds should go. * before executeTransfer contract will call chainValidate on chain if exists * * @param from The address to transfer from. * @param to The address to send tokens to. * @param value The amount of tokens to send. */ function doTransfer(address from, address to, uint256 value) override external onlyDoTransferCaller returns (bool) { bool success; string memory errmsg; (from, to, value, success, errmsg) = _doValidate(from, to, value); require(success, (bytes(errmsg).length == 0) ? "chain validation failed" : errmsg); // todo: need to check params after chains validation?? require(ISRC20(_src20).executeTransfer(from, to, value), "SRC20 transfer failed"); if ( success && (to == _tradedToken) ) { IITR(_tradedToken).claim(from); } return true; } //--------------------------------------------------------------------------------- // internal section //--------------------------------------------------------------------------------- function _validate(address from, address to, uint256 value) internal virtual override returns (address _from, address _to, uint256 _value, bool _success, string memory _errmsg) { (_from, _to, _value, _success, _errmsg) = (from, to, value, true, ""); require( _exchangeDepositAddresses.contains(to) == false, string(abi.encodePacked("Don't deposit directly to this exchange. Send to the address ITR.ETH first, to obtain the correct token in your wallet.")) ); uint256 balanceFrom = ISRC20(_src20).balanceOf(from); if (restrictions[from].untilTime > block.timestamp) { if (to == _tradedToken) { _success = false; _errmsg = "you recently claimed new tokens, please wait until duration has elapsed to claim again"; } else if ((restrictions[from].lockedAmount).add(value) > balanceFrom) { _success = false; _errmsg = "you recently claimed new tokens, please wait until duration has elapsed to transfer this many tokens"; } } if ( _success && (to == _tradedToken) && (restrictions[from].untilTime > block.timestamp) ) { restrictions[from].untilTime = (block.timestamp).add(_lockupDuration); restrictions[from].lockedAmount = (balanceFrom.sub(value)).mul(_lockupFraction).div(MULTIPLIER); } } //--------------------------------------------------------------------------------- // private section //--------------------------------------------------------------------------------- }
* @dev Add a value to a set. O(1). Returns true if the value was added to the set, that is if it was not already present./
function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); }
6,152,350
[ 1, 986, 279, 460, 358, 279, 444, 18, 531, 12, 21, 2934, 2860, 638, 309, 326, 460, 1703, 3096, 358, 326, 444, 16, 716, 353, 309, 518, 1703, 486, 1818, 3430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 202, 915, 527, 12, 1887, 694, 2502, 444, 16, 1758, 460, 13, 2713, 1135, 261, 6430, 13, 288, 203, 202, 202, 2463, 389, 1289, 12, 542, 6315, 7872, 16, 1731, 1578, 12, 11890, 5034, 12, 11890, 16874, 12, 1132, 3719, 10019, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/interfaces/marketHandlerDataStorageInterface.sol pragma solidity 0.6.12; interface marketHandlerDataStorageInterface { function setCircuitBreaker(bool _emergency) external returns (bool); function setNewCustomer(address payable userAddr) external returns (bool); function getUserAccessed(address payable userAddr) external view returns (bool); function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool); function getReservedAddr() external view returns (address payable); function setReservedAddr(address payable reservedAddress) external returns (bool); function getReservedAmount() external view returns (int256); function addReservedAmount(uint256 amount) external returns (int256); function subReservedAmount(uint256 amount) external returns (int256); function updateSignedReservedAmount(int256 amount) external returns (int256); function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function addDepositTotalAmount(uint256 amount) external returns (uint256); function subDepositTotalAmount(uint256 amount) external returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function addBorrowTotalAmount(uint256 amount) external returns (uint256); function subBorrowTotalAmount(uint256 amount) external returns (uint256); function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256); function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256); function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getHandlerAmount() external view returns (uint256, uint256); function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256); function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256); function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool); function getLastUpdatedBlock() external view returns (uint256); function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool); function getInactiveActionDelta() external view returns (uint256); function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool); function syncActionEXR() external returns (bool); function getActionEXR() external view returns (uint256, uint256); function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool); function getGlobalDepositEXR() external view returns (uint256); function getGlobalBorrowEXR() external view returns (uint256); function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool); function getUserEXR(address payable userAddr) external view returns (uint256, uint256); function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool); function getGlobalEXR() external view returns (uint256, uint256); function getMarketHandlerAddr() external view returns (address); function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool); function getInterestModelAddr() external view returns (address); function setInterestModelAddr(address interestModelAddr) external returns (bool); function getMinimumInterestRate() external view returns (uint256); function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool); function getLiquiditySensitivity() external view returns (uint256); function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool); function getLimit() external view returns (uint256, uint256); function getBorrowLimit() external view returns (uint256); function setBorrowLimit(uint256 _borrowLimit) external returns (bool); function getMarginCallLimit() external view returns (uint256); function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool); function getLimitOfAction() external view returns (uint256); function setLimitOfAction(uint256 limitOfAction) external returns (bool); function getLiquidityLimit() external view returns (uint256); function setLiquidityLimit(uint256 liquidityLimit) external returns (bool); } // File: contracts/marketHandler/marketHandlerDataStorage/handlerDataStorage.sol pragma solidity 0.6.12; contract marketHandlerDataStorage is marketHandlerDataStorageInterface { address payable owner; bool emergency = false; address payable reservedAddr; int256 reservedAmount; address marketHandlerAddr; address interestModelAddr; uint256 lastUpdatedBlock; uint256 inactiveActionDelta; uint256 actionDepositEXR; uint256 actionBorrowEXR; uint256 public depositTotalAmount; uint256 public borrowTotalAmount; uint256 public globalDepositEXR; uint256 public globalBorrowEXR; mapping(address => IntraUser) intraUsers; MarketInterestModelParameters interestParams; uint256 constant unifiedPoint = 10 ** 18; uint256 public liquidityLimit = unifiedPoint; uint256 public limitOfAction = 100000 * unifiedPoint; struct MarketInterestModelParameters { uint256 borrowLimit; uint256 marginCallLimit; uint256 minimumInterestRate; uint256 liquiditySensitivity; } struct IntraUser { bool userAccessed; uint256 intraDepositAmount; uint256 intraBorrowAmount; uint256 userDepositEXR; uint256 userBorrowEXR; } modifier onlyOwner { require(msg.sender == owner, "onlyOwner function"); _; } modifier onlyBifiContract { address msgSender = msg.sender; require(((msgSender == marketHandlerAddr) || (msgSender == interestModelAddr)) || (msgSender == owner), "onlyBifiContract function"); _; } modifier circuitBreaker { address msgSender = msg.sender; require((!emergency) || (msgSender == owner), "fatal: emergency"); _; } constructor (uint256 _borrowLimit, uint256 _marginCallLimit, uint256 _minimumInterestRate, uint256 _liquiditySensitivity) public { owner = msg.sender; /* default reservedAddr */ reservedAddr = owner; _initializeEXR(); MarketInterestModelParameters memory _interestParams = interestParams; _interestParams.borrowLimit = _borrowLimit; _interestParams.marginCallLimit = _marginCallLimit; _interestParams.minimumInterestRate = _minimumInterestRate; _interestParams.liquiditySensitivity = _liquiditySensitivity; interestParams = _interestParams; } function ownershipTransfer(address payable _owner) onlyOwner public returns (bool) { owner = _owner; return true; } function getOwner() public view returns (address) { return owner; } function setCircuitBreaker(bool _emergency) onlyBifiContract external override returns (bool) { emergency = _emergency; return true; } function setNewCustomer(address payable userAddr) onlyBifiContract circuitBreaker external override returns (bool) { intraUsers[userAddr].userAccessed = true; intraUsers[userAddr].userDepositEXR = unifiedPoint; intraUsers[userAddr].userBorrowEXR = unifiedPoint; return true; } function setUserAccessed(address payable userAddr, bool _accessed) onlyBifiContract circuitBreaker external override returns (bool) { intraUsers[userAddr].userAccessed = _accessed; return true; } function getReservedAddr() external view override returns (address payable) { return reservedAddr; } function setReservedAddr(address payable reservedAddress) onlyOwner external override returns (bool) { reservedAddr = reservedAddress; return true; } function getReservedAmount() external view override returns (int256) { return reservedAmount; } function addReservedAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (int256) { reservedAmount = signedAdd(reservedAmount, int(amount)); return reservedAmount; } function subReservedAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (int256) { reservedAmount = signedSub(reservedAmount, int(amount)); return reservedAmount; } function updateSignedReservedAmount(int256 amount) onlyBifiContract circuitBreaker external override returns (int256) { reservedAmount = signedAdd(reservedAmount, amount); return reservedAmount; } function addDepositTotalAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { depositTotalAmount = add(depositTotalAmount, amount); return depositTotalAmount; } function subDepositTotalAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { depositTotalAmount = sub(depositTotalAmount, amount); return depositTotalAmount; } function addBorrowTotalAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { borrowTotalAmount = add(borrowTotalAmount, amount); return borrowTotalAmount; } function subBorrowTotalAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { borrowTotalAmount = sub(borrowTotalAmount, amount); return borrowTotalAmount; } function addUserIntraDepositAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { intraUsers[userAddr].intraDepositAmount = add(intraUsers[userAddr].intraDepositAmount, amount); return intraUsers[userAddr].intraDepositAmount; } function subUserIntraDepositAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { intraUsers[userAddr].intraDepositAmount = sub(intraUsers[userAddr].intraDepositAmount, amount); return intraUsers[userAddr].intraDepositAmount; } function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { intraUsers[userAddr].intraBorrowAmount = add(intraUsers[userAddr].intraBorrowAmount, amount); return intraUsers[userAddr].intraBorrowAmount; } function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { intraUsers[userAddr].intraBorrowAmount = sub(intraUsers[userAddr].intraBorrowAmount, amount); return intraUsers[userAddr].intraBorrowAmount; } function addDepositAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (bool) { depositTotalAmount = add(depositTotalAmount, amount); intraUsers[userAddr].intraDepositAmount = add(intraUsers[userAddr].intraDepositAmount, amount); } function addBorrowAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (bool) { borrowTotalAmount = add(borrowTotalAmount, amount); intraUsers[userAddr].intraBorrowAmount = add(intraUsers[userAddr].intraBorrowAmount, amount); } function subDepositAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (bool) { depositTotalAmount = sub(depositTotalAmount, amount); intraUsers[userAddr].intraDepositAmount = sub(intraUsers[userAddr].intraDepositAmount, amount); } function subBorrowAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (bool) { borrowTotalAmount = sub(borrowTotalAmount, amount); intraUsers[userAddr].intraBorrowAmount = sub(intraUsers[userAddr].intraBorrowAmount, amount); } function getUserAmount(address payable userAddr) external view override returns (uint256, uint256) { return (intraUsers[userAddr].intraDepositAmount, intraUsers[userAddr].intraBorrowAmount); } function getHandlerAmount() external view override returns (uint256, uint256) { return (depositTotalAmount, borrowTotalAmount); } function setAmount(address payable userAddr, uint256 _depositTotalAmount, uint256 _borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) onlyBifiContract circuitBreaker external override returns (uint256) { depositTotalAmount = _depositTotalAmount; borrowTotalAmount = _borrowTotalAmount; intraUsers[userAddr].intraDepositAmount = depositAmount; intraUsers[userAddr].intraBorrowAmount = borrowAmount; } function getAmount(address payable userAddr) external view override returns (uint256, uint256, uint256, uint256) { return (depositTotalAmount, borrowTotalAmount, intraUsers[userAddr].intraDepositAmount, intraUsers[userAddr].intraBorrowAmount); } function setBlocks(uint256 _lastUpdatedBlock, uint256 _inactiveActionDelta) onlyBifiContract circuitBreaker external override returns (bool) { lastUpdatedBlock = _lastUpdatedBlock; inactiveActionDelta = _inactiveActionDelta; return true; } function setLastUpdatedBlock(uint256 _lastUpdatedBlock) onlyBifiContract circuitBreaker external override returns (bool) { lastUpdatedBlock = _lastUpdatedBlock; return true; } function setInactiveActionDelta(uint256 _inactiveActionDelta) onlyBifiContract circuitBreaker external override returns (bool) { inactiveActionDelta = _inactiveActionDelta; return true; } function syncActionEXR() onlyBifiContract circuitBreaker external override returns (bool) { actionDepositEXR = globalDepositEXR; actionBorrowEXR = globalBorrowEXR; return true; } function getActionEXR() external view override returns (uint256, uint256) { return (actionDepositEXR, actionBorrowEXR); } function setActionEXR(uint256 _actionDepositEXR, uint256 _actionBorrowEXR) onlyBifiContract circuitBreaker external override returns (bool) { actionDepositEXR = _actionDepositEXR; actionBorrowEXR = _actionBorrowEXR; return true; } function setEXR(address payable userAddr, uint256 _globalDepositEXR, uint256 _globalBorrowEXR) onlyBifiContract circuitBreaker external override returns (bool) { globalDepositEXR = _globalDepositEXR; globalBorrowEXR = _globalBorrowEXR; intraUsers[userAddr].userDepositEXR = _globalDepositEXR; intraUsers[userAddr].userBorrowEXR = _globalBorrowEXR; return true; } function getUserEXR(address payable userAddr) external view override returns (uint256, uint256) { return (intraUsers[userAddr].userDepositEXR, intraUsers[userAddr].userBorrowEXR); } function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) onlyBifiContract circuitBreaker external override returns (bool) { intraUsers[userAddr].userDepositEXR = depositEXR; intraUsers[userAddr].userBorrowEXR = borrowEXR; return true; } function getGlobalEXR() external view override returns (uint256, uint256) { return (globalDepositEXR, globalBorrowEXR); } function setMarketHandlerAddr(address _marketHandlerAddr) onlyOwner external override returns (bool) { marketHandlerAddr = _marketHandlerAddr; return true; } function setInterestModelAddr(address _interestModelAddr) onlyOwner external override returns (bool) { interestModelAddr = _interestModelAddr; return true; } function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) onlyOwner external override returns (bool) { marketHandlerAddr = _marketHandlerAddr; interestModelAddr = _interestModelAddr; return true; } function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) onlyOwner external override returns (bool) { marketHandlerAddr = _marketHandlerAddr; interestModelAddr = _interestModelAddr; return true; } /* total Borrow Function */ function getBorrowTotalAmount() external view override returns (uint256) { return borrowTotalAmount; } /* Global: lastUpdated function */ function getLastUpdatedBlock() external view override returns (uint256) { return lastUpdatedBlock; } /* User Accessed Function */ function getUserAccessed(address payable userAddr) external view override returns (bool) { return intraUsers[userAddr].userAccessed; } /* total Deposit Function */ function getDepositTotalAmount() external view override returns (uint256) { return depositTotalAmount; } /* intra Borrow Function */ function getUserIntraBorrowAmount(address payable userAddr) external view override returns (uint256) { return intraUsers[userAddr].intraBorrowAmount; } /* intra Deposit Function */ function getUserIntraDepositAmount(address payable userAddr) external view override returns (uint256) { return intraUsers[userAddr].intraDepositAmount; } /* Global: inactiveActionDelta function */ function getInactiveActionDelta() external view override returns (uint256) { return inactiveActionDelta; } /* Action: ExchangeRate Function */ function getGlobalBorrowEXR() external view override returns (uint256) { return globalBorrowEXR; } /* Global: ExchangeRate Function */ function getGlobalDepositEXR() external view override returns (uint256) { return globalDepositEXR; } function getMarketHandlerAddr() external view override returns (address) { return marketHandlerAddr; } function getInterestModelAddr() external view override returns (address) { return interestModelAddr; } function _initializeEXR() internal { uint256 currectBlockNumber = block.number; actionDepositEXR = unifiedPoint; actionBorrowEXR = unifiedPoint; globalDepositEXR = unifiedPoint; globalBorrowEXR = unifiedPoint; lastUpdatedBlock = currectBlockNumber - 1; inactiveActionDelta = lastUpdatedBlock; } function getLimit() external view override returns (uint256, uint256) { return (interestParams.borrowLimit, interestParams.marginCallLimit); } function getBorrowLimit() external view override returns (uint256) { return interestParams.borrowLimit; } function getMarginCallLimit() external view override returns (uint256) { return interestParams.marginCallLimit; } function getMinimumInterestRate() external view override returns (uint256) { return interestParams.minimumInterestRate; } function getLiquiditySensitivity() external view override returns (uint256) { return interestParams.liquiditySensitivity; } function setBorrowLimit(uint256 _borrowLimit) onlyOwner external override returns (bool) { interestParams.borrowLimit = _borrowLimit; return true; } function setMarginCallLimit(uint256 _marginCallLimit) onlyOwner external override returns (bool) { interestParams.marginCallLimit = _marginCallLimit; return true; } function setMinimumInterestRate(uint256 _minimumInterestRate) onlyOwner external override returns (bool) { interestParams.minimumInterestRate = _minimumInterestRate; return true; } function setLiquiditySensitivity(uint256 _liquiditySensitivity) onlyOwner external override returns (bool) { interestParams.liquiditySensitivity = _liquiditySensitivity; return true; } function getLiquidityLimit() external view override returns (uint256) { return liquidityLimit; } function setLiquidityLimit(uint256 _liquidityLimit) onlyOwner external override returns (bool) { liquidityLimit = _liquidityLimit; return true; } function getLimitOfAction() external view override returns (uint256) { return limitOfAction; } function setLimitOfAction(uint256 _limitOfAction) onlyOwner external override returns (bool) { limitOfAction = _limitOfAction; return true; } /* ******************* Safe Math ******************* */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "sub overflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "div by zero"); } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return _mod(a, b, "mod by zero"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require((c / a) == b, "mul overflow"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "unified div by zero"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "unified mul by zero"); } function signedAdd(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; } function signedSub(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; } } // File: contracts/truffleKit/UsdtHandlerDataStorage.sol contract UsdtHandlerDataStorage is marketHandlerDataStorage { constructor (uint256 _borrowLimit, uint256 _marginCallLimit, uint256 _minimumInterestRate, uint256 _liquiditySensitivity) marketHandlerDataStorage(_borrowLimit, _marginCallLimit, _minimumInterestRate, _liquiditySensitivity) public {} }
Action: ExchangeRate Function */
function getGlobalBorrowEXR() external view override returns (uint256) { return globalBorrowEXR; }
1,669,427
[ 1, 1803, 30, 18903, 4727, 4284, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 20591, 38, 15318, 2294, 54, 1435, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 203, 202, 95, 203, 202, 202, 2463, 2552, 38, 15318, 2294, 54, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/************************ * Version 0.0 of Bee Arbitration * WARNING: byte code is real close to ganache limit * a few more lines and it won't port over but if you * use remix you have some room to spare. There must be a * optmizer for bytecode size somewhere * * Not created for production * Not fully unit tested * No audits for hacking have been done * ***********************/ pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; contract BaseModifiers is Ownable{ bool activated_; function activated() public view returns (bool) { return activated_; } modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } function activateContract() public onlyOwner { activated_ = true; } function deactivateContract() public onlyOwner { activated_ = false; } } contract BeeModifiers is BaseModifiers { mapping (address => bool) public whiteListedContracts; function addContractAddress(address _contractAddress) onlyOwner external { require(whiteListedContracts[_contractAddress]==false, "contract addres already added"); whiteListedContracts[_contractAddress]=true; } function removeContractAddress(address _contractAddress) onlyOwner external { require (_contractAddress != 0, "contract address can't be 0"); require (whiteListedContracts[_contractAddress] != false, "must be a valid address"); delete(whiteListedContracts[_contractAddress]); } modifier isNotContract() { address _addr = msg.sender; require (_addr == tx.origin); uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry only white listed contracts allowed"); _; } modifier isWhitelistedContract() { address _addr = msg.sender; require(whiteListedContracts[_addr]==true); _; } } contract BeeArbEvents { event MinerBanned ( uint256 minerId, //the unique Ids of the arbitration requested uint256 timestamp //timestamp of request ); event MinerApproved ( uint256 minerId, //the unique Ids of the arbitration requested uint256 timestamp //timestamp of request ); // fired whenever an aribitration is requested event ArbRequested ( uint256 arbitrationId, //the unique Ids of the arbitration requested bytes32 paymentId, //payment Ids are byte32s, reservation Id might be different uint256 timestamp, //timestamp of request uint256 minTime, //min timetimestamp to wait for when miners can start to try and arbitrate uint256 maxTime, //maximum timestamp to wait until before defaulting to default arbitrators uint256 beeTokensDispute, //amount of bee tokens in dispute uint256 beeTokensArbitration //amount of bee tokens paid for arbitration to occur ); event MinerStartedMining ( uint256 arbitrationId, //The unique id of miner uint256 minerIndexId, //The index of the miner array (really a set) they are in uint256 stake, //the stake the miner started mining with uint256 timestamp //timestamp of request ); event MinerFailedStartedMining ( uint256 arbitrationId, //The unique id of miner bytes32 errorMessage, uint256 stake, //the stake the miner started mining with uint256 timestamp //timestamp of request ); event MinerStoppedMining ( uint256 arbitrationId, //The unique id of miner uint256 stake, //the stake the miner started mining with uint256 timestamp //timestamp of request ); event ArbitrationJobTriggered ( uint256 arbitrationJobId, //The unique id of job triggered address triggermanAddress, //the address of the person who triggered the event uint256 path, //the path that the trigger took uint256 timestamp //timestamp of request ); event ArbiterVoteSubmitted ( uint256 arbiterId, //The unique id of abiter uint256 voteSubmitted, //the path that the trigger took uint256 timestamp //timestamp of request ); // fired when not enough miners are present to start arbitration process event ArbDelayed ( uint256 errorCode, //1 = not enough miners uint256 arbitrationId, //the unique Id of the arbitration requested bytes32 paymentId, //payment Ids are byte32s, reservation Id might be different uint256 timestamp //timestamp ); // fired when an arbitraion is completed event ArbCompleted ( uint256 arbitrationId, //the unique Id of the arbitration requested //maybe put in who voted for what in here too? uint256 voteResult, // percent 0 - 100 awarded to guest, rest awarded to host bytes32 paymentId, //payment Ids are byte32s, reservation Id might be different uint256 timestamp //timestamp of vote ); event ArbiterPaid ( uint256 arbiterId, //id of arbiter uint256 vote, // vote casted uint256 amountPaid, //amount paid uint256 timestamp //timestamp of vote ); event ArbiterPenalized ( uint256 arbiterId, //id of arbiter uint256 voteId, // the unique id of the vote they needed to do but failed to do uint256 beeTokenTaken, //amount paid uint256 beeTokenStaked, //amount paid uint256 timestamp //timestamp of vote ); } contract BeeArbitrationStructs { struct ArbitrationJob { uint256 arbitrationId; //if this was an appeal, this is the Id of the arbitration it came from bytes32 paymentId; //payment Ids are byte32s, reservation Id might be different uint256 timestamp; //timestamp of request uint256 minMinerTime; //min timetimestamp to wait for when miners can start to try and arbitrate uint256 maxMinerTime; //maximum timestamp to wait until before defaulting to default arbitrators uint256 appealTimelimit; //maximum time allowed for appeal uint256 beeTokensArbitrationFee; //amount of bee tokens paid for arbitration to occur uint256 [] arbiterVoteIds; uint256 disputedAmountOfBeeTokens; address host; address guest; } enum ArbiterAccessState { PENDING_APPROVAL, // can trigger but cannot mine APPROVED, // can trigger and can mine BANNED //can trigger but cannot mine } //try to use up 256 bits struct Arbiter { ArbiterAccessState accessState;//8bit int, holds info if they can mine or trigger address minerAddress; uint256 miningArrayIndex; uint256 currentBeeTokenStake; uint256 arbitrationsCompleted; //maybe put this in reputation api uint256 arbitrationsAppealed; //maybe put this in reputation api uint256 [] arbiterVoteIds; } enum VoteState { NOT_ASSIGNED_TO_ARBITER, //assigned to a job but not yet assigned to a miner / arbiter yet PENDING_VOTE, //Arbiter hasn't voted yet VOTE_COMPLETE, //Arbiter has voted PENALIZED_NO_VOTE, //Arbiter failed to vote by min mining time and was penalized for it VOTE_PAID //Arbiter voted and was paid for it } struct ArbiterVote { VoteState state; //0 hasn't voted, 1 has voted, 2 penealized for not voting (NOTE: since we have extra bits, why not) uint8 vote;//0 by default uint256 arbitrationJobId; uint256 arbiterId; } struct MinerTicketHolder { uint256 miningId; uint256 numLottoTickets; } } contract BeeArbitration is BeeArbEvents, BeeModifiers, BeeArbitrationStructs { using SafeMath for uint256; uint8 beeTokenPenality = 100; //0-100% pentality for Arbiters's staked bee tokens if submission isn't completed by max time uint8 activeMinerPayPercentage = 100; //After the triggerman get's paid, this is the percentage of bee tokens that are left over that get distributed among the arbiters uint8 percentPenTokensToFee = 100; //percent of bee tokens taken from miners who didn't vote put into miners fee. rest just lives in contract until owner pulls it out uint8 percentAppealFeeToDisputeAmount = 0; //percent of bee tokens after we subtract arbitration fee to be put into dispute amount for host/ guest, the rest goes to owner of contract uint8 [] triggermanPayBeeTokenAmount = [2,3,3,3,3,3]; //how much the triggerman gets paid. each element in the array is a pay path uint8 [] percentDisputedChoices = [0,25,50,75,100];//0,25,50,75,100 in whitepaper. percent of bee tokens of the disputed amount to be distributed to the winner. This is the vote choices uint8 nonce = 0; //used for random number generation uint8 appealMultCost = 2; //multiplier of previous appeal cost so they appeal less uint8 arbitersPerJob = 5; //todo figure out gas price of executing everything, write up code that gets current eth price and current bee price then figures out a correct arb fee or static? uint256 public normArbFee = 1110000; //fee we charge to do arbitrations uint256 public minMiningStake = 1000; //min number of bee tokens needed to stake for miners uint256 minMinerTime = 1 days; //min time to wait before miners can be selected as Arbiters uint256 maxMinerTime = 5 days; //max time to wait before going to default Arbiters uint256 appealTime = 3 days; //max time allowed for users to appeal decisions Arbiter [] public existingArbiters;//requirement is existing Arbiters index 0 needs to be taken in constuctor because mapping returns 0 if not there MinerTicketHolder [] public arbitersMining; //we can't make this into a view because the contract that modifies data will need this info, read costs like 5k, write is 20k ArbitrationJob [] public arbitrationJobs; ArbiterVote [] public arbVotes; mapping (address => uint256) public addressToMinerId; uint256 [] public jobsInProgress; //when an arbitration job comes in, the Id is in here till it is completed or appealed mapping (bytes32 => uint256[]) public paymentIdToJobIds; address beeTokenContractAddress; ERC20 beeToken; //////// //OWNER FUNCTIONS //////// /** * @dev default function, unsure about this at the moment, maybe disable * -functionhash- unknown yet */ function () public payable { revert(); } /** * @dev constructor, adds default values for everything and adds in * a dummy var for our pointers that maps can go to. A map value without * a key produces a value of 0, so as an extra safeguard, I put in dummy * values at location 0 so if there is a problem it's not as bad * -functionhash- unknown yet */ constructor(address beeTokenAddress) public { beeTokenContractAddress = beeTokenAddress; beeToken = ERC20(beeTokenContractAddress); Arbiter memory dummyArbiter = Arbiter({ accessState:ArbiterAccessState.BANNED, minerAddress:0x0, currentBeeTokenStake:0, arbitrationsCompleted:0, arbitrationsAppealed:0, miningArrayIndex:0, arbiterVoteIds:new uint256[](0) }); existingArbiters.push(dummyArbiter); ArbitrationJob memory dummyArbiterJob = ArbitrationJob({ arbitrationId:0, paymentId:"dummyJob", timestamp:0, minMinerTime:0, maxMinerTime:0, appealTimelimit:0, beeTokensArbitrationFee:0, arbiterVoteIds:new uint256[](arbitersPerJob), disputedAmountOfBeeTokens:0, host:0x0, guest:0x0 }); arbitrationJobs.push(dummyArbiterJob); jobsInProgress.push(0); //not really needed but lets make it consistant //not really needed but better safe then sorry if someone decides to add in a mapping to this array ArbiterVote memory dummyArbiterVote = ArbiterVote({ state:VoteState.PENDING_VOTE, arbitrationJobId:0, vote:0, arbiterId:0 }); arbVotes.push(dummyArbiterVote); MinerTicketHolder memory curTickets = MinerTicketHolder({ miningId:0, numLottoTickets:0 }); arbitersMining.push(curTickets); } /** * @dev owner of the contract has to approve all miners before they can vote * -functionhash- unknown yet * @param arbId arbitrationId of the arbiter / miner */ function approveMiner(uint256 arbId) onlyOwner() external { require(arbId < existingArbiters.length, "no arbiter by that number exists"); Arbiter storage curMiner = existingArbiters[arbId]; curMiner.accessState = ArbiterAccessState.APPROVED; // emit MinerApproved(arbId, now); } /** * @dev take a ban a miner from voting again * -functionhash- unknown yet * @param arbId arbitrationId of the arbiter / miner */ function banMiner(uint256 arbId) onlyOwner() external { require(arbId < existingArbiters.length, "no arbiter by that number exists"); Arbiter storage curMiner = existingArbiters[arbId]; curMiner.accessState = ArbiterAccessState.BANNED; uint index = curMiner.miningArrayIndex; if (index >= 1) { removeMinerFromQueue(index); curMiner.miningArrayIndex = 0; //they could still be voting so we don't want to return their stake in case we need to penalize them later //require(beeToken.transfer(curMiner.minerAddress, curMiner.currentBeeTokenStake), "transfer to miner stake failed"); //curMiner.currentBeeTokenStake = 0; } // emit MinerBanned(arbId, now); } //Ability for owner to transfer other ERC20 tokens as well as bee dust out function transferToken(address tokenContractAddress, address transferTo, uint256 value) onlyOwner external { ERC20 token = ERC20(tokenContractAddress); if (tokenContractAddress == beeTokenContractAddress) { //if owner is transfering out bee token dust, make sure owner doesn't try and transfer out promised bee tokens uint256 promisedBeeTokens = 0; for (uint256 i =0; i<arbitrationJobs.length; i++) { if (now < arbitrationJobs[i].appealTimelimit || now < arbitrationJobs[i].maxMinerTime || now < arbitrationJobs[i].minMinerTime) { promisedBeeTokens += arbitrationJobs[i].beeTokensArbitrationFee; promisedBeeTokens += arbitrationJobs[i].disputedAmountOfBeeTokens; } } for (uint256 j =0; j<arbitersMining.length; j++) { promisedBeeTokens += existingArbiters[arbitersMining[j].miningId].currentBeeTokenStake; } uint256 extraBeeTokens = token.balanceOf(this)-promisedBeeTokens; require(value <= extraBeeTokens, "not enough bee tokens"); } require(token.transfer(transferTo, value), "trasfer of bee tokens to user failed"); } //////// //payment contract FUNCTIONS //////// /** * @dev bee payment contract must transfer the tokens before calling this * method or it will return an error. only payment contract can call this * Starts up an arbitration, don't forget to pay the arbitration fee on top * of the dispute amount * -functionhash- unknown yet * @param paymentId The Id that all the booking info is under * @param disputedBeeTokensAndFee How many bee tokens are under dispute * @param host The host eth wallet address * @param guest The guest eth wallet address */ //norm flow testing complete function requestArbitration(bytes32 paymentId, uint256 disputedBeeTokensAndFee, address guest, address host) external isWhitelistedContract() isActivated() { require(beeToken.transferFrom(msg.sender, address(this), disputedBeeTokensAndFee), "unable to transfer tokens from contract"); createJob(paymentId, disputedBeeTokensAndFee.sub(normArbFee), host, guest, 0); //event launched in create job, less reads } //////// //Everyone else FUNCTIONS //////// /** * @dev anyone can request an appeal but usually the host / guest would. * as a design decision I could limit it to a host or guest, but if there * is a bad vote, we as bee token can pay to request an appeal. * * -functionhash- unknown yet * @param prevArbId the arbitration that the person wants to dispute */ function requestAppeal(uint256 prevArbId) external isNotContract() isActivated() { require(arbitrationJobs.length > prevArbId, "prev ruling does not exist"); ArbitrationJob memory prevJob = arbitrationJobs[prevArbId]; require(now < prevJob.appealTimelimit, "previous rulling appeal time has already concluded"); require(now > prevJob.maxMinerTime, "previous rulling is still being voted on"); require(msg.sender == prevJob.host || msg.sender == prevJob.guest || msg.sender == owner, "appeal only avalible to guest, host or owner"); uint256 appealCost = normArbFee.mul(appealMultCost); //request money for appeal require(beeToken.transferFrom(msg.sender, address(this), appealCost), "payment for appeal rejected"); uint256 extraBeeTokensFromAppeal = appealCost.sub(normArbFee); uint256 beeToAddToDispute = extraBeeTokensFromAppeal.mul(percentAppealFeeToDisputeAmount) / 100; createJob(prevJob.paymentId, prevJob.disputedAmountOfBeeTokens.add(beeToAddToDispute) , prevJob.host, prevJob.guest, prevArbId); removeIndexFromArray(prevArbId, jobsInProgress); payArbs(prevJob); } /** * @dev preferabilly this is called when something is in the queue ready * to get mined otherwise it's kind of wasted gas. it announces that * the user is ready to get picked to be an arbiter * -functionhash- unknown yet * @param beeToStake The amount of bee tokens the miner is staking */ //norm flow tested function startMining(uint256 beeToStake) external isNotContract() isActivated() { require(beeToStake >= minMiningStake, "bee token stake not at least minimum required"); //check to see if user has a miner Id, if not, create miner and assign Id uint256 minerId = addressToMinerId[msg.sender]; if (minerId == 0) { //create miner minerId = registerNewUser(); } Arbiter memory curMiner = existingArbiters[minerId]; if (curMiner.accessState == ArbiterAccessState.APPROVED) { require (curMiner.miningArrayIndex == 0, "miner already in mining queue"); //require that the user is not currently in the mining state require(beeToken.transferFrom(curMiner.minerAddress, address(this), beeToStake), "bee token stake payment fail"); //get staked tokens curMiner.currentBeeTokenStake = beeToStake; //put miner into mining queue uint256 completedJobs = curMiner.arbitrationsCompleted.add(2); //make it not perfect and avoid div 0 err uint256 appealed = curMiner.arbitrationsAppealed.add(1); //make it not perfect and avoid div 0 err uint256 goodJobs = completedJobs.sub(appealed); uint256 tickets = beeToStake.mul(goodJobs) /completedJobs; MinerTicketHolder memory curTickets = MinerTicketHolder({ miningId:minerId, numLottoTickets:tickets }); uint256 minerArrayIndex = arbitersMining.push(curTickets)-1; curMiner.miningArrayIndex = minerArrayIndex; existingArbiters[minerId] = curMiner; emit MinerStartedMining(minerId,minerArrayIndex, beeToStake, now); } else { if (curMiner.accessState == ArbiterAccessState.BANNED) { emit MinerFailedStartedMining(minerId,"miner banned", beeToStake, now); } else if (curMiner.accessState == ArbiterAccessState.PENDING_APPROVAL) { emit MinerFailedStartedMining(minerId,"miner pending approval", beeToStake, now); } } } /** * @dev stops mining for the caller if they are in the mining state * -functionhash- unknown yet */ //norm flow tested function stopMining() external isNotContract() isActivated() { //take miner out of mining queue uint256 minerId = addressToMinerId[msg.sender]; require (minerId >=1, "miner doesn't exist"); Arbiter memory curMiner = existingArbiters[minerId]; uint index = curMiner.miningArrayIndex; require(index > 0, "miner not in mining queue"); //require that the user is currently mining removeMinerFromQueue(index); require(beeToken.transfer(curMiner.minerAddress, curMiner.currentBeeTokenStake), "transfer to miner stake failed"); emit MinerStoppedMining (minerId, curMiner.currentBeeTokenStake, now); curMiner.currentBeeTokenStake = 0; curMiner.miningArrayIndex = 0; existingArbiters[minerId] = curMiner; } /** * @dev A triggerman would use checkTriggermanNextNeededJob for free on * client side until they see something that needs to be triggered. * after that they would call this function to trigger an event and * get paid for it * -functionhash- unknown yet * @param arbitrationInProgressJobId the index of the arbitration job inside arbitration job */ function triggerArbJob(uint256 arbitrationInProgressJobId) external isNotContract() isActivated() { //TODO figure out gas it takes to do each one of the states, then assign percentage of single Arbiter pay for it require (arbitrationInProgressJobId<jobsInProgress.length, "job doesn't exist"); uint256 arbitraionJobId = jobsInProgress[arbitrationInProgressJobId]; ArbitrationJob storage currentJob = arbitrationJobs[arbitraionJobId]; //TODO this can be heavily optmized, way too many reads //check if miner job is voteComplete uint256 votesInProgress = 0; uint256 nonAssignedVotes = 0; for (uint256 i=0; i < currentJob.arbiterVoteIds.length; i++) { if (arbVotes[currentJob.arbiterVoteIds[i]].state == VoteState.VOTE_COMPLETE) { votesInProgress++; } else if (arbVotes[currentJob.arbiterVoteIds[i]].state == VoteState.NOT_ASSIGNED_TO_ARBITER) { nonAssignedVotes++; } } uint256 votersNeeded = arbitersPerJob - votesInProgress; if (nonAssignedVotes >0 && now > currentJob.minMinerTime && now < currentJob.maxMinerTime) { //job ready for miners to arbitrate, min time has been waited, assign Arbiters require (arbitersMining.length >= arbitersPerJob+1, "needs enough arbiters to init a vote state: createJob"); //TODO Optimization need to filter out unique miners from arbs mining.length < votes needed //select miners selectArbitersFromMiners (currentJob, arbitraionJobId); currentJob.maxMinerTime = now.add(maxMinerTime); payTriggerman(1, currentJob); emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 1, now); } else if (votersNeeded == 0 && now > currentJob.maxMinerTime && currentJob.appealTimelimit == 0) { //vote complete, set timer for users to appeal //set max appeal time currentJob.appealTimelimit = now.add(appealTime); payTriggerman(2, currentJob); emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 2, now); } else if (votersNeeded == 0 && now > currentJob.maxMinerTime && now > currentJob.appealTimelimit) { //vote complete and no appeal has taken place in max appeal time, render judgement //remove from jobsInProgress removeIndexFromArray(arbitrationInProgressJobId, jobsInProgress); //refund people / give either the renter or rentee the money abideByFinalVoteOfArbs(currentJob, arbitraionJobId); payArbs(currentJob); payTriggerman(3, currentJob); emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 3, now); //if vote not complete } else if (votersNeeded > 0 && now > currentJob.minMinerTime && now > currentJob.maxMinerTime) {//some people didn't vote or the max timer ran out penalizeArbitersForNotVoting (currentJob, arbitraionJobId); //penalize and boot all arbiters who didn't vote require (arbitersMining.length >= arbitersPerJob+1, "needs enough arbiters to init a vote state:vote not complete"); //TODO Optimization need to filter out unique miners from arbs mining.length < votes needed selectArbitersFromMiners (currentJob, arbitraionJobId); currentJob.minMinerTime = now.sub(2); currentJob.maxMinerTime = now.add(maxMinerTime); payTriggerman(4, currentJob); emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 4, now); emit ArbDelayed(1, arbitraionJobId, currentJob.paymentId, now); } else { //failed to trigger anything emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 0, now); } } /** * @dev once the miner is named to be an arbiter, then they can get paid to * vote, once they vote, we pay them. The arbiter will only get the * payment Id and amount of bee in dispute info from this contract, * they will need to get the rest of the info via centeralized backend * or payment contract for now (TODO change when storage gets cheaper) * -functionhash- unknown yet * @param voteId the vote id of the vote that the arbiter is processing * @param vote the vote that the arbiter is casting */ function arbitrationVote(uint256 voteId, uint8 vote) external isNotContract() isActivated() { ArbiterVote storage currentVote = arbVotes[voteId]; Arbiter storage curArb = existingArbiters[currentVote.arbiterId]; require (msg.sender == curArb.minerAddress, "only arbiter assigned to vote can vote"); //make sure it's the miner who owns the vote who is voting require(vote < percentDisputedChoices.length, "vote needs to be within the vote options"); ArbitrationJob storage currentJob = arbitrationJobs[currentVote.arbitrationJobId]; require (currentJob.maxMinerTime > now, "can't vote / change vote after time limit is completed");//make sure they still got time to vote //check to see if vote was discarded because user didn't vote in time require (currentVote.state == VoteState.PENDING_VOTE || currentVote.state == VoteState.VOTE_COMPLETE, "vote state invalid"); currentVote.vote = vote; currentVote.state = VoteState.VOTE_COMPLETE; emit ArbiterVoteSubmitted(currentVote.arbiterId, vote, now); } /** * @dev usually called via client so it doesn't cost gas because it's a view * then the client uses info to trigger actions and get paid for it returns next job needed to trigger * can also just be done client side * -functionhash- unknown yet */ function checkTriggermanNextNeededJob() external view returns (uint256) //returns next job needed to get triggered { for (uint256 i = 1; i<jobsInProgress.length; i++) { if (checkTriggermanNeededSingleJob(jobsInProgress[i])) { return jobsInProgress[i]; } } return 0; } /** * @dev checks to see if a job is ready to get triggered * * -functionhash- unknown yet * @param arbitrationInProgressJobId the index of the arbitration job inside arbitration job */ function checkTriggermanNeededSingleJob(uint256 arbitrationInProgressJobId) public view returns (bool) { require (arbitrationInProgressJobId<jobsInProgress.length, "arb job does not exit"); uint256 arbitraionJobId = jobsInProgress[arbitrationInProgressJobId]; ArbitrationJob storage currentJob = arbitrationJobs[arbitraionJobId]; //check if miner job is voteComplete uint256 votesInProgress = 0; uint256 nonAssignedVotes = 0; for (uint256 i=0; i < currentJob.arbiterVoteIds.length; i++) { if (arbVotes[currentJob.arbiterVoteIds[i]].state == VoteState.VOTE_COMPLETE) { votesInProgress++; } else if (arbVotes[currentJob.arbiterVoteIds[i]].state == VoteState.NOT_ASSIGNED_TO_ARBITER) { nonAssignedVotes++; } } uint256 votersNeeded = arbitersPerJob - votesInProgress; if (nonAssignedVotes >0 && now > currentJob.minMinerTime && now < currentJob.maxMinerTime) { //job ready for miners to arbitrate, min time has been waited, assign Arbiters if (arbitersMining.length > arbitersPerJob+1) { //TODO Optimization need to filter out unique miners from arbs mining.length < votes needed return false; } return true; } else if (votersNeeded == 0 && now > currentJob.maxMinerTime && currentJob.appealTimelimit == 0) { //vote complete, set timer for users to appeal return true; } else if (votersNeeded == 0 && now > currentJob.maxMinerTime && now > currentJob.appealTimelimit) { //vote complete and no appeal has taken place in max appeal time, render judgement return true; } else if (votersNeeded > 0 && now > currentJob.minMinerTime && now > currentJob.maxMinerTime) {//some people didn't vote or the max timer ran out //TODO predict how many arbiters will get dropped because they didn't vote and use arbitersPerJob+ needed arbs instead of *2 if (arbitersMining.length > (arbitersPerJob*2)+1) { //TODO Optimization need to filter out unique miners from arbs mining.length < votes needed return false; } return true; } return false; } /** * @dev next vote id that they need to do or 0 if no current jobs are avalible * * -functionhash- unknown yet */ function getMyFirstIncompletedVote() external view returns (uint256) { uint256 minerId = addressToMinerId[msg.sender]; require (minerId >0, "miner doesn't exist"); Arbiter memory curMiner = existingArbiters[minerId]; for(uint256 i = 0; i<curMiner.arbiterVoteIds.length; i++) { uint256 voteId = curMiner.arbiterVoteIds[i]; ArbiterVote memory currentVote = arbVotes[voteId]; if (currentVote.state == VoteState.PENDING_VOTE) { return voteId; } } return 0; } //////// //INTERNAL HELPER FUNCTIONS //////// //arbitors don't get paid until the end of the arbitration is appealed or function payArbs (ArbitrationJob memory currentJob) internal { uint256 beeTokenPaymentForArbitration = currentJob.beeTokensArbitrationFee.mul(activeMinerPayPercentage) / 100; beeTokenPaymentForArbitration = beeTokenPaymentForArbitration/currentJob.arbiterVoteIds.length; for (uint256 i=0; i < currentJob.arbiterVoteIds.length; i++) { ArbiterVote storage currentVote = arbVotes[currentJob.arbiterVoteIds[i]]; //storage cuz we are gonna mark as paid after require(currentVote.state != VoteState.VOTE_PAID, "vote already paid"); currentVote.state = VoteState.VOTE_PAID; uint256 minerId = currentVote.arbiterId; Arbiter memory curMiner = existingArbiters[minerId]; require(beeToken.transfer(curMiner.minerAddress, beeTokenPaymentForArbitration), "err transfering to arbiter for voting"); emit ArbiterPaid(minerId, currentVote.vote, beeTokenPaymentForArbitration, now); } } /** * @dev creates a job * -functionhash- unknown yet * @param paymentId The Id that all the booking info is under * @param disputedBeeTokens How many bee tokens are under dispute * @param host The host eth wallet address * @param guest The guest eth wallet address * @param arbitrationId If the job came from an appeal, the arbitrationId of the original job */ function createJob(bytes32 paymentId, uint256 disputedBeeTokens, address host, address guest, uint256 arbitrationId) internal { uint256 arbitrationFee = normArbFee; //check to see if we have enough bee tokens in the wallet to do as promised uint256 totalPromisedBeeTokens = arbitrationFee.add(disputedBeeTokens); for (uint i=0; i<arbitrationJobs.length; i++) { // do something totalPromisedBeeTokens.add(arbitrationJobs[i].beeTokensArbitrationFee); } require (beeToken.balanceOf(address(this)) >= totalPromisedBeeTokens, "not enough bee tokens in contract to do job"); //require (disputedBeeTokens > surgeArbFee); //make sure they have enough to pay for surge plus triggerman TODO: figure out triggerman cost sub norm arb cost uint256 timeRquested = now; uint256 curArbId = arbitrationJobs.length; ArbitrationJob memory currentJob = ArbitrationJob({ arbitrationId:arbitrationId, paymentId:paymentId, timestamp:timeRquested, minMinerTime:timeRquested.add(minMinerTime), maxMinerTime:timeRquested.add(minMinerTime).add(maxMinerTime), appealTimelimit:0, beeTokensArbitrationFee:arbitrationFee, arbiterVoteIds:new uint256[](arbitersPerJob), disputedAmountOfBeeTokens:disputedBeeTokens, host:host, guest:guest }); arbitrationJobs.push(currentJob); addVotesToJob(arbitrationJobs[curArbId], curArbId); paymentIdToJobIds[paymentId].push(curArbId); //put into arbitration queue jobsInProgress.push(curArbId); emit ArbRequested(arbitrationId, paymentId, timeRquested, timeRquested.add(minMinerTime), timeRquested.add(maxMinerTime), disputedBeeTokens, arbitrationFee); } /** * @dev add votes to job * -functionhash- unknown yet * @param currentJob The arbitration job we are adding votes to * @param currentJobId The Id of the arbitrationJob */ function addVotesToJob(ArbitrationJob storage currentJob, uint256 currentJobId) internal { for (uint256 currentJobVoteIndex=0; currentJobVoteIndex<arbitersPerJob; currentJobVoteIndex++) { assignVote(currentJob, currentJobId, currentJobVoteIndex); } } /** * @dev crate vote at location index of job and replace old vote that was there if there was an old vote * -functionhash- unknown yet * @param currentJob The arbitration job we are adding votes to * @param currentJobId The Id of the arbitrationJob * @param currentJobVoteIndex The index of the vote in the aribtration job vote array we are modifying */ function assignVote(ArbitrationJob storage currentJob, uint256 currentJobId, uint256 currentJobVoteIndex) internal { ArbiterVote memory addVote = ArbiterVote({ state:VoteState.NOT_ASSIGNED_TO_ARBITER, arbitrationJobId:currentJobId, vote:0, arbiterId:0 }); uint256 voteIndex = arbVotes.push(addVote)-1; currentJob.arbiterVoteIds[currentJobVoteIndex] = voteIndex; } /** * @dev Internal function. it removes an element from an array stored on * the blockchain without keeping order at a O(1) efficency * -functionhash- unknown yet * @param index The index of the array we are removing * @param arr The array we are modifying */ function removeIndexFromArray (uint256 index, uint256 [] storage arr) internal { //maybe make a memory version of this for functions that loaded everything into memory so it cost less gas require(index < arr.length, "index doesn't exist in array"); uint lastIndex = arr.length.sub(1); arr[index] = arr[lastIndex]; delete arr[lastIndex]; arr.length = lastIndex; } /** * @dev Internal function. it removes a miner from the mining queue * -functionhash- unknown yet * @param index The index of the array we are removing */ function removeMinerFromQueue (uint256 index) internal { //maybe make a memory version of this for functions that loaded everything into memory so it cost less gas require(index >= 1, "can't remove dummy miner"); require(index < arbitersMining.length, "index doens't exist in mining queue"); uint lastIndex = arbitersMining.length.sub(1); arbitersMining[index] = arbitersMining[lastIndex]; Arbiter storage curMiner = existingArbiters[arbitersMining[lastIndex].miningId]; curMiner.miningArrayIndex = index; delete arbitersMining[lastIndex]; arbitersMining.length = lastIndex; } /** * @dev penalize arbitors for not voting by taking some of their stake and * taking them off the mining queue * * -functionhash- unknown yet * @param currentJob The arbitration job we are searching through for non voters * @param currentJobId The arbitration job id that corrasponds to the arbitration job we passed in */ function penalizeArbitersForNotVoting (ArbitrationJob storage currentJob, uint256 currentJobId) internal { uint256 [] memory jobVotes = currentJob.arbiterVoteIds; uint256 beeTokenTaken = 0; //trim non voters out and keep the ones who voted for (uint256 currentJobIndex = 0; currentJobIndex<jobVotes.length; currentJobIndex++) { if (jobVotes[currentJobIndex] != 0 && arbVotes[jobVotes[currentJobIndex]].state == VoteState.PENDING_VOTE) { //keep votes that happened beeTokenTaken += penalizeArbiter(jobVotes[currentJobIndex]); //replace bad vote slot in job with blank job to fill with a miner at a later date assignVote(currentJob, currentJobId, currentJobIndex); } } beeTokenTaken = beeTokenTaken.mul(percentPenTokensToFee) / 100; //calculate what is added to fee currentJob.beeTokensArbitrationFee += beeTokenTaken; } /** * @dev selected miners from the mining pool to become Arbitors * * -functionhash- unknown yet * @param currentJob The arbitration job we are selecting miners for * @param arbId The arbitration job id that corrasponds to the arbitration job we passed in */ function selectArbitersFromMiners (ArbitrationJob storage currentJob, uint256 arbId) internal { uint256 [] memory voteIds = currentJob.arbiterVoteIds; MinerTicketHolder [] memory curTickets = arbitersMining; //make copy in memory //for arbieters that haven't voted, make them not vote again for this job for (uint256 j = 0 ;j<voteIds.length; j++) { ArbiterVote memory checkVote = arbVotes[voteIds[j]]; if (checkVote.state == VoteState.VOTE_COMPLETE) { uint256 lottoIndex = existingArbiters[checkVote.arbiterId].miningArrayIndex; curTickets[lottoIndex].numLottoTickets = 0; //take away mining tickets for existing arbiter } } for (uint256 i = 0 ;i<voteIds.length; i++) { ArbiterVote storage currentVote = arbVotes[voteIds[i]]; if (currentVote.state == VoteState.PENALIZED_NO_VOTE || currentVote.state == VoteState.NOT_ASSIGNED_TO_ARBITER) { uint256 arbiterId = selectArbiter(curTickets); require (arbiterId >0, "can't be the dummy miner..."); uint256 miningArrayIndex = existingArbiters[arbiterId].miningArrayIndex; curTickets[miningArrayIndex].numLottoTickets = 0; //take away mining tickets for existing arbiter if (currentVote.state == VoteState.PENALIZED_NO_VOTE) { ArbiterVote memory addVote = ArbiterVote({ state:VoteState.PENDING_VOTE, arbitrationJobId:arbId, vote:0, arbiterId:arbiterId }); uint256 voteIndex = arbVotes.push(addVote)-1; //replace new vote with old bad vote voteIds[i] = voteIndex; //push vote id to miner so they know they got a job to do existingArbiters[arbiterId].arbiterVoteIds.push(voteIndex); } else if (currentVote.state == VoteState.NOT_ASSIGNED_TO_ARBITER) { //assgin to arbiter if not assigned yet currentVote.state = VoteState.PENDING_VOTE; currentVote.arbiterId = arbiterId; //push vote id to miner so they know they got a job to do existingArbiters[arbiterId].arbiterVoteIds.push(voteIds[i]); } } } currentJob.arbiterVoteIds = voteIds; //save new voter ids. optimization so we don't read a ton of times from storage } /** * @dev needed to pay triggermen for doing any triggers * * -functionhash- unknown yet * @param pathCompleted The path we took in our triggering * @param currentJob The arbitration job we helped by triggering an event */ function payTriggerman (uint256 pathCompleted, ArbitrationJob storage currentJob) internal { //triggerman always pays himself uint256 beeTokenPaymentForTrigger = triggermanPayBeeTokenAmount[pathCompleted]; currentJob.beeTokensArbitrationFee = currentJob.beeTokensArbitrationFee.sub(beeTokenPaymentForTrigger); require(beeToken.transfer(msg.sender, beeTokenPaymentForTrigger), "error paying / transfering to triggerman"); } /** * @dev figures out how much to pay everyone then pays them. * * -functionhash- unknown yet * @param currentJob The job we are refunding the host / guest from */ function abideByFinalVoteOfArbs (ArbitrationJob memory currentJob, uint256 arbitraionJobId) internal { uint256 totalPercent = 0; for (uint256 j=0; j < currentJob.arbiterVoteIds.length; j++) { ArbiterVote memory currentVote = arbVotes[currentJob.arbiterVoteIds[j]]; totalPercent += percentDisputedChoices[currentVote.vote]; } uint256 medianPercent = totalPercent / currentJob.arbiterVoteIds.length; uint256 beeTokenForHost = currentJob.disputedAmountOfBeeTokens.mul(medianPercent)/100; require(beeToken.transfer(currentJob.host, beeTokenForHost), "err transfering to host"); uint256 beeTokenForGuest = currentJob.disputedAmountOfBeeTokens. sub(beeTokenForHost); require(beeToken.transfer(currentJob.guest, beeTokenForGuest), "err transfering to guest"); emit ArbCompleted(arbitraionJobId, medianPercent, currentJob.paymentId, now); } /** * @dev internal helper function to penalize arbiters for missing a vote * -functionhash- unknown yet * @param voteId The id of the vote that didn't get completed by the end time */ function penalizeArbiter(uint256 voteId) internal returns (uint256) { ArbiterVote storage currentVote = arbVotes[voteId]; require (currentVote.state == VoteState.PENDING_VOTE, "arbiter not in pending vote state, can't penalize"); Arbiter storage curMiner = existingArbiters[currentVote.arbiterId]; uint256 beeTokenTaken = (curMiner.currentBeeTokenStake).mul(beeTokenPenality) / 100; uint256 salvagedBeeTokens = curMiner.currentBeeTokenStake.sub(beeTokenTaken); if (salvagedBeeTokens > 0) { require(beeToken.transfer(curMiner.minerAddress, salvagedBeeTokens), "err transfering bee from bad arbiter");//take bee tokens from Arbiter } emit ArbiterPenalized(currentVote.arbiterId, voteId, beeTokenTaken,curMiner.currentBeeTokenStake, now); currentVote.state = VoteState.PENALIZED_NO_VOTE; curMiner.currentBeeTokenStake = 0; removeMinerFromQueue(curMiner.miningArrayIndex); //remove miner from mining because they didn't do their job //select one more Arbiter return beeTokenTaken; } /** * @dev internal function that helps select one arbiter * -functionhash- unknown yet * @param curTickets A memory copy of all miners modified to set tickets to 0 where we blacklisted. * A miner can't be picked twice for the same job */ function selectArbiter(MinerTicketHolder [] memory curTickets) internal returns (uint256) //returns arbiter id of winner { //get number of total tickets uint256 numTicketsOut = 0; for (uint256 i=0; i < curTickets.length; i++) { numTicketsOut = numTicketsOut.add(curTickets[i].numLottoTickets); } require (numTicketsOut > 2, "needs to have at least 2 tickets avalible to init a vote");//needs to be at least 2 tickets avalible uint256 winningLottoTicket = getRandomNumber(1, numTicketsOut); uint256 winningMinerIndex = 0; uint256 curLottoTicket = curTickets[winningMinerIndex].numLottoTickets; while(curLottoTicket < winningLottoTicket) { winningMinerIndex = winningMinerIndex.add(1); //winner not found, try next index curLottoTicket = curLottoTicket.add(curTickets[winningMinerIndex].numLottoTickets); } return curTickets[winningMinerIndex].miningId; } /** * @dev our random number generator, need to check how expensive it is to * call, might just use less info to generate the random number. stolen * from fomo3d game, LOL, lots of stuff stolen from their open source. * They got skillz for being one of the best teams, their code is solId * -functionhash- unknown yet * @param min The min amount that we want * @param max The max amount that we want to go up to (non inclusive) */ function getRandomNumber (uint256 min, uint256 max) internal returns (uint256) { nonce = (nonce+1)%255; //this might overflow and cause thrown mining requests uint256 rawRand = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number).add(nonce) ))); return (rawRand%(max-min))+min; } /** * @dev registers a mininer, but puts them in a approval needed state * the contract owner needs to review all of the pending miners and * approve them * -functionhash- unknown yet */ function registerNewUser() internal returns (uint256) { uint256 minerId = existingArbiters.length; Arbiter memory curMiner = Arbiter({ accessState:ArbiterAccessState.PENDING_APPROVAL, minerAddress:msg.sender, currentBeeTokenStake:0, arbitrationsCompleted:0, arbitrationsAppealed:0, miningArrayIndex:0, arbiterVoteIds:new uint256[](0) }); existingArbiters.push(curMiner); addressToMinerId[msg.sender] = minerId; return minerId; } }
* @dev selected miners from the mining pool to become Arbitors -functionhash- unknown yet @param currentJob The arbitration job we are selecting miners for @param arbId The arbitration job id that corrasponds to the arbitration job we passed in/for arbieters that haven't voted, make them not vote again for this job
{ uint256 [] memory voteIds = currentJob.arbiterVoteIds; function selectArbitersFromMiners (ArbitrationJob storage currentJob, uint256 arbId) internal for (uint256 j = 0 ;j<voteIds.length; j++) { ArbiterVote memory checkVote = arbVotes[voteIds[j]]; if (checkVote.state == VoteState.VOTE_COMPLETE) { uint256 lottoIndex = existingArbiters[checkVote.arbiterId].miningArrayIndex; } } function selectArbitersFromMiners (ArbitrationJob storage currentJob, uint256 arbId) internal for (uint256 j = 0 ;j<voteIds.length; j++) { ArbiterVote memory checkVote = arbVotes[voteIds[j]]; if (checkVote.state == VoteState.VOTE_COMPLETE) { uint256 lottoIndex = existingArbiters[checkVote.arbiterId].miningArrayIndex; } } for (uint256 i = 0 ;i<voteIds.length; i++) { ArbiterVote storage currentVote = arbVotes[voteIds[i]]; if (currentVote.state == VoteState.PENALIZED_NO_VOTE || currentVote.state == VoteState.NOT_ASSIGNED_TO_ARBITER) { uint256 arbiterId = selectArbiter(curTickets); require (arbiterId >0, "can't be the dummy miner..."); uint256 miningArrayIndex = existingArbiters[arbiterId].miningArrayIndex; if (currentVote.state == VoteState.PENALIZED_NO_VOTE) { ArbiterVote memory addVote = ArbiterVote({ state:VoteState.PENDING_VOTE, arbitrationJobId:arbId, vote:0, arbiterId:arbiterId }); uint256 voteIndex = arbVotes.push(addVote)-1; currentVote.state = VoteState.PENDING_VOTE; currentVote.arbiterId = arbiterId; } } } for (uint256 i = 0 ;i<voteIds.length; i++) { ArbiterVote storage currentVote = arbVotes[voteIds[i]]; if (currentVote.state == VoteState.PENALIZED_NO_VOTE || currentVote.state == VoteState.NOT_ASSIGNED_TO_ARBITER) { uint256 arbiterId = selectArbiter(curTickets); require (arbiterId >0, "can't be the dummy miner..."); uint256 miningArrayIndex = existingArbiters[arbiterId].miningArrayIndex; if (currentVote.state == VoteState.PENALIZED_NO_VOTE) { ArbiterVote memory addVote = ArbiterVote({ state:VoteState.PENDING_VOTE, arbitrationJobId:arbId, vote:0, arbiterId:arbiterId }); uint256 voteIndex = arbVotes.push(addVote)-1; currentVote.state = VoteState.PENDING_VOTE; currentVote.arbiterId = arbiterId; } } } for (uint256 i = 0 ;i<voteIds.length; i++) { ArbiterVote storage currentVote = arbVotes[voteIds[i]]; if (currentVote.state == VoteState.PENALIZED_NO_VOTE || currentVote.state == VoteState.NOT_ASSIGNED_TO_ARBITER) { uint256 arbiterId = selectArbiter(curTickets); require (arbiterId >0, "can't be the dummy miner..."); uint256 miningArrayIndex = existingArbiters[arbiterId].miningArrayIndex; if (currentVote.state == VoteState.PENALIZED_NO_VOTE) { ArbiterVote memory addVote = ArbiterVote({ state:VoteState.PENDING_VOTE, arbitrationJobId:arbId, vote:0, arbiterId:arbiterId }); uint256 voteIndex = arbVotes.push(addVote)-1; currentVote.state = VoteState.PENDING_VOTE; currentVote.arbiterId = arbiterId; } } } for (uint256 i = 0 ;i<voteIds.length; i++) { ArbiterVote storage currentVote = arbVotes[voteIds[i]]; if (currentVote.state == VoteState.PENALIZED_NO_VOTE || currentVote.state == VoteState.NOT_ASSIGNED_TO_ARBITER) { uint256 arbiterId = selectArbiter(curTickets); require (arbiterId >0, "can't be the dummy miner..."); uint256 miningArrayIndex = existingArbiters[arbiterId].miningArrayIndex; if (currentVote.state == VoteState.PENALIZED_NO_VOTE) { ArbiterVote memory addVote = ArbiterVote({ state:VoteState.PENDING_VOTE, arbitrationJobId:arbId, vote:0, arbiterId:arbiterId }); uint256 voteIndex = arbVotes.push(addVote)-1; currentVote.state = VoteState.PENDING_VOTE; currentVote.arbiterId = arbiterId; } } } voteIds[i] = voteIndex; existingArbiters[arbiterId].arbiterVoteIds.push(voteIndex); existingArbiters[arbiterId].arbiterVoteIds.push(voteIds[i]); }
1,841,599
[ 1, 8109, 1131, 414, 628, 326, 1131, 310, 2845, 358, 12561, 1201, 3682, 1383, 225, 300, 915, 2816, 17, 5917, 4671, 225, 783, 2278, 1021, 10056, 7034, 1719, 732, 854, 24674, 1131, 414, 364, 225, 419, 70, 548, 1021, 10056, 7034, 1719, 612, 716, 19480, 345, 12545, 358, 326, 10056, 7034, 1719, 732, 2275, 316, 19, 1884, 419, 13266, 1032, 716, 15032, 1404, 331, 16474, 16, 1221, 2182, 486, 12501, 3382, 364, 333, 1719, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 540, 203, 3639, 2254, 5034, 225, 5378, 3778, 12501, 2673, 273, 783, 2278, 18, 6779, 2165, 19338, 2673, 31, 203, 540, 203, 565, 445, 2027, 686, 3682, 414, 1265, 2930, 414, 261, 686, 3682, 7034, 2278, 2502, 783, 2278, 16, 2254, 5034, 419, 70, 548, 13, 7010, 3639, 2713, 203, 3639, 364, 261, 11890, 5034, 525, 273, 374, 274, 78, 32, 25911, 2673, 18, 2469, 31, 525, 27245, 288, 203, 5411, 1201, 70, 2165, 19338, 3778, 866, 19338, 273, 419, 70, 29637, 63, 25911, 2673, 63, 78, 13563, 31, 203, 5411, 309, 261, 1893, 19338, 18, 2019, 422, 27540, 1119, 18, 16169, 1448, 67, 15795, 13, 288, 203, 7734, 2254, 5034, 17417, 869, 1016, 273, 2062, 686, 3682, 414, 63, 1893, 19338, 18, 6779, 2165, 548, 8009, 1154, 310, 1076, 1016, 31, 203, 5411, 289, 203, 3639, 289, 203, 540, 203, 565, 445, 2027, 686, 3682, 414, 1265, 2930, 414, 261, 686, 3682, 7034, 2278, 2502, 783, 2278, 16, 2254, 5034, 419, 70, 548, 13, 7010, 3639, 2713, 203, 3639, 364, 261, 11890, 5034, 525, 273, 374, 274, 78, 32, 25911, 2673, 18, 2469, 31, 525, 27245, 288, 203, 5411, 1201, 70, 2165, 19338, 3778, 866, 19338, 273, 419, 70, 29637, 63, 25911, 2673, 63, 78, 13563, 31, 203, 5411, 309, 261, 1893, 19338, 18, 2019, 422, 27540, 1119, 18, 16169, 1448, 67, 15795, 13, 288, 203, 7734, 2254, 5034, 17417, 869, 1016, 273, 2062, 686, 3682, 414, 63, 1893, 19338, 18, 6779, 2165, 548, 8009, 1154, 310, 1076, 1016, 31, 2 ]
// File: ReentrancyGuard.sol // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol // Subject to the MIT license. /** * @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; } } // File: Context.sol // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/GSN/Context.sol // Subject to the MIT license. /* * @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: Ownable.sol // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol // Subject to the MIT license. /** * @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; } } // File: SafeMath.sol // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the 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: EnumerableSet.sol // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/EnumerableSet.sol // Subject to the MIT license. /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: TransferHelper.sol /** helper methods for interacting with ERC20 tokens that do not consistently return true/false with the addition of a transfer function to send eth or an erc20 token */ library TransferHelper { function safeApprove(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } // sends ETH or an erc20 token function safeTransferBaseToken(address token, address payable to, uint value, bool isERC20) internal { if (!isERC20) { to.transfer(value); } else { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } } } // File: UniswapV2Locker.sol // @Credits Unicrypt Network 2021 // This contract locks uniswap v2 liquidity tokens. Used to give investors peace of mind a token team has locked liquidity // and that the univ2 tokens cannot be removed from uniswap until the specified unlock date has been reached. interface IUniswapV2Pair { function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); } interface IERCBurn { function burn(uint256 _amount) external; function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external returns (uint256); function balanceOf(address account) external view returns (uint256); } interface IUniFactory { function getPair(address tokenA, address tokenB) external view returns (address); } interface IMigrator { function migrate(address lpToken, uint256 amount, uint256 unlockDate, address owner) external returns (bool); } contract UniswapV2Locker is Ownable, ReentrancyGuard { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; IUniFactory public uniswapFactory; struct UserInfo { EnumerableSet.AddressSet lockedTokens; // records all tokens the user has locked mapping(address => uint256[]) locksForToken; // map erc20 address to lock id for that token } struct TokenLock { uint256 lockDate; // the date the token was locked uint256 amount; // the amount of tokens still locked (initialAmount minus withdrawls) uint256 initialAmount; // the initial lock amount uint256 unlockDate; // the date the token can be withdrawn uint256 lockID; // lockID nonce per uni pair address owner; } mapping(address => UserInfo) private users; EnumerableSet.AddressSet private lockedTokens; mapping(address => TokenLock[]) public tokenLocks; //map univ2 pair to all its locks struct FeeStruct { uint256 ethFee; // Small eth fee to prevent spam on the platform IERCBurn secondaryFeeToken; // UNCX or UNCL uint256 secondaryTokenFee; // optional, UNCX or UNCL uint256 secondaryTokenDiscount; // discount on liquidity fee for burning secondaryToken uint256 liquidityFee; // fee on univ2 liquidity tokens uint256 referralPercent; // fee for referrals IERCBurn referralToken; // token the refferer must hold to qualify as a referrer uint256 referralHold; // balance the referrer must hold to qualify as a referrer uint256 referralDiscount; // discount on flatrate fees for using a valid referral address } FeeStruct public gFees; EnumerableSet.AddressSet private feeWhitelist; address payable devaddr; IMigrator migrator; event onDeposit(address lpToken, address user, uint256 amount, uint256 lockDate, uint256 unlockDate); event onWithdraw(address lpToken, uint256 amount); constructor(IUniFactory _uniswapFactory) public { devaddr = msg.sender; gFees.referralPercent = 250; // 25% gFees.ethFee = 1e18; gFees.secondaryTokenFee = 100e18; gFees.secondaryTokenDiscount = 200; // 20% gFees.liquidityFee = 10; // 1% gFees.referralHold = 10e18; gFees.referralDiscount = 100; // 10% uniswapFactory = _uniswapFactory; } function setDev(address payable _devaddr) public onlyOwner { devaddr = _devaddr; } /** * @notice set the migrator contract which allows locked lp tokens to be migrated to uniswap v3 */ function setMigrator(IMigrator _migrator) public onlyOwner { migrator = _migrator; } function setSecondaryFeeToken(address _secondaryFeeToken) public onlyOwner { gFees.secondaryFeeToken = IERCBurn(_secondaryFeeToken); } /** * @notice referrers need to hold the specified token and hold amount to be elegible for referral fees */ function setReferralTokenAndHold(IERCBurn _referralToken, uint256 _hold) public onlyOwner { gFees.referralToken = _referralToken; gFees.referralHold = _hold; } function setFees(uint256 _referralPercent, uint256 _referralDiscount, uint256 _ethFee, uint256 _secondaryTokenFee, uint256 _secondaryTokenDiscount, uint256 _liquidityFee) public onlyOwner { gFees.referralPercent = _referralPercent; gFees.referralDiscount = _referralDiscount; gFees.ethFee = _ethFee; gFees.secondaryTokenFee = _secondaryTokenFee; gFees.secondaryTokenDiscount = _secondaryTokenDiscount; gFees.liquidityFee = _liquidityFee; } /** * @notice whitelisted accounts dont pay flatrate fees on locking */ function whitelistFeeAccount(address _user, bool _add) public onlyOwner { if (_add) { feeWhitelist.add(_user); } else { feeWhitelist.remove(_user); } } /** * @notice Creates a new lock * @param _lpToken the univ2 token address * @param _amount amount of LP tokens to lock * @param _unlock_date the unix timestamp (in seconds) until unlock * @param _referral the referrer address if any or address(0) for none * @param _fee_in_eth fees can be paid in eth or in a secondary token such as UNCX with a discount on univ2 tokens * @param _withdrawer the user who can withdraw liquidity once the lock expires. */ function lockLPToken (address _lpToken, uint256 _amount, uint256 _unlock_date, address payable _referral, bool _fee_in_eth, address payable _withdrawer) external payable nonReentrant { require(_unlock_date < 10000000000, 'TIMESTAMP INVALID'); // prevents errors when timestamp entered in milliseconds require(_amount > 0, 'INSUFFICIENT'); // ensure this pair is a univ2 pair by querying the factory IUniswapV2Pair lpair = IUniswapV2Pair(address(_lpToken)); address factoryPairAddress = uniswapFactory.getPair(lpair.token0(), lpair.token1()); require(factoryPairAddress == address(_lpToken), 'NOT UNIV2'); TransferHelper.safeTransferFrom(_lpToken, address(msg.sender), address(this), _amount); if (_referral != address(0) && address(gFees.referralToken) != address(0)) { require(gFees.referralToken.balanceOf(_referral) >= gFees.referralHold, 'INADEQUATE BALANCE'); } // flatrate fees if (!feeWhitelist.contains(msg.sender)) { if (_fee_in_eth) { // charge fee in eth uint256 ethFee = gFees.ethFee; if (_referral != address(0)) { ethFee = ethFee.mul(1000 - gFees.referralDiscount).div(1000); } require(msg.value == ethFee, 'FEE NOT MET'); uint256 devFee = ethFee; if (ethFee != 0 && _referral != address(0)) { // referral fee uint256 referralFee = devFee.mul(gFees.referralPercent).div(1000); _referral.transfer(referralFee); devFee = devFee.sub(referralFee); } devaddr.transfer(devFee); } else { // charge fee in token uint256 burnFee = gFees.secondaryTokenFee; if (_referral != address(0)) { burnFee = burnFee.mul(1000 - gFees.referralDiscount).div(1000); } TransferHelper.safeTransferFrom(address(gFees.secondaryFeeToken), address(msg.sender), address(this), burnFee); if (gFees.referralPercent != 0 && _referral != address(0)) { // referral fee uint256 referralFee = burnFee.mul(gFees.referralPercent).div(1000); TransferHelper.safeApprove(address(gFees.secondaryFeeToken), _referral, referralFee); TransferHelper.safeTransfer(address(gFees.secondaryFeeToken), _referral, referralFee); burnFee = burnFee.sub(referralFee); } gFees.secondaryFeeToken.burn(burnFee); } } else if (msg.value > 0){ // refund eth if a whitelisted member sent it by mistake msg.sender.transfer(msg.value); } // percent fee uint256 liquidityFee = _amount.mul(gFees.liquidityFee).div(1000); if (!_fee_in_eth && !feeWhitelist.contains(msg.sender)) { // fee discount for large lockers using secondary token liquidityFee = liquidityFee.mul(1000 - gFees.secondaryTokenDiscount).div(1000); } TransferHelper.safeTransfer(_lpToken, devaddr, liquidityFee); uint256 amountLocked = _amount.sub(liquidityFee); TokenLock memory token_lock; token_lock.lockDate = block.timestamp; token_lock.amount = amountLocked; token_lock.initialAmount = amountLocked; token_lock.unlockDate = _unlock_date; token_lock.lockID = tokenLocks[_lpToken].length; token_lock.owner = _withdrawer; // record the lock for the univ2pair tokenLocks[_lpToken].push(token_lock); lockedTokens.add(_lpToken); // record the lock for the user UserInfo storage user = users[_withdrawer]; user.lockedTokens.add(_lpToken); uint256[] storage user_locks = user.locksForToken[_lpToken]; user_locks.push(token_lock.lockID); emit onDeposit(_lpToken, msg.sender, token_lock.amount, token_lock.lockDate, token_lock.unlockDate); } /** * @notice extend a lock with a new unlock date, _index and _lockID ensure the correct lock is changed * this prevents errors when a user performs multiple tx per block possibly with varying gas prices */ function relock (address _lpToken, uint256 _index, uint256 _lockID, uint256 _unlock_date) external nonReentrant { require(_unlock_date < 10000000000, 'TIMESTAMP INVALID'); // prevents errors when timestamp entered in milliseconds uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected require(userLock.unlockDate < _unlock_date, 'UNLOCK BEFORE'); uint256 liquidityFee = userLock.amount.mul(gFees.liquidityFee).div(1000); uint256 amountLocked = userLock.amount.sub(liquidityFee); userLock.amount = amountLocked; userLock.unlockDate = _unlock_date; // send univ2 fee to dev address TransferHelper.safeTransfer(_lpToken, devaddr, liquidityFee); } /** * @notice withdraw a specified amount from a lock. _index and _lockID ensure the correct lock is changed * this prevents errors when a user performs multiple tx per block possibly with varying gas prices */ function withdraw (address _lpToken, uint256 _index, uint256 _lockID, uint256 _amount) external nonReentrant { require(_amount > 0, 'ZERO WITHDRAWL'); uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected require(userLock.unlockDate < block.timestamp, 'NOT YET'); userLock.amount = userLock.amount.sub(_amount); // clean user storage if (userLock.amount == 0) { uint256[] storage userLocks = users[msg.sender].locksForToken[_lpToken]; userLocks[_index] = userLocks[userLocks.length-1]; userLocks.pop(); if (userLocks.length == 0) { users[msg.sender].lockedTokens.remove(_lpToken); } } TransferHelper.safeTransfer(_lpToken, msg.sender, _amount); emit onWithdraw(_lpToken, _amount); } /** * @notice increase the amount of tokens per a specific lock, this is preferable to creating a new lock, less fees, and faster loading on our live block explorer */ function incrementLock (address _lpToken, uint256 _index, uint256 _lockID, uint256 _amount) external nonReentrant { require(_amount > 0, 'ZERO AMOUNT'); uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected TransferHelper.safeTransferFrom(_lpToken, address(msg.sender), address(this), _amount); // send univ2 fee to dev address uint256 liquidityFee = _amount.mul(gFees.liquidityFee).div(1000); TransferHelper.safeTransfer(_lpToken, devaddr, liquidityFee); uint256 amountLocked = _amount.sub(liquidityFee); userLock.amount = userLock.amount.add(amountLocked); emit onDeposit(_lpToken, msg.sender, amountLocked, userLock.lockDate, userLock.unlockDate); } /** * @notice split a lock into two seperate locks, useful when a lock is about to expire and youd like to relock a portion * and withdraw a smaller portion */ function splitLock (address _lpToken, uint256 _index, uint256 _lockID, uint256 _amount) external payable nonReentrant { require(_amount > 0, 'ZERO AMOUNT'); uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected require(msg.value == gFees.ethFee, 'FEE NOT MET'); devaddr.transfer(gFees.ethFee); userLock.amount = userLock.amount.sub(_amount); TokenLock memory token_lock; token_lock.lockDate = userLock.lockDate; token_lock.amount = _amount; token_lock.initialAmount = _amount; token_lock.unlockDate = userLock.unlockDate; token_lock.lockID = tokenLocks[_lpToken].length; token_lock.owner = msg.sender; // record the lock for the univ2pair tokenLocks[_lpToken].push(token_lock); // record the lock for the user UserInfo storage user = users[msg.sender]; uint256[] storage user_locks = user.locksForToken[_lpToken]; user_locks.push(token_lock.lockID); } /** * @notice transfer a lock to a new owner, e.g. presale project -> project owner */ function transferLockOwnership (address _lpToken, uint256 _index, uint256 _lockID, address payable _newOwner) external { require(msg.sender != _newOwner, 'OWNER'); uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage transferredLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && transferredLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected // record the lock for the new Owner UserInfo storage user = users[_newOwner]; user.lockedTokens.add(_lpToken); uint256[] storage user_locks = user.locksForToken[_lpToken]; user_locks.push(transferredLock.lockID); // remove the lock from the old owner uint256[] storage userLocks = users[msg.sender].locksForToken[_lpToken]; userLocks[_index] = userLocks[userLocks.length-1]; userLocks.pop(); if (userLocks.length == 0) { users[msg.sender].lockedTokens.remove(_lpToken); } transferredLock.owner = _newOwner; } /** * @notice migrates liquidity to uniswap v3 */ function migrate (address _lpToken, uint256 _index, uint256 _lockID, uint256 _amount) external nonReentrant { require(address(migrator) != address(0), "NOT SET"); require(_amount > 0, 'ZERO MIGRATION'); uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected userLock.amount = userLock.amount.sub(_amount); // clean user storage if (userLock.amount == 0) { uint256[] storage userLocks = users[msg.sender].locksForToken[_lpToken]; userLocks[_index] = userLocks[userLocks.length-1]; userLocks.pop(); if (userLocks.length == 0) { users[msg.sender].lockedTokens.remove(_lpToken); } } TransferHelper.safeApprove(_lpToken, address(migrator), _amount); migrator.migrate(_lpToken, _amount, userLock.unlockDate, msg.sender); } function getNumLocksForToken (address _lpToken) external view returns (uint256) { return tokenLocks[_lpToken].length; } function getNumLockedTokens () external view returns (uint256) { return lockedTokens.length(); } function getLockedTokenAtIndex (uint256 _index) external view returns (address) { return lockedTokens.at(_index); } // user functions function getUserNumLockedTokens (address _user) external view returns (uint256) { UserInfo storage user = users[_user]; return user.lockedTokens.length(); } function getUserLockedTokenAtIndex (address _user, uint256 _index) external view returns (address) { UserInfo storage user = users[_user]; return user.lockedTokens.at(_index); } function getUserNumLocksForToken (address _user, address _lpToken) external view returns (uint256) { UserInfo storage user = users[_user]; return user.locksForToken[_lpToken].length; } function getUserLockForTokenAtIndex (address _user, address _lpToken, uint256 _index) external view returns (uint256, uint256, uint256, uint256, uint256, address) { uint256 lockID = users[_user].locksForToken[_lpToken][_index]; TokenLock storage tokenLock = tokenLocks[_lpToken][lockID]; return (tokenLock.lockDate, tokenLock.amount, tokenLock.initialAmount, tokenLock.unlockDate, tokenLock.lockID, tokenLock.owner); } // whitelist function getWhitelistedUsersLength () external view returns (uint256) { return feeWhitelist.length(); } function getWhitelistedUserAtIndex (uint256 _index) external view returns (address) { return feeWhitelist.at(_index); } function getUserWhitelistStatus (address _user) external view returns (bool) { return feeWhitelist.contains(_user); } }
records all tokens the user has locked
EnumerableSet.AddressSet lockedTokens;
312,111
[ 1, 7094, 777, 2430, 326, 729, 711, 8586, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6057, 25121, 694, 18, 1887, 694, 8586, 5157, 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 ]
pragma solidity ^0.5.16; // Inheritance import "./PerpsV2SettingsMixin.sol"; import "./interfaces/IPerpsV2Market.sol"; // Libraries import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "./SignedSafeMath.sol"; import "./SignedSafeDecimalMath.sol"; import "./SafeDecimalMath.sol"; // Internal references import "./interfaces/IExchangeCircuitBreaker.sol"; import "./interfaces/IExchangeRates.sol"; import "./interfaces/IExchanger.sol"; import "./interfaces/ISystemStatus.sol"; import "./interfaces/IERC20.sol"; /* * */ interface IFuturesMarketManagerInternal { function issueSUSD(address account, uint amount) external; function burnSUSD(address account, uint amount) external returns (uint postReclamationAmount); function payFee(uint amount, bytes32 trackingCode) external; } contract PerpsV2MarketBase is PerpsV2SettingsMixin, IPerpsV2BaseTypes { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SignedSafeMath for int; using SignedSafeDecimalMath for int; using SafeDecimalMath for uint; /* ========== CONSTANTS ========== */ // This is the same unit as used inside `SignedSafeDecimalMath`. int private constant _UNIT = int(10**uint(18)); //slither-disable-next-line naming-convention bytes32 internal constant sUSD = "sUSD"; /* ========== STATE VARIABLES ========== */ // The market identifier in the system (manager + settings). Multiple markets can co-exist // for the same asset in order to allow migrations. bytes32 public marketKey; // The asset being traded in this market. This should be a valid key into the ExchangeRates contract. bytes32 public baseAsset; // The total number of base units in long and short positions. uint128 public marketSize; /* * The net position in base units of the whole market. * When this is positive, longs outweigh shorts. When it is negative, shorts outweigh longs. */ int128 public marketSkew; /* * The funding sequence allows constant-time calculation of the funding owed to a given position. * Each entry in the sequence holds the net funding accumulated per base unit since the market was created. * Then to obtain the net funding over a particular interval, subtract the start point's sequence entry * from the end point's sequence entry. * Positions contain the funding sequence entry at the time they were confirmed; so to compute * the net funding on a given position, obtain from this sequence the net funding per base unit * since the position was confirmed and multiply it by the position size. */ uint32 public fundingLastRecomputed; int128[] public fundingSequence; /* * Each user's position. Multiple positions can always be merged, so each user has * only have one position at a time. */ mapping(address => Position) public positions; /// mapping of position id to account addresses mapping(uint => address) public positionIdOwner; /* * This holds the value: sum_{p in positions}{p.margin - p.size * (p.lastPrice + fundingSequence[p.lastFundingIndex])} * Then marketSkew * (price + _nextFundingEntry()) + _entryDebtCorrection yields the total system debt, * which is equivalent to the sum of remaining margins in all positions. */ int128 internal _entryDebtCorrection; // This increments for each position; zero id reflects a position id that wasn't initialized. uint64 public lastPositionId = 0; // Holds the revert message for each type of error. mapping(uint8 => string) internal _errorMessages; bytes32 public constant CONTRACT_NAME = "PerpsV2Market"; /* ---------- Address Resolver Configuration ---------- */ bytes32 internal constant CONTRACT_CIRCUIT_BREAKER = "ExchangeCircuitBreaker"; bytes32 internal constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 internal constant CONTRACT_FUTURESMARKETMANAGER = "FuturesMarketManager"; bytes32 internal constant CONTRACT_PERPSV2SETTINGS = "PerpsV2Settings"; bytes32 internal constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; // convenience struct for passing params between position modification helper functions struct TradeParams { int sizeDelta; uint price; uint baseFee; bytes32 trackingCode; // optional tracking code for volume source fee sharing } /* ========== CONSTRUCTOR ========== */ constructor( address _resolver, bytes32 _baseAsset, bytes32 _marketKey ) public PerpsV2SettingsMixin(_resolver) { baseAsset = _baseAsset; marketKey = _marketKey; // Initialise the funding sequence with 0 initially accrued, so that the first usable funding index is 1. fundingSequence.push(0); // Set up the mapping between error codes and their revert messages. _errorMessages[uint8(Status.InvalidPrice)] = "Invalid price"; _errorMessages[uint8(Status.PriceOutOfBounds)] = "Price out of acceptable range"; _errorMessages[uint8(Status.CanLiquidate)] = "Position can be liquidated"; _errorMessages[uint8(Status.CannotLiquidate)] = "Position cannot be liquidated"; _errorMessages[uint8(Status.MaxMarketSizeExceeded)] = "Max market size exceeded"; _errorMessages[uint8(Status.MaxLeverageExceeded)] = "Max leverage exceeded"; _errorMessages[uint8(Status.InsufficientMargin)] = "Insufficient margin"; _errorMessages[uint8(Status.NotPermitted)] = "Not permitted by this address"; _errorMessages[uint8(Status.NilOrder)] = "Cannot submit empty order"; _errorMessages[uint8(Status.NoPositionOpen)] = "No position open"; _errorMessages[uint8(Status.PriceTooVolatile)] = "Price too volatile"; } /* ========== VIEWS ========== */ /* ---------- External Contracts ---------- */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = PerpsV2SettingsMixin.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](5); newAddresses[0] = CONTRACT_EXCHANGER; newAddresses[1] = CONTRACT_CIRCUIT_BREAKER; newAddresses[2] = CONTRACT_FUTURESMARKETMANAGER; newAddresses[3] = CONTRACT_PERPSV2SETTINGS; newAddresses[4] = CONTRACT_SYSTEMSTATUS; addresses = combineArrays(existingAddresses, newAddresses); } function _exchangeCircuitBreaker() internal view returns (IExchangeCircuitBreaker) { return IExchangeCircuitBreaker(requireAndGetAddress(CONTRACT_CIRCUIT_BREAKER)); } function _exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function _systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function _manager() internal view returns (IFuturesMarketManagerInternal) { return IFuturesMarketManagerInternal(requireAndGetAddress(CONTRACT_FUTURESMARKETMANAGER)); } function _settings() internal view returns (address) { return requireAndGetAddress(CONTRACT_PERPSV2SETTINGS); } /* ---------- Market Details ---------- */ /* * The size of the skew relative to the size of the market skew scaler. * This value can be outside of [-1, 1] values. * Scaler used for skew is at skewScaleUSD to prevent extreme funding rates for small markets. */ function _proportionalSkew(uint price) internal view returns (int) { // marketSize is in baseAsset units so we need to convert from USD units require(price > 0, "price can't be zero"); uint skewScaleBaseAsset = _skewScaleUSD(marketKey).divideDecimal(price); require(skewScaleBaseAsset != 0, "skewScale is zero"); // don't divide by zero return int(marketSkew).divideDecimal(int(skewScaleBaseAsset)); } function _currentFundingRate(uint price) internal view returns (int) { int maxFundingRate = int(_maxFundingRate(marketKey)); // Note the minus sign: funding flows in the opposite direction to the skew. return _min(_max(-_UNIT, -_proportionalSkew(price)), _UNIT).multiplyDecimal(maxFundingRate); } function _unrecordedFunding(uint price) internal view returns (int funding) { int elapsed = int(block.timestamp.sub(fundingLastRecomputed)); // The current funding rate, rescaled to a percentage per second. int currentFundingRatePerSecond = _currentFundingRate(price) / 1 days; return currentFundingRatePerSecond.multiplyDecimal(int(price)).mul(elapsed); } /* * The new entry in the funding sequence, appended when funding is recomputed. It is the sum of the * last entry and the unrecorded funding, so the sequence accumulates running total over the market's lifetime. */ function _nextFundingEntry(uint price) internal view returns (int funding) { return int(fundingSequence[_latestFundingIndex()]).add(_unrecordedFunding(price)); } function _netFundingPerUnit(uint startIndex, uint price) internal view returns (int) { // Compute the net difference between start and end indices. return _nextFundingEntry(price).sub(fundingSequence[startIndex]); } /* ---------- Position Details ---------- */ /* * Determines whether a change in a position's size would violate the max market value constraint. */ function _orderSizeTooLarge( uint maxSize, int oldSize, int newSize ) internal view returns (bool) { // Allow users to reduce an order no matter the market conditions. if (_sameSide(oldSize, newSize) && _abs(newSize) <= _abs(oldSize)) { return false; } // Either the user is flipping sides, or they are increasing an order on the same side they're already on; // we check that the side of the market their order is on would not break the limit. int newSkew = int(marketSkew).sub(oldSize).add(newSize); int newMarketSize = int(marketSize).sub(_signedAbs(oldSize)).add(_signedAbs(newSize)); int newSideSize; if (0 < newSize) { // long case: marketSize + skew // = (|longSize| + |shortSize|) + (longSize + shortSize) // = 2 * longSize newSideSize = newMarketSize.add(newSkew); } else { // short case: marketSize - skew // = (|longSize| + |shortSize|) - (longSize + shortSize) // = 2 * -shortSize newSideSize = newMarketSize.sub(newSkew); } // newSideSize still includes an extra factor of 2 here, so we will divide by 2 in the actual condition if (maxSize < _abs(newSideSize.div(2))) { return true; } return false; } function _notionalValue(int positionSize, uint price) internal pure returns (int value) { return positionSize.multiplyDecimal(int(price)); } function _profitLoss(Position memory position, uint price) internal pure returns (int pnl) { int priceShift = int(price).sub(int(position.lastPrice)); return int(position.size).multiplyDecimal(priceShift); } function _accruedFunding(Position memory position, uint price) internal view returns (int funding) { uint lastModifiedIndex = position.lastFundingIndex; if (lastModifiedIndex == 0) { return 0; // The position does not exist -- no funding. } int net = _netFundingPerUnit(lastModifiedIndex, price); return int(position.size).multiplyDecimal(net); } /* * The initial margin of a position, plus any PnL and funding it has accrued. The resulting value may be negative. */ function _marginPlusProfitFunding(Position memory position, uint price) internal view returns (int) { int funding = _accruedFunding(position, price); return int(position.margin).add(_profitLoss(position, price)).add(funding); } /* * The value in a position's margin after a deposit or withdrawal, accounting for funding and profit. * If the resulting margin would be negative or below the liquidation threshold, an appropriate error is returned. * If the result is not an error, callers of this function that use it to update a position's margin * must ensure that this is accompanied by a corresponding debt correction update, as per `_applyDebtCorrection`. */ function _recomputeMarginWithDelta( Position memory position, uint price, int marginDelta ) internal view returns (uint margin, Status statusCode) { int newMargin = _marginPlusProfitFunding(position, price).add(marginDelta); if (newMargin < 0) { return (0, Status.InsufficientMargin); } uint uMargin = uint(newMargin); int positionSize = int(position.size); // minimum margin beyond which position can be liquidated uint lMargin = _liquidationMargin(positionSize, price); if (positionSize != 0 && uMargin <= lMargin) { return (uMargin, Status.CanLiquidate); } return (uMargin, Status.Ok); } function _remainingMargin(Position memory position, uint price) internal view returns (uint) { int remaining = _marginPlusProfitFunding(position, price); // If the margin went past zero, the position should have been liquidated - return zero remaining margin. return uint(_max(0, remaining)); } function _accessibleMargin(Position memory position, uint price) internal view returns (uint) { // Ugly solution to rounding safety: leave up to an extra tenth of a cent in the account/leverage // This should guarantee that the value returned here can always been withdrawn, but there may be // a little extra actually-accessible value left over, depending on the position size and margin. uint milli = uint(_UNIT / 1000); int maxLeverage = int(_maxLeverage(marketKey).sub(milli)); uint inaccessible = _abs(_notionalValue(position.size, price).divideDecimal(maxLeverage)); // If the user has a position open, we'll enforce a min initial margin requirement. if (0 < inaccessible) { uint minInitialMargin = _minInitialMargin(); if (inaccessible < minInitialMargin) { inaccessible = minInitialMargin; } inaccessible = inaccessible.add(milli); } uint remaining = _remainingMargin(position, price); if (remaining <= inaccessible) { return 0; } return remaining.sub(inaccessible); } /** * The fee charged from the margin during liquidation. Fee is proportional to position size * but is at least the _minKeeperFee() of sUSD to prevent underincentivising * liquidations of small positions. * @param positionSize size of position in fixed point decimal baseAsset units * @param price price of single baseAsset unit in sUSD fixed point decimal units * @return lFee liquidation fee to be paid to liquidator in sUSD fixed point decimal units */ function _liquidationFee(int positionSize, uint price) internal view returns (uint lFee) { // size * price * fee-ratio uint proportionalFee = _abs(positionSize).multiplyDecimal(price).multiplyDecimal(_liquidationFeeRatio()); uint minFee = _minKeeperFee(); // max(proportionalFee, minFee) - to prevent not incentivising liquidations enough return proportionalFee > minFee ? proportionalFee : minFee; // not using _max() helper because it's for signed ints } /** * The minimal margin at which liquidation can happen. Is the sum of liquidationBuffer and liquidationFee * @param positionSize size of position in fixed point decimal baseAsset units * @param price price of single baseAsset unit in sUSD fixed point decimal units * @return lMargin liquidation margin to maintain in sUSD fixed point decimal units * @dev The liquidation margin contains a buffer that is proportional to the position * size. The buffer should prevent liquidation happenning at negative margin (due to next price being worse) * so that stakers would not leak value to liquidators through minting rewards that are not from the * account's margin. */ function _liquidationMargin(int positionSize, uint price) internal view returns (uint lMargin) { uint liquidationBuffer = _abs(positionSize).multiplyDecimal(price).multiplyDecimal(_liquidationBufferRatio()); return liquidationBuffer.add(_liquidationFee(positionSize, price)); } function _canLiquidate(Position memory position, uint price) internal view returns (bool) { // No liquidating empty positions. if (position.size == 0) { return false; } return _remainingMargin(position, price) <= _liquidationMargin(int(position.size), price); } function _currentLeverage( Position memory position, uint price, uint remainingMargin_ ) internal pure returns (int leverage) { // No position is open, or it is ready to be liquidated; leverage goes to nil if (remainingMargin_ == 0) { return 0; } return _notionalValue(position.size, price).divideDecimal(int(remainingMargin_)); } function _orderFee(TradeParams memory params, uint dynamicFeeRate) internal pure returns (uint fee) { // usd value of the difference in position int notionalDiff = params.sizeDelta.multiplyDecimal(int(params.price)); uint feeRate = params.baseFee.add(dynamicFeeRate); return _abs(notionalDiff.multiplyDecimal(int(feeRate))); } /// Uses the exchanger to get the dynamic fee (SIP-184) for trading from sUSD to baseAsset /// this assumes dynamic fee is symmetric in direction of trade. /// @dev this is a pretty expensive action in terms of execution gas as it queries a lot /// of past rates from oracle. Shoudn't be much of an issue on a rollup though. function _dynamicFeeRate() internal view returns (uint feeRate, bool tooVolatile) { return _exchanger().dynamicFeeRateForExchange(sUSD, baseAsset); } function _latestFundingIndex() internal view returns (uint) { return fundingSequence.length.sub(1); // at least one element is pushed in constructor } function _postTradeDetails(Position memory oldPos, TradeParams memory params) internal view returns ( Position memory newPosition, uint fee, Status tradeStatus ) { // Reverts if the user is trying to submit a size-zero order. if (params.sizeDelta == 0) { return (oldPos, 0, Status.NilOrder); } // The order is not submitted if the user's existing position needs to be liquidated. if (_canLiquidate(oldPos, params.price)) { return (oldPos, 0, Status.CanLiquidate); } // get the dynamic fee rate SIP-184 (uint dynamicFeeRate, bool tooVolatile) = _dynamicFeeRate(); if (tooVolatile) { return (oldPos, 0, Status.PriceTooVolatile); } // calculate the total fee for exchange fee = _orderFee(params, dynamicFeeRate); // Deduct the fee. // It is an error if the realised margin minus the fee is negative or subject to liquidation. (uint newMargin, Status status) = _recomputeMarginWithDelta(oldPos, params.price, -int(fee)); if (_isError(status)) { return (oldPos, 0, status); } // construct new position Position memory newPos = Position({ id: oldPos.id, lastFundingIndex: uint64(_latestFundingIndex()), margin: uint128(newMargin), lastPrice: uint128(params.price), size: int128(int(oldPos.size).add(params.sizeDelta)) }); // always allow to decrease a position, otherwise a margin of minInitialMargin can never // decrease a position as the price goes against them. // we also add the paid out fee for the minInitialMargin because otherwise minInitialMargin // is never the actual minMargin, because the first trade will always deduct // a fee (so the margin that otherwise would need to be transferred would have to include the future // fee as well, making the UX and definition of min-margin confusing). bool positionDecreasing = _sameSide(oldPos.size, newPos.size) && _abs(newPos.size) < _abs(oldPos.size); if (!positionDecreasing) { // minMargin + fee <= margin is equivalent to minMargin <= margin - fee // except that we get a nicer error message if fee > margin, rather than arithmetic overflow. if (uint(newPos.margin).add(fee) < _minInitialMargin()) { return (oldPos, 0, Status.InsufficientMargin); } } // check that new position margin is above liquidation margin // (above, in _recomputeMarginWithDelta() we checked the old position, here we check the new one) // Liquidation margin is considered without a fee, because it wouldn't make sense to allow // a trade that will make the position liquidatable. if (newMargin <= _liquidationMargin(newPos.size, params.price)) { return (newPos, 0, Status.CanLiquidate); } // Check that the maximum leverage is not exceeded when considering new margin including the paid fee. // The paid fee is considered for the benefit of UX of allowed max leverage, otherwise, the actual // max leverage is always below the max leverage parameter since the fee paid for a trade reduces the margin. // We'll allow a little extra headroom for rounding errors. { // stack too deep int leverage = int(newPos.size).multiplyDecimal(int(params.price)).divideDecimal(int(newMargin.add(fee))); if (_maxLeverage(marketKey).add(uint(_UNIT) / 100) < _abs(leverage)) { return (oldPos, 0, Status.MaxLeverageExceeded); } } // Check that the order isn't too large for the market. // Allow a bit of extra value in case of rounding errors. if ( _orderSizeTooLarge( uint(int(_maxSingleSideValueUSD(marketKey).add(100 * uint(_UNIT))).divideDecimal(int(params.price))), oldPos.size, newPos.size ) ) { return (oldPos, 0, Status.MaxMarketSizeExceeded); } return (newPos, fee, Status.Ok); } /* ---------- Utilities ---------- */ /* * Absolute value of the input, returned as a signed number. */ function _signedAbs(int x) internal pure returns (int) { return x < 0 ? -x : x; } /* * Absolute value of the input, returned as an unsigned number. */ function _abs(int x) internal pure returns (uint) { return uint(_signedAbs(x)); } function _max(int x, int y) internal pure returns (int) { return x < y ? y : x; } function _min(int x, int y) internal pure returns (int) { return x < y ? x : y; } // True if and only if two positions a and b are on the same side of the market; // that is, if they have the same sign, or either of them is zero. function _sameSide(int a, int b) internal pure returns (bool) { return (a >= 0) == (b >= 0); } /* * True if and only if the given status indicates an error. */ function _isError(Status status) internal pure returns (bool) { return status != Status.Ok; } /* * Revert with an appropriate message if the first argument is true. */ function _revertIfError(bool isError, Status status) internal view { if (isError) { revert(_errorMessages[uint8(status)]); } } /* * Revert with an appropriate message if the input is an error. */ function _revertIfError(Status status) internal view { if (_isError(status)) { revert(_errorMessages[uint8(status)]); } } /* * The current base price from the oracle, and whether that price was invalid. Zero prices count as invalid. * Public because used both externally and internally */ function assetPrice() public view returns (uint price, bool invalid) { (price, invalid) = _exchangeCircuitBreaker().rateWithInvalid(baseAsset); return (price, invalid); } /* ========== MUTATIVE FUNCTIONS ========== */ /* ---------- Market Operations ---------- */ /** * The current base price, reverting if it is invalid, or if system or synth is suspended. * This is mutative because the circuit breaker stores the last price on every invocation. * @param allowMarketPaused if true, checks everything except the specific market, if false * checks only top level checks (system, exchange, futures) */ function _assetPriceRequireSystemChecks(bool allowMarketPaused) internal returns (uint) { // check that market isn't suspended, revert with appropriate message if (allowMarketPaused) { // this will check system activbe, exchange active, futures active _systemStatus().requireFuturesActive(); } else { // this will check all of the above + that specific market is active _systemStatus().requireFuturesMarketActive(marketKey); // asset and market may be different } // TODO: refactor the following when circuit breaker is updated. // The reason both view and mutative are used is because the breaker validates that the // synth exists, and for perps - the there is no synth, so in case of attempting to suspend // the suspension fails (reverts due to "No such synth") // check the view first and revert if price is invalid or out deviation range (uint price, bool invalid) = _exchangeCircuitBreaker().rateWithInvalid(baseAsset); _revertIfError(invalid, Status.InvalidPrice); // note: rateWithBreakCircuit (mutative) is used here in addition to rateWithInvalid (view). // This is despite reverting immediately after if circuit is broken, which may seem silly. // This is in order to persist last-rate in exchangeCircuitBreaker in the happy case // because last-rate is what used for measuring the deviation for subsequent trades. // This also means that the circuit will not be broken in unhappy case (synth suspended) // because this method will revert above. The reason it has to revert is that perps // don't support no-op actions. _exchangeCircuitBreaker().rateWithBreakCircuit(baseAsset); // persist rate for next checks return price; } // default of allowMarketPaused is false, allow calling without this flag function _assetPriceRequireSystemChecks() internal returns (uint) { return _assetPriceRequireSystemChecks(false); } function _recomputeFunding(uint price) internal returns (uint lastIndex) { uint sequenceLengthBefore = fundingSequence.length; int funding = _nextFundingEntry(price); fundingSequence.push(int128(funding)); fundingLastRecomputed = uint32(block.timestamp); emit FundingRecomputed(funding, sequenceLengthBefore, fundingLastRecomputed); return sequenceLengthBefore; } /** * Pushes a new entry to the funding sequence at the current price and funding rate. * @dev Admin only method accessible to FuturesMarketSettings. This is admin only because: * - When system parameters change, funding should be recomputed, but system may be paused * during that time for any reason, so this method needs to work even if system is paused. * But in that case, it shouldn't be accessible to external accounts. */ function recomputeFunding() external returns (uint lastIndex) { // only FuturesMarketSettings is allowed to use this method _revertIfError(msg.sender != _settings(), Status.NotPermitted); // This method uses the view _assetPrice() // and not the mutative _assetPriceRequireSystemChecks() that reverts on system flags. // This is because this method is used by system settings when changing funding related // parameters, so needs to function even when system / market is paused. E.g. to facilitate // market migration. (uint price, bool invalid) = assetPrice(); // A check for a valid price is still in place, to ensure that a system settings action // doesn't take place when the price is invalid (e.g. some oracle issue). require(!invalid, "Invalid price"); return _recomputeFunding(price); } /* * The impact of a given position on the debt correction. */ function _positionDebtCorrection(Position memory position) internal view returns (int) { /** This method only returns the correction term for the debt calculation of the position, and not it's debt. This is needed for keeping track of the _marketDebt() in an efficient manner to allow O(1) marketDebt calculation in _marketDebt(). Explanation of the full market debt calculation from the SIP https://sips.synthetix.io/sips/sip-80/: The overall market debt is the sum of the remaining margin in all positions. The intuition is that the debt of a single position is the value withdrawn upon closing that position. single position remaining margin = initial-margin + profit-loss + accrued-funding = = initial-margin + q * (price - last-price) + q * funding-accrued-per-unit = initial-margin + q * price - q * last-price + q * (funding - initial-funding) Total debt = sum ( position remaining margins ) = sum ( initial-margin + q * price - q * last-price + q * (funding - initial-funding) ) = sum( q * price ) + sum( q * funding ) + sum( initial-margin - q * last-price - q * initial-funding ) = skew * price + skew * funding + sum( initial-margin - q * ( last-price + initial-funding ) ) = skew (price + funding) + sum( initial-margin - q * ( last-price + initial-funding ) ) The last term: sum( initial-margin - q * ( last-price + initial-funding ) ) being the position debt correction that is tracked with each position change using this method. The first term and the full debt calculation using current skew, price, and funding is calculated globally in _marketDebt(). */ return int(position.margin).sub( int(position.size).multiplyDecimal(int(position.lastPrice).add(fundingSequence[position.lastFundingIndex])) ); } function _marketDebt(uint price) internal view returns (uint) { // short circuit and also convenient during setup if (marketSkew == 0 && _entryDebtCorrection == 0) { // if these are 0, the resulting calculation is necessarily zero as well return 0; } // see comment explaining this calculation in _positionDebtCorrection() int priceWithFunding = int(price).add(_nextFundingEntry(price)); int totalDebt = int(marketSkew).multiplyDecimal(priceWithFunding).add(_entryDebtCorrection); return uint(_max(totalDebt, 0)); } /* * Alter the debt correction to account for the net result of altering a position. */ function _applyDebtCorrection(Position memory newPosition, Position memory oldPosition) internal { int newCorrection = _positionDebtCorrection(newPosition); int oldCorrection = _positionDebtCorrection(oldPosition); _entryDebtCorrection = int128(int(_entryDebtCorrection).add(newCorrection).sub(oldCorrection)); } function _transferMargin( int marginDelta, uint price, address sender ) internal { // Transfer no tokens if marginDelta is 0 uint absDelta = _abs(marginDelta); if (marginDelta > 0) { // A positive margin delta corresponds to a deposit, which will be burnt from their // sUSD balance and credited to their margin account. // Ensure we handle reclamation when burning tokens. uint postReclamationAmount = _manager().burnSUSD(sender, absDelta); if (postReclamationAmount != absDelta) { // If balance was insufficient, the actual delta will be smaller marginDelta = int(postReclamationAmount); } } else if (marginDelta < 0) { // A negative margin delta corresponds to a withdrawal, which will be minted into // their sUSD balance, and debited from their margin account. _manager().issueSUSD(sender, absDelta); } else { // Zero delta is a no-op return; } Position storage position = positions[sender]; // initialise id if not initialised and store update id=>account mapping _initPosition(sender, position); // add the margin _updatePositionMargin(position, price, marginDelta); emit MarginTransferred(sender, marginDelta); emit PositionModified(position.id, sender, position.margin, position.size, 0, price, _latestFundingIndex(), 0); } function _initPosition(address account, Position storage position) internal { // if position has no id, give it an incremental id if (position.id == 0) { lastPositionId++; // increment position id uint64 id = lastPositionId; position.id = id; positionIdOwner[id] = account; } } // updates the stored position margin in place (on the stored position) function _updatePositionMargin( Position storage position, uint price, int marginDelta ) internal { Position memory oldPosition = position; // Determine new margin, ensuring that the result is positive. (uint margin, Status status) = _recomputeMarginWithDelta(oldPosition, price, marginDelta); _revertIfError(status); // Update the debt correction. int positionSize = position.size; uint fundingIndex = _latestFundingIndex(); _applyDebtCorrection( Position(0, uint64(fundingIndex), uint128(margin), uint128(price), int128(positionSize)), Position(0, position.lastFundingIndex, position.margin, position.lastPrice, int128(positionSize)) ); // Update the account's position with the realised margin. position.margin = uint128(margin); // We only need to update their funding/PnL details if they actually have a position open if (positionSize != 0) { position.lastPrice = uint128(price); position.lastFundingIndex = uint64(fundingIndex); // The user can always decrease their margin if they have no position, or as long as: // * they have sufficient margin to do so // * the resulting margin would not be lower than the liquidation margin or min initial margin // * the resulting leverage is lower than the maximum leverage if (marginDelta < 0) { _revertIfError( (margin < _minInitialMargin()) || (margin <= _liquidationMargin(position.size, price)) || (_maxLeverage(marketKey) < _abs(_currentLeverage(position, price, margin))), Status.InsufficientMargin ); } } } /* * Alter the amount of margin in a position. A positive input triggers a deposit; a negative one, a * withdrawal. The margin will be burnt or issued directly into/out of the caller's sUSD wallet. * Reverts on deposit if the caller lacks a sufficient sUSD balance. * Reverts on withdrawal if the amount to be withdrawn would expose an open position to liquidation. */ function transferMargin(int marginDelta) external { // allow topping up margin if this specific market is paused. // will still revert on all other checks (system, exchange, futures in general) bool allowMarketPaused = marginDelta > 0; uint price = _assetPriceRequireSystemChecks(allowMarketPaused); _recomputeFunding(price); _transferMargin(marginDelta, price, msg.sender); } /* * Withdraws all accessible margin in a position. This will leave some remaining margin * in the account if the caller has a position open. Equivalent to `transferMargin(-accessibleMargin(sender))`. */ function withdrawAllMargin() external { address sender = msg.sender; uint price = _assetPriceRequireSystemChecks(); _recomputeFunding(price); int marginDelta = -int(_accessibleMargin(positions[sender], price)); _transferMargin(marginDelta, price, sender); } function _trade(address sender, TradeParams memory params) internal { Position storage position = positions[sender]; Position memory oldPosition = position; // Compute the new position after performing the trade (Position memory newPosition, uint fee, Status status) = _postTradeDetails(oldPosition, params); _revertIfError(status); // Update the aggregated market size and skew with the new order size marketSkew = int128(int(marketSkew).add(newPosition.size).sub(oldPosition.size)); marketSize = uint128(uint(marketSize).add(_abs(newPosition.size)).sub(_abs(oldPosition.size))); // Send the fee to the fee pool if (0 < fee) { _manager().payFee(fee, params.trackingCode); // emit tracking code event if (params.trackingCode != bytes32(0)) { emit Tracking(params.trackingCode, baseAsset, marketKey, params.sizeDelta, fee); } } // Update the margin, and apply the resulting debt correction position.margin = newPosition.margin; _applyDebtCorrection(newPosition, oldPosition); // Record the trade uint64 id = oldPosition.id; uint fundingIndex = _latestFundingIndex(); position.size = newPosition.size; position.lastPrice = uint128(params.price); position.lastFundingIndex = uint64(fundingIndex); // emit the modification event emit PositionModified( id, sender, newPosition.margin, newPosition.size, params.sizeDelta, params.price, fundingIndex, fee ); } /* * Adjust the sender's position size. * Reverts if the resulting position is too large, outside the max leverage, or is liquidating. */ function modifyPosition(int sizeDelta) external { _modifyPosition(sizeDelta, bytes32(0)); } /* * Same as modifyPosition, but emits an event with the passed tracking code to * allow offchain calculations for fee sharing with originating integrations */ function modifyPositionWithTracking(int sizeDelta, bytes32 trackingCode) external { _modifyPosition(sizeDelta, trackingCode); } function _modifyPosition(int sizeDelta, bytes32 trackingCode) internal { uint price = _assetPriceRequireSystemChecks(); _recomputeFunding(price); _trade( msg.sender, TradeParams({sizeDelta: sizeDelta, price: price, baseFee: _baseFee(marketKey), trackingCode: trackingCode}) ); } /* * Submit an order to close a position. */ function closePosition() external { _closePosition(bytes32(0)); } /// Same as closePosition, but emits an even with the trackingCode for volume source fee sharing function closePositionWithTracking(bytes32 trackingCode) external { _closePosition(trackingCode); } function _closePosition(bytes32 trackingCode) internal { int size = positions[msg.sender].size; _revertIfError(size == 0, Status.NoPositionOpen); uint price = _assetPriceRequireSystemChecks(); _recomputeFunding(price); _trade( msg.sender, TradeParams({sizeDelta: -size, price: price, baseFee: _baseFee(marketKey), trackingCode: trackingCode}) ); } function _liquidatePosition( address account, address liquidator, uint price ) internal { Position storage position = positions[account]; // get remaining margin for sending any leftover buffer to fee pool uint remMargin = _remainingMargin(position, price); // Record updates to market size and debt. int positionSize = position.size; uint positionId = position.id; marketSkew = int128(int(marketSkew).sub(positionSize)); marketSize = uint128(uint(marketSize).sub(_abs(positionSize))); uint fundingIndex = _latestFundingIndex(); _applyDebtCorrection( Position(0, uint64(fundingIndex), 0, uint128(price), 0), Position(0, position.lastFundingIndex, position.margin, position.lastPrice, int128(positionSize)) ); // Close the position size and margin delete positions[account].size; delete positions[account].margin; // Issue the reward to the liquidator. uint liqFee = _liquidationFee(positionSize, price); _manager().issueSUSD(liquidator, liqFee); emit PositionModified(positionId, account, 0, 0, 0, price, fundingIndex, 0); emit PositionLiquidated(positionId, account, liquidator, positionSize, price, liqFee); // Send any positive margin buffer to the fee pool if (remMargin > liqFee) { _manager().payFee(remMargin.sub(liqFee), bytes32(0)); } } /* * Liquidate a position if its remaining margin is below the liquidation fee. This succeeds if and only if * `canLiquidate(account)` is true, and reverts otherwise. * Upon liquidation, the position will be closed, and the liquidation fee minted into the liquidator's account. */ function liquidatePosition(address account) external { uint price = _assetPriceRequireSystemChecks(); _recomputeFunding(price); _revertIfError(!_canLiquidate(positions[account], price), Status.CannotLiquidate); _liquidatePosition(account, msg.sender, price); } /* ========== EVENTS ========== */ event MarginTransferred(address indexed account, int marginDelta); event PositionModified( uint indexed id, address indexed account, uint margin, int size, int tradeSize, uint lastPrice, uint fundingIndex, uint fee ); event PositionLiquidated( uint indexed id, address indexed account, address indexed liquidator, int size, uint price, uint fee ); event FundingRecomputed(int funding, uint index, uint timestamp); event Tracking(bytes32 indexed trackingCode, bytes32 baseAsset, bytes32 marketKey, int sizeDelta, uint fee); }
The value in a position's margin after a deposit or withdrawal, accounting for funding and profit. If the resulting margin would be negative or below the liquidation threshold, an appropriate error is returned. If the result is not an error, callers of this function that use it to update a position's margin must ensure that this is accompanied by a corresponding debt correction update, as per `_applyDebtCorrection`./
function _recomputeMarginWithDelta( Position memory position, uint price, int marginDelta ) internal view returns (uint margin, Status statusCode) { int newMargin = _marginPlusProfitFunding(position, price).add(marginDelta); if (newMargin < 0) { return (0, Status.InsufficientMargin); } uint uMargin = uint(newMargin); int positionSize = int(position.size); if (positionSize != 0 && uMargin <= lMargin) { return (uMargin, Status.CanLiquidate); } return (uMargin, Status.Ok); }
12,935,987
[ 1, 1986, 460, 316, 279, 1754, 1807, 7333, 1839, 279, 443, 1724, 578, 598, 9446, 287, 16, 2236, 310, 364, 22058, 471, 450, 7216, 18, 971, 326, 8156, 7333, 4102, 506, 6092, 578, 5712, 326, 4501, 26595, 367, 5573, 16, 392, 5505, 555, 353, 2106, 18, 971, 326, 563, 353, 486, 392, 555, 16, 19932, 434, 333, 445, 716, 999, 518, 358, 1089, 279, 1754, 1807, 7333, 1297, 3387, 716, 333, 353, 1721, 2919, 304, 2092, 635, 279, 4656, 18202, 88, 15104, 1089, 16, 487, 1534, 1375, 67, 9010, 758, 23602, 20884, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 266, 9200, 9524, 1190, 9242, 12, 203, 3639, 11010, 3778, 1754, 16, 203, 3639, 2254, 6205, 16, 203, 3639, 509, 7333, 9242, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 7333, 16, 2685, 6593, 13, 288, 203, 3639, 509, 394, 9524, 273, 389, 10107, 13207, 626, 7216, 42, 14351, 12, 3276, 16, 6205, 2934, 1289, 12, 10107, 9242, 1769, 203, 3639, 309, 261, 2704, 9524, 411, 374, 13, 288, 203, 5411, 327, 261, 20, 16, 2685, 18, 5048, 11339, 9524, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 582, 9524, 273, 2254, 12, 2704, 9524, 1769, 203, 3639, 509, 1754, 1225, 273, 509, 12, 3276, 18, 1467, 1769, 203, 3639, 309, 261, 3276, 1225, 480, 374, 597, 582, 9524, 1648, 328, 9524, 13, 288, 203, 5411, 327, 261, 89, 9524, 16, 2685, 18, 2568, 48, 18988, 350, 340, 1769, 203, 3639, 289, 203, 203, 3639, 327, 261, 89, 9524, 16, 2685, 18, 8809, 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 ]
pragma solidity =0.5.16; import 'OpenZeppelin/[email protected]/contracts/ownership/Ownable.sol'; import 'OpenZeppelin/[email protected]/contracts/token/ERC20/IERC20.sol'; import 'Uniswap/[email protected]/contracts/libraries/Math.sol'; import './uniswap/UniswapV2Library.sol'; import './uniswap/IUniswapV2Router02.sol'; import './interfaces/IBank.sol'; // helper methods for interacting with ERC20 tokens and sending BNB that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED' ); } function safeTransfer( address token, address to, uint value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED' ); } function safeTransferFrom( address token, address from, address to, uint value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED' ); } function safeTransferBNB(address to, uint value) internal { (bool success, ) = to.call.value(value)(new bytes(0)); require(success, 'TransferHelper: BNB_TRANSFER_FAILED'); } } contract IbBNBRouter is Ownable { using SafeMath for uint; address public router; address public ibBNB; address public alpha; address public lpToken; constructor( address _router, address _ibBNB, address _alpha ) public { router = _router; ibBNB = _ibBNB; alpha = _alpha; address factory = IUniswapV2Router02(router).factory(); lpToken = UniswapV2Library.pairFor(factory, ibBNB, alpha); IUniswapV2Pair(lpToken).approve(router, uint(-1)); // 100% trust in the router IBank(ibBNB).approve(router, uint(-1)); // 100% trust in the router IERC20(alpha).approve(router, uint(-1)); // 100% trust in the router } function() external payable { assert(msg.sender == ibBNB); // only accept BNB via fallback from the Bank contract } // **** BNB-ibBNB FUNCTIONS **** // Get number of ibBNB needed to withdraw to get exact amountBNB from the Bank function ibBNBForExactBNB(uint amountBNB) public view returns (uint) { uint totalBNB = IBank(ibBNB).totalBNB(); return totalBNB == 0 ? amountBNB : amountBNB.mul(IBank(ibBNB).totalSupply()).add(totalBNB).sub(1).div(totalBNB); } // Add BNB and Alpha from ibBNB-Alpha Pool. // 1. Receive BNB and Alpha from caller. // 2. Wrap BNB to ibBNB. // 3. Provide liquidity to the pool. function addLiquidityBNB( uint amountAlphaDesired, uint amountAlphaMin, uint amountBNBMin, address to, uint deadline ) external payable returns ( uint amountAlpha, uint amountBNB, uint liquidity ) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired); IBank(ibBNB).deposit.value(msg.value)(); uint amountIbBNBDesired = IBank(ibBNB).balanceOf(address(this)); uint amountIbBNB; (amountAlpha, amountIbBNB, liquidity) = IUniswapV2Router02(router).addLiquidity( alpha, ibBNB, amountAlphaDesired, amountIbBNBDesired, amountAlphaMin, 0, to, deadline ); if (amountAlphaDesired > amountAlpha) { TransferHelper.safeTransfer(alpha, msg.sender, amountAlphaDesired.sub(amountAlpha)); } IBank(ibBNB).withdraw(amountIbBNBDesired.sub(amountIbBNB)); amountBNB = msg.value.sub(address(this).balance); if (amountBNB > 0) { TransferHelper.safeTransferBNB(msg.sender, address(this).balance); } require(amountBNB >= amountBNBMin, 'IbBNBRouter: require more BNB than amountBNBmin'); } /// @dev Compute optimal deposit amount /// @param amtA amount of token A desired to deposit /// @param amtB amount of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve /// (forked from ./StrategyAddTwoSidesOptimal.sol) function optimalDeposit( uint amtA, uint amtB, uint resA, uint resB ) internal pure returns (uint swapAmt, bool isReversed) { if (amtA.mul(resB) >= amtB.mul(resA)) { swapAmt = _optimalDepositA(amtA, amtB, resA, resB); isReversed = false; } else { swapAmt = _optimalDepositA(amtB, amtA, resB, resA); isReversed = true; } } /// @dev Compute optimal deposit amount helper /// @param amtA amount of token A desired to deposit /// @param amtB amount of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve /// (forked from ./StrategyAddTwoSidesOptimal.sol) function _optimalDepositA( uint amtA, uint amtB, uint resA, uint resB ) internal pure returns (uint) { require(amtA.mul(resB) >= amtB.mul(resA), 'Reversed'); uint a = 998; uint b = uint(1998).mul(resA); uint _c = (amtA.mul(resB)).sub(amtB.mul(resA)); uint c = _c.mul(1000).div(amtB.add(resB)).mul(resA); uint d = a.mul(c).mul(4); uint e = Math.sqrt(b.mul(b).add(d)); uint numerator = e.sub(b); uint denominator = a.mul(2); return numerator.div(denominator); } // Add ibBNB and Alpha to ibBNB-Alpha Pool. // All ibBNB and Alpha supplied are optimally swap and add too ibBNB-Alpha Pool. function addLiquidityTwoSidesOptimal( uint amountIbBNBDesired, uint amountAlphaDesired, uint amountLPMin, address to, uint deadline ) external returns (uint liquidity) { if (amountIbBNBDesired > 0) { TransferHelper.safeTransferFrom(ibBNB, msg.sender, address(this), amountIbBNBDesired); } if (amountAlphaDesired > 0) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired); } uint swapAmt; bool isReversed; { (uint r0, uint r1, ) = IUniswapV2Pair(lpToken).getReserves(); (uint ibBNBReserve, uint alphaReserve) = IUniswapV2Pair(lpToken).token0() == ibBNB ? (r0, r1) : (r1, r0); (swapAmt, isReversed) = optimalDeposit( amountIbBNBDesired, amountAlphaDesired, ibBNBReserve, alphaReserve ); } address[] memory path = new address[](2); (path[0], path[1]) = isReversed ? (alpha, ibBNB) : (ibBNB, alpha); IUniswapV2Router02(router).swapExactTokensForTokens(swapAmt, 0, path, address(this), now); (, , liquidity) = IUniswapV2Router02(router).addLiquidity( alpha, ibBNB, IERC20(alpha).balanceOf(address(this)), IBank(ibBNB).balanceOf(address(this)), 0, 0, to, deadline ); uint dustAlpha = IERC20(alpha).balanceOf(address(this)); uint dustIbBNB = IBank(ibBNB).balanceOf(address(this)); if (dustAlpha > 0) { TransferHelper.safeTransfer(alpha, msg.sender, dustAlpha); } if (dustIbBNB > 0) { TransferHelper.safeTransfer(ibBNB, msg.sender, dustIbBNB); } require(liquidity >= amountLPMin, 'IbBNBRouter: receive less lpToken than amountLPMin'); } // Add BNB and Alpha to ibBNB-Alpha Pool. // All BNB and Alpha supplied are optimally swap and add too ibBNB-Alpha Pool. function addLiquidityTwoSidesOptimalBNB( uint amountAlphaDesired, uint amountLPMin, address to, uint deadline ) external payable returns (uint liquidity) { if (amountAlphaDesired > 0) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired); } IBank(ibBNB).deposit.value(msg.value)(); uint amountIbBNBDesired = IBank(ibBNB).balanceOf(address(this)); uint swapAmt; bool isReversed; { (uint r0, uint r1, ) = IUniswapV2Pair(lpToken).getReserves(); (uint ibBNBReserve, uint alphaReserve) = IUniswapV2Pair(lpToken).token0() == ibBNB ? (r0, r1) : (r1, r0); (swapAmt, isReversed) = optimalDeposit( amountIbBNBDesired, amountAlphaDesired, ibBNBReserve, alphaReserve ); } address[] memory path = new address[](2); (path[0], path[1]) = isReversed ? (alpha, ibBNB) : (ibBNB, alpha); IUniswapV2Router02(router).swapExactTokensForTokens(swapAmt, 0, path, address(this), now); (, , liquidity) = IUniswapV2Router02(router).addLiquidity( alpha, ibBNB, IERC20(alpha).balanceOf(address(this)), IBank(ibBNB).balanceOf(address(this)), 0, 0, to, deadline ); uint dustAlpha = IERC20(alpha).balanceOf(address(this)); uint dustIbBNB = IBank(ibBNB).balanceOf(address(this)); if (dustAlpha > 0) { TransferHelper.safeTransfer(alpha, msg.sender, dustAlpha); } if (dustIbBNB > 0) { TransferHelper.safeTransfer(ibBNB, msg.sender, dustIbBNB); } require(liquidity >= amountLPMin, 'IbBNBRouter: receive less lpToken than amountLPMin'); } // Remove BNB and Alpha from ibBNB-Alpha Pool. // 1. Remove ibBNB and Alpha from the pool. // 2. Unwrap ibBNB to BNB. // 3. Return BNB and Alpha to caller. function removeLiquidityBNB( uint liquidity, uint amountAlphaMin, uint amountBNBMin, address to, uint deadline ) public returns (uint amountAlpha, uint amountBNB) { TransferHelper.safeTransferFrom(lpToken, msg.sender, address(this), liquidity); uint amountIbBNB; (amountAlpha, amountIbBNB) = IUniswapV2Router02(router).removeLiquidity( alpha, ibBNB, liquidity, amountAlphaMin, 0, address(this), deadline ); TransferHelper.safeTransfer(alpha, to, amountAlpha); IBank(ibBNB).withdraw(amountIbBNB); amountBNB = address(this).balance; if (amountBNB > 0) { TransferHelper.safeTransferBNB(to, address(this).balance); } require(amountBNB >= amountBNBMin, 'IbBNBRouter: receive less BNB than amountBNBmin'); } // Remove liquidity from ibBNB-Alpha Pool and convert all ibBNB to Alpha // 1. Remove ibBNB and Alpha from the pool. // 2. Swap ibBNB for Alpha. // 3. Return Alpha to caller. function removeLiquidityAllAlpha( uint liquidity, uint amountAlphaMin, address to, uint deadline ) public returns (uint amountAlpha) { TransferHelper.safeTransferFrom(lpToken, msg.sender, address(this), liquidity); (uint removeAmountAlpha, uint removeAmountIbBNB) = IUniswapV2Router02(router).removeLiquidity( alpha, ibBNB, liquidity, 0, 0, address(this), deadline ); address[] memory path = new address[](2); path[0] = ibBNB; path[1] = alpha; uint[] memory amounts = IUniswapV2Router02(router).swapExactTokensForTokens(removeAmountIbBNB, 0, path, to, deadline); TransferHelper.safeTransfer(alpha, to, removeAmountAlpha); amountAlpha = removeAmountAlpha.add(amounts[1]); require(amountAlpha >= amountAlphaMin, 'IbBNBRouter: receive less Alpha than amountAlphaMin'); } // Swap exact amount of BNB for Token // 1. Receive BNB from caller // 2. Wrap BNB to ibBNB. // 3. Swap ibBNB for Token function swapExactBNBForAlpha( uint amountAlphaOutMin, address to, uint deadline ) external payable returns (uint[] memory amounts) { IBank(ibBNB).deposit.value(msg.value)(); address[] memory path = new address[](2); path[0] = ibBNB; path[1] = alpha; uint[] memory swapAmounts = IUniswapV2Router02(router).swapExactTokensForTokens( IBank(ibBNB).balanceOf(address(this)), amountAlphaOutMin, path, to, deadline ); amounts = new uint[](2); amounts[0] = msg.value; amounts[1] = swapAmounts[1]; } // Swap Token for exact amount of BNB // 1. Receive Token from caller // 2. Swap Token for ibBNB. // 3. Unwrap ibBNB to BNB. function swapAlphaForExactBNB( uint amountBNBOut, uint amountAlphaInMax, address to, uint deadline ) external returns (uint[] memory amounts) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaInMax); address[] memory path = new address[](2); path[0] = alpha; path[1] = ibBNB; IBank(ibBNB).withdraw(0); uint[] memory swapAmounts = IUniswapV2Router02(router).swapTokensForExactTokens( ibBNBForExactBNB(amountBNBOut), amountAlphaInMax, path, address(this), deadline ); IBank(ibBNB).withdraw(swapAmounts[1]); amounts = new uint[](2); amounts[0] = swapAmounts[0]; amounts[1] = address(this).balance; TransferHelper.safeTransferBNB(to, address(this).balance); if (amountAlphaInMax > amounts[0]) { TransferHelper.safeTransfer(alpha, msg.sender, amountAlphaInMax.sub(amounts[0])); } } // Swap exact amount of Token for BNB // 1. Receive Token from caller // 2. Swap Token for ibBNB. // 3. Unwrap ibBNB to BNB. function swapExactAlphaForBNB( uint amountAlphaIn, uint amountBNBOutMin, address to, uint deadline ) external returns (uint[] memory amounts) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaIn); address[] memory path = new address[](2); path[0] = alpha; path[1] = ibBNB; uint[] memory swapAmounts = IUniswapV2Router02(router).swapExactTokensForTokens( amountAlphaIn, 0, path, address(this), deadline ); IBank(ibBNB).withdraw(swapAmounts[1]); amounts = new uint[](2); amounts[0] = swapAmounts[0]; amounts[1] = address(this).balance; TransferHelper.safeTransferBNB(to, amounts[1]); require(amounts[1] >= amountBNBOutMin, 'IbBNBRouter: receive less BNB than amountBNBmin'); } // Swap BNB for exact amount of Token // 1. Receive BNB from caller // 2. Wrap BNB to ibBNB. // 3. Swap ibBNB for Token function swapBNBForExactAlpha( uint amountAlphaOut, address to, uint deadline ) external payable returns (uint[] memory amounts) { IBank(ibBNB).deposit.value(msg.value)(); uint amountIbBNBInMax = IBank(ibBNB).balanceOf(address(this)); address[] memory path = new address[](2); path[0] = ibBNB; path[1] = alpha; uint[] memory swapAmounts = IUniswapV2Router02(router).swapTokensForExactTokens( amountAlphaOut, amountIbBNBInMax, path, to, deadline ); amounts = new uint[](2); amounts[0] = msg.value; amounts[1] = swapAmounts[1]; // Transfer left over BNB back if (amountIbBNBInMax > swapAmounts[0]) { IBank(ibBNB).withdraw(amountIbBNBInMax.sub(swapAmounts[0])); amounts[0] = msg.value.sub(address(this).balance); TransferHelper.safeTransferBNB(msg.sender, address(this).balance); } } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover( address token, address to, uint value ) external onlyOwner { TransferHelper.safeTransfer(token, to, value); } /// @dev Recover BNB that were accidentally sent to this smart contract. /// @param to The address to send the BNB to. /// @param value The number of BNB to transfer to `to`. function recoverBNB(address to, uint value) external onlyOwner { TransferHelper.safeTransferBNB(to, value); } }
@dev Recover BNB that were accidentally sent to this smart contract. @param to The address to send the BNB to. @param value The number of BNB to transfer to `to`.
function recoverBNB(address to, uint value) external onlyOwner { TransferHelper.safeTransferBNB(to, value); }
5,453,110
[ 1, 27622, 605, 20626, 716, 4591, 25961, 1230, 3271, 358, 333, 13706, 6835, 18, 225, 358, 1021, 1758, 358, 1366, 326, 605, 20626, 358, 18, 225, 460, 1021, 1300, 434, 605, 20626, 358, 7412, 358, 1375, 869, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 5910, 15388, 38, 12, 2867, 358, 16, 2254, 460, 13, 3903, 1338, 5541, 288, 203, 565, 12279, 2276, 18, 4626, 5912, 15388, 38, 12, 869, 16, 460, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract Wemark is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function Wemark() { balances[msg.sender] = 135000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 135000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "Wemark Token"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "WMK"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 500000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() public payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
Set the symbol for display purposes (CHANGE THIS)
symbol = "WMK";
6,873,454
[ 1, 694, 326, 3273, 364, 2562, 13694, 261, 14473, 20676, 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, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3273, 273, 315, 25173, 47, 14432, 4766, 2868, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.12; // SPDX-License-Identifier: MIT /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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 provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // BTA with Governance. contract BTA is ERC20("BTA TOKEN", "BTAD"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } } contract BTADChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of BTADs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBTADPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBTADPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. BTADs to distribute per block. uint256 lastRewardBlock; // Last block number that BTADs distribution occurs. uint256 accBTADPerShare; // Accumulated BTADs per share, times 1e12. See below. } // The BTAD TOKEN! BTA public BTAD; // Dev address. address public devaddr; // Block number when bonus BTAD period ends. uint256 public bonusEndBlock; // BTAD tokens created per block. uint256 public BTADPerBlock; // Bonus muliplier for early BTAD makers. uint256 public constant BONUS_MULTIPLIER = 1; // no bonus // No of blocks in a day - 7000 uint256 public constant perDayBlocks = 7000; // no bonus // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that BTADs LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BTAD mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( BTA _BTAD, address _devaddr, uint256 _BTADPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { BTAD = _BTAD; devaddr = _devaddr; BTADPerBlock = _BTADPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBTADPerShare: 0 })); } // Update the given pool's BTAD allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // reward prediction at specific block function getRewardPerBlock(uint blockNumber) public view returns (uint256) { if (blockNumber >= startBlock){ uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks); if(blockDaysPassed <= 0){ return BTADPerBlock; } } else { return 0; } } // View function to see pending BTADs on frontend. function pendingBTAD(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBTADPerShare = pool.accBTADPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rewardThisBlock = getRewardPerBlock(block.number); uint256 BTADReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint); accBTADPerShare = accBTADPerShare.add(BTADReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBTADPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rewardThisBlock = getRewardPerBlock(block.number); uint256 BTADReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint); BTAD.mint(devaddr, BTADReward.div(10)); // 10% BTAD.mint(address(this), BTADReward); pool.accBTADPerShare = pool.accBTADPerShare.add(BTADReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for BTAD allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBTADPerShare).div(1e12).sub(user.rewardDebt); safeBTADTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accBTADPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accBTADPerShare).div(1e12).sub(user.rewardDebt); safeBTADTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accBTADPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe BTAD transfer function, just in case if rounding error causes pool to not have enough BTADs. function safeBTADTransfer(address _to, uint256 _amount) internal { uint256 BTADBal = BTAD.balanceOf(address(this)); if (_amount > BTADBal) { BTAD.transfer(_to, BTADBal); } else { BTAD.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
BTAD tokens created per block.
uint256 public BTADPerBlock;
10,296,222
[ 1, 38, 56, 1880, 2430, 2522, 1534, 1203, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 605, 56, 1880, 2173, 1768, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; // ---------------------------------------------------------------------------- // 'PAYTOKEN' contract with following features // => In-built ICO functionality - Infinite duration // => ERC20 Compliance // => Higher control of ICO by admin/owner // => selfdestruct functionality // => SafeMath implementation // // Deployed to : 0x6A51a1415ED5e6156D4A6046C890e2f2a4Cfd0B9 // Symbol : PAYTK // Name : PAYTOKEN // Total supply: 1,000,000,000 (1 Billion) // Decimals : 18 // // Copyright (c) 2018 Payou Ltd, Malta (https://paytoken.co) // ---------------------------------------------------------------------------- /** * @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; } } contract owned { address public owner; using SafeMath for uint256; constructor () public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token using SafeMath for uint256; string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; bool public safeguard = false; //putting safeguard on will halt all non-owner functions // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor ( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply.mul(1 ether); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(!safeguard); // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(!safeguard); require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { require(!safeguard); allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { require(!safeguard); tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(!safeguard); require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(!safeguard); require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } } //*******************************************************// //------------- ADVANCED TOKEN STARTS HERE -------------// //*******************************************************// contract PAYTOKEN is owned, TokenERC20 { using SafeMath for uint256; /**********************************/ /* Code for the ERC20 PAYTOKEN */ /**********************************/ // Public variables of the token string private tokenName = "PAYTOKEN"; string private tokenSymbol = "PAYTK"; uint256 private initialSupply = 1000000000; // Initial supply of the tokens // Records for the fronzen accounts mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor () TokenERC20(initialSupply, tokenName, tokenSymbol) public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(!safeguard); require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /**************************/ /* Code for the Crowdsale */ /**************************/ //public variables for the Crowdsale uint256 public icoStartDate = 999 ; // Any past timestamp uint256 public icoEndDate = 9999999999999999 ; // Infinite end date. uint256 public exchangeRate = 10000; // 1 ETH = 10000 Tokens uint256 public tokensSold = 0; // how many tokens sold through crowdsale //@dev fallback function, only accepts ether if ICO is running or Reject function () payable public { require(icoEndDate > now); require(icoStartDate < now); require(!safeguard); uint ethervalueWEI=msg.value; // calculate token amount to be sent uint256 token = ethervalueWEI.mul(exchangeRate); //weiamount * price tokensSold = tokensSold.add(token); _transfer(this, msg.sender, token); // makes the transfers forwardEherToOwner(); } //Automatocally forwards ether from smart contract to owner address function forwardEherToOwner() internal { owner.transfer(msg.value); } //function to start an ICO. //It requires: timestamp of start and end date, exchange rate (1 ETH = ? Tokens), and token amounts to allocate for the ICO //It will transfer allocated amount to the smart contract from Owner function startIco(uint256 start,uint256 end, uint256 exchangeRateNew, uint256 TokensAllocationForICO) onlyOwner public { require(start < end); uint256 tokenAmount = TokensAllocationForICO.mul(1 ether); require(balanceOf[msg.sender] > tokenAmount); icoStartDate=start; icoEndDate=end; exchangeRate = exchangeRateNew; approve(this,tokenAmount); transfer(this,tokenAmount); } //Stops an ICO. //It will also transfer remaining tokens to owner function stopICO() onlyOwner public{ icoEndDate = 0; uint256 tokenAmount=balanceOf[this]; _transfer(this, msg.sender, tokenAmount); } //function to check wheter ICO is running or not. function isICORunning() public view returns(bool){ if(icoEndDate > now && icoStartDate < now){ return true; }else{ return false; } } //Function to set ICO Exchange rate. function setICOExchangeRate(uint256 newExchangeRate) onlyOwner public { exchangeRate=newExchangeRate; } //Just in case, owner wants to transfer Tokens from contract to owner address function manualWithdrawToken(uint256 _amount) onlyOwner public { uint256 tokenAmount = _amount.mul(1 ether); _transfer(this, msg.sender, tokenAmount); } //Just in case, owner wants to transfer Ether from contract to owner address function manualWithdrawEther()onlyOwner public{ uint256 amount=address(this).balance; owner.transfer(amount); } //selfdestruct function. just in case owner decided to destruct this contract. function destructContract()onlyOwner public{ selfdestruct(owner); } /** * Change safeguard status on or off * * When safeguard is true, then all the non-owner functions will stop working. */ function changeSafeguardStatus() onlyOwner public{ if (safeguard == false){ safeguard = true; } else{ safeguard = false; } } }
* Destroy tokens from other account Remove `_value` tokens from the system irreversibly on behalf of `_from`. @param _from the address of the sender @param _value the amount of money to burn/
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(!safeguard); emit Burn(_from, _value); return true; }
1,510,135
[ 1, 10740, 2430, 628, 1308, 2236, 3581, 1375, 67, 1132, 68, 2430, 628, 326, 2619, 9482, 266, 2496, 24755, 603, 12433, 6186, 434, 1375, 67, 2080, 8338, 225, 389, 2080, 326, 1758, 434, 326, 5793, 225, 389, 1132, 326, 3844, 434, 15601, 358, 18305, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 445, 18305, 1265, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 5411, 2583, 12, 5, 87, 1727, 1332, 89, 1060, 1769, 203, 6647, 202, 18356, 225, 605, 321, 24899, 2080, 16, 389, 1132, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 540, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Mintable.sol"; import "./IBBLRToken.sol"; /** * @title Bubblr ERC721 token * @dev */ contract MATToken is ERC721Full, ERC721Mintable { using SafeMath for uint256; /*** TODO Testing (remove for production) ***/ uint256 public constant OPENING_RATE = 6400; function test(uint256 asset) external returns (uint256) { return _valueToken.balanceOf(msg.sender); } /*** State Variables ***/ IBBLRToken private _valueToken; // Token to use for value transfer mapping(uint256 => mapping (address => string)) private _facts; // Staked facts function fact(uint256 asset, address owner) external view returns (string) { return _facts[asset][owner]; } mapping(uint256 => bool) private _verified; // Is asset in varified state function verified(uint256 asset) external view returns (bool) { return _verified[asset]; } mapping(uint256 => bool) private _published; // Is asset in published state function published(uint256 asset) external view returns (bool) { return _published[asset]; } /*** Events ***/ /* Initializes contract */ constructor(address valueToken) ERC721Full("MATToken", "MAT") public { _valueToken = IBBLRToken(valueToken); } // To mint, call mintWithTokenURI(to, tokenId, tokenURI) // TODO add or get timestamp when minted for timeout // to read asset, call tokenURI(tokenId) /* Support unvarified content */ function support(uint256 asset) external { } /* Attach a positive or negative fact to an asset with a BBLR stake */ function factCheck(uint256 asset, uint256 stake, bool positive, string URI) external { } /* Boost an owned asset by offering BBLR stake */ function boost(uint256 asset, uint256 stake) external { require(_isApprovedOrOwner(msg.sender, asset), ""); // Only owner or approved operator of the asset } /* Publish and unpublish asset content on the Bubblr consumer app */ function publish(uint256 asset) external { require(_isApprovedOrOwner(msg.sender, asset), ""); // Only owner or approved operator of the asset _published[asset] = true; } function unpublish(uint256 asset) external { require(_isApprovedOrOwner(msg.sender, asset), ""); // Only owner or approved operator of the asset delete _published[asset]; } /* (called whenever someone tries to send ether to this contract) */ function() external payable { require(msg.value != 0, ""); // Stop spamming, contract only calls, etc require(msg.sender != address(0), ""); // Prevent transfer to 0x0 address require(msg.sender != address(this), ""); // Prevent calls from this.transfer(this) // assert(address(this).balance >= msg.value, ""); // this.balance gets updated with msg.value before this function starts } }
Boost an owned asset by offering BBLR stake */
function boost(uint256 asset, uint256 stake) external { }
12,906,300
[ 1, 26653, 392, 16199, 3310, 635, 10067, 310, 605, 14618, 54, 384, 911, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14994, 12, 11890, 5034, 3310, 16, 2254, 5034, 384, 911, 13, 3903, 288, 203, 540, 203, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBa375Ad13559AC07baDbf4353E9afD1FE8920b68/sources/contracts/multiTransfer.sol
SPDX-License-Identifier:MIT
pragma solidity >=0.8.2 <0.8.5;
17,160,477
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 6068, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 22, 411, 20, 18, 28, 18, 25, 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 ]
./full_match/80001/0xEE51AC33a7258ce51E2ff4A3DcAbb629b1B6A858/sources/contracts/NFT.sol
function to show the imageURI
function getImageURI() public view returns (string memory) { return imageUri; }
5,555,643
[ 1, 915, 358, 2405, 326, 1316, 3098, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10567, 3098, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 1316, 3006, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xaBcf18BF1937e3d7Bac7Ac743b7829aD6aD6D2ca/sources/contracts/MintPass.sol
* @notice Calculates the royalty information for a given sale. @dev Implements the required royaltyInfo function for the ERC2981 standard. @param _salePrice The sale price of the token being sold. @return receiver The address of the royalty recipient. @return royaltyAmount The amount of royalty to be paid./
function royaltyInfo( uint256, uint256 _salePrice ) external view returns (address receiver, uint256 royaltyAmount) { return (project.royaltyAddress, (_salePrice * project.royalty) / 10000); }
17,053,550
[ 1, 10587, 326, 721, 93, 15006, 1779, 364, 279, 864, 272, 5349, 18, 225, 29704, 326, 1931, 721, 93, 15006, 966, 445, 364, 326, 4232, 39, 5540, 11861, 4529, 18, 225, 389, 87, 5349, 5147, 1021, 272, 5349, 6205, 434, 326, 1147, 3832, 272, 1673, 18, 327, 5971, 1021, 1758, 434, 326, 721, 93, 15006, 8027, 18, 327, 721, 93, 15006, 6275, 1021, 3844, 434, 721, 93, 15006, 358, 506, 30591, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 721, 93, 15006, 966, 12, 203, 3639, 2254, 5034, 16, 203, 3639, 2254, 5034, 389, 87, 5349, 5147, 203, 565, 262, 3903, 1476, 1135, 261, 2867, 5971, 16, 2254, 5034, 721, 93, 15006, 6275, 13, 288, 203, 3639, 327, 261, 4406, 18, 3800, 15006, 1887, 16, 261, 67, 87, 5349, 5147, 380, 1984, 18, 3800, 15006, 13, 342, 12619, 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 ]
pragma solidity 0.4.25; // File: contracts/sogur/interfaces/ISGATokenManager.sol /** * @title SGA Token Manager Interface. */ interface ISGATokenManager { /** * @dev Exchange ETH for SGA. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @return The amount of SGA that the sender is entitled to. */ function exchangeEthForSga(address _sender, uint256 _ethAmount) external returns (uint256); /** * @dev Exchange SGA for ETH. * @param _sender The address of the sender. * @param _sgaAmount The amount of SGA received. * @return The amount of ETH that the sender is entitled to. */ function exchangeSgaForEth(address _sender, uint256 _sgaAmount) external returns (uint256); /** * @dev Handle direct SGA transfer. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The amount of SGA to be transferred. */ function uponTransfer(address _sender, address _to, uint256 _value) external; /** * @dev Handle custodian SGA transfer. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGA to be transferred. */ function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external; /** * @dev Handle the operation of ETH deposit into the SGAToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGAToken contract. * @param _amount The deposited ETH amount. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGAToken contract. */ function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external returns (address, uint256); /** * @dev Handle the operation of ETH withdrawal from the SGAToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGAToken contract prior the withdrawal. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGAToken contract. */ function uponWithdraw(address _sender, uint256 _balance) external returns (address, uint256); /** * @dev Upon SGA mint for SGN holders. * @param _value The amount of SGA to mint. */ function uponMintSgaForSgnHolders(uint256 _value) external; /** * @dev Upon SGA transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGA to transfer. */ function uponTransferSgaToSgnHolder(address _to, uint256 _value) external; /** * @dev Upon ETH transfer to an SGA holder. * @param _to The address of the SGA holder. * @param _value The amount of ETH to transfer. * @param _status The operation's completion-status. */ function postTransferEthToSgaHolder(address _to, uint256 _value, bool _status) external; /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGAToken contract. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGAToken contract. */ function getDepositParams() external view returns (address, uint256); /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGAToken contract. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGAToken contract. */ function getWithdrawParams() external view returns (address, uint256); } // File: contracts/sogur/interfaces/IReserveManager.sol /** * @title Reserve Manager Interface. */ interface IReserveManager { /** * @dev Get a deposit-recommendation. * @param _balance The balance of the token-contract. * @return The address of the wallet permitted to deposit ETH into the token-contract. * @return The amount that should be deposited in order for the balance to reach `mid` ETH. */ function getDepositParams(uint256 _balance) external view returns (address, uint256); /** * @dev Get a withdraw-recommendation. * @param _balance The balance of the token-contract. * @return The address of the wallet permitted to withdraw ETH into the token-contract. * @return The amount that should be withdrawn in order for the balance to reach `mid` ETH. */ function getWithdrawParams(uint256 _balance) external view returns (address, uint256); } // File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol /** * @title Contract Address Locator Interface. */ interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } // File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol /** * @title Contract Address Locator Holder. * @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system. * @dev Any contract which inherits from this contract can retrieve the address of any contract in the system. * @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system. * @dev In addition to that, any function in any contract can be restricted to a specific caller. */ contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ; bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager"; bytes32 internal constant _ISGRToken_ = "ISGRToken" ; bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ; bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ; bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ; bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ; IContractAddressLocator private contractAddressLocator; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } /** * @dev Get the contract address locator. * @return The contract address locator. */ function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } /** * @dev Determine whether or not the sender relates to one of the identifiers. * @param _identifiers The identifiers. * @return A boolean indicating if the sender relates to one of the identifiers. */ function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } /** * @dev Verify that the caller is mapped to a given identifier. * @param _identifier The identifier. */ modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/sogur/TransferOnlySGATokenManager.sol /** * Details of usage of licenced software see here: https://www.saga.org/software/readme_v1 */ /** * @title Transfer Only SGA Token Manager. */ contract TransferOnlySGATokenManager is ISGATokenManager, ContractAddressLocatorHolder { string public constant VERSION = "1.0.0"; using SafeMath for uint256; event WithdrawCompleted(address indexed _sender, uint256 _balance, uint256 _amount); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the IReserveManager interface. */ function getReserveManager() public view returns (IReserveManager) { return IReserveManager(getContractAddress(_IReserveManager_)); } /** * @dev Exchange ETH for SGA. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @return The amount of SGA that the sender is entitled to. */ function exchangeEthForSga(address _sender, uint256 _ethAmount) external returns (uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); _sender; _ethAmount; return 0; } /** * @dev Exchange SGA for ETH. * @param _sender The address of the sender. * @param _sgaAmount The amount of SGA received. * @return The amount of ETH that the sender is entitled to. */ function exchangeSgaForEth(address _sender, uint256 _sgaAmount) external returns (uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); _sender; _sgaAmount; return 0; } /** * @dev Handle direct SGA transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The amount of SGA to be transferred. */ function uponTransfer(address _sender, address _to, uint256 _value) external { _sender; _to; _value; } /** * @dev Handle custodian SGA transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGA to be transferred. */ function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external { _sender; _from; _to; _value; } /** * @dev Handle the operation of ETH deposit into the SGAToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGAToken contract. * @param _amount The deposited ETH amount. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGAToken contract. */ function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external returns (address, uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); _sender; _balance; _amount; return (address(0), 0); } /** * @dev Handle the operation of ETH withdrawal from the SGAToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGAToken contract prior the withdrawal. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGAToken contract. */ function uponWithdraw(address _sender, uint256 _balance) external returns (address, uint256) { (address wallet, uint256 amount) = getReserveManager().getWithdrawParams(_balance); require(wallet != address(0), "caller is illegal"); emit WithdrawCompleted(_sender, _balance, amount); return (wallet, _balance); } /** * @dev Upon SGA mint for SGN holders. * @param _value The amount of SGA to mint. */ function uponMintSgaForSgnHolders(uint256 _value) external { require(false, "SGA token has been deprecated. Use SGR token instead"); _value; } /** * @dev Upon SGA transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGA to transfer. */ function uponTransferSgaToSgnHolder(address _to, uint256 _value) external { require(false, "SGA token has been deprecated. Use SGR token instead"); _to; _value; } /** * @dev Upon ETH transfer to an SGA holder. * @param _to The address of the SGA holder. * @param _value The amount of ETH to transfer. * @param _status The operation's completion-status. */ function postTransferEthToSgaHolder(address _to, uint256 _value, bool _status) external { require(false, "SGA token has been deprecated. Use SGR token instead"); _to; _value; _status; } /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGAToken contract. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGAToken contract. */ function getDepositParams() external view returns (address, uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); return (address(0), 0); } /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGAToken contract. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGAToken contract. */ function getWithdrawParams() external view returns (address, uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); return (address(0), 0); } }
* @title Transfer Only SGA Token Manager./
contract TransferOnlySGATokenManager is ISGATokenManager, ContractAddressLocatorHolder { string public constant VERSION = "1.0.0"; using SafeMath for uint256; event WithdrawCompleted(address indexed _sender, uint256 _balance, uint256 _amount); constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} function getReserveManager() public view returns (IReserveManager) { return IReserveManager(getContractAddress(_IReserveManager_)); } function exchangeEthForSga(address _sender, uint256 _ethAmount) external returns (uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); _sender; _ethAmount; return 0; } function exchangeSgaForEth(address _sender, uint256 _sgaAmount) external returns (uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); _sender; _sgaAmount; return 0; } function uponTransfer(address _sender, address _to, uint256 _value) external { _sender; _to; _value; } function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external { _sender; _from; _to; _value; } function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external returns (address, uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); _sender; _balance; _amount; return (address(0), 0); } function uponWithdraw(address _sender, uint256 _balance) external returns (address, uint256) { (address wallet, uint256 amount) = getReserveManager().getWithdrawParams(_balance); require(wallet != address(0), "caller is illegal"); emit WithdrawCompleted(_sender, _balance, amount); return (wallet, _balance); } function uponMintSgaForSgnHolders(uint256 _value) external { require(false, "SGA token has been deprecated. Use SGR token instead"); _value; } function uponTransferSgaToSgnHolder(address _to, uint256 _value) external { require(false, "SGA token has been deprecated. Use SGR token instead"); _to; _value; } function postTransferEthToSgaHolder(address _to, uint256 _value, bool _status) external { require(false, "SGA token has been deprecated. Use SGR token instead"); _to; _value; _status; } function getDepositParams() external view returns (address, uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); return (address(0), 0); } function getWithdrawParams() external view returns (address, uint256) { require(false, "SGA token has been deprecated. Use SGR token instead"); return (address(0), 0); } }
10,632,970
[ 1, 5912, 5098, 348, 25043, 3155, 8558, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12279, 3386, 30820, 789, 969, 1318, 353, 4437, 43, 789, 969, 1318, 16, 13456, 1887, 5786, 6064, 288, 203, 565, 533, 1071, 5381, 8456, 273, 315, 21, 18, 20, 18, 20, 14432, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 3423, 9446, 9556, 12, 2867, 8808, 389, 15330, 16, 2254, 5034, 389, 12296, 16, 2254, 5034, 389, 8949, 1769, 203, 203, 203, 377, 203, 203, 203, 565, 3885, 12, 45, 8924, 1887, 5786, 389, 16351, 1887, 5786, 13, 13456, 1887, 5786, 6064, 24899, 16351, 1887, 5786, 13, 1071, 2618, 203, 565, 445, 31792, 6527, 1318, 1435, 1071, 1476, 1135, 261, 45, 607, 6527, 1318, 13, 288, 203, 3639, 327, 467, 607, 6527, 1318, 12, 588, 8924, 1887, 24899, 45, 607, 6527, 1318, 67, 10019, 203, 565, 289, 203, 377, 203, 565, 445, 7829, 41, 451, 1290, 55, 15833, 12, 2867, 389, 15330, 16, 2254, 5034, 389, 546, 6275, 13, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 5743, 16, 315, 55, 25043, 1147, 711, 2118, 6849, 18, 2672, 348, 6997, 1147, 3560, 8863, 203, 3639, 389, 15330, 31, 203, 3639, 389, 546, 6275, 31, 203, 3639, 327, 374, 31, 203, 565, 289, 203, 203, 565, 445, 7829, 55, 15833, 1290, 41, 451, 12, 2867, 389, 15330, 16, 2254, 5034, 389, 1055, 69, 6275, 13, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 5743, 16, 315, 55, 25043, 1147, 711, 2118, 6849, 18, 2672, 348, 6997, 1147, 3560, 8863, 203, 3639, 389, 15330, 2 ]
pragma solidity ^0.4.18; contract Posse { /// struct para representar o objeto do contrato de posse struct Objeto { uint id; string nome; string descricao; } /// instância do objeto do contrato de posse /// ex: casa, carro, terreno, bicicleta, barco, ... Objeto public objeto; /// dono do objeto address public dono; /// valor do objeto uint public valor; /// indica se o objeto está a venda bool public avenda; /// Evento lançado quando o objeto é liberado para venda event VendaLiberada(uint id, string objeto); /// Evento lançado toda vez que o preço for atualizado event PrecoAtualizado(uint id, string objeto, uint valor); /// Evento lançado toda vez que a posse for vendida para novo dono event Comprada(address novo, uint objetoId, string objeto, uint valor); /// Evento lançado toda vez que a posse for doada event Doada(address novo, uint objetoId, string objeto); /// Construtor do contrato de Posse. /// *ATENÇÃO* Apenas um construtor é permitido. constructor(uint objetoID, string objetoNome, string objetoDescricao) public { /// Criar uma instância de Objeto objeto = Objeto(objetoID, objetoNome, objetoDescricao); /// Atribuir o dono atual do objeto utilizando o atributo sender dono = msg.sender; /// Inicialmente o objeto não está disponível para venda avenda = false; } /// Liberar a venda do objeto function liberar() public { /// Somente o dono do objeto pode liberar a venda require(msg.sender == dono, "Somente o dono pode liberar a venda do objeto"); /// Liberar a venda avenda = true; /// Lançar evento sobre liberação da venda emit VendaLiberada(objeto.id, objeto.nome); } /// Atribuir o preço de venda do objeto function preco(uint _valor) public payable { /// Somente o dono do objeto pode atribuir preço require(msg.sender == dono, "Somente o dono pode modificar o preço do objeto"); /// Atribuir novo valor valor = _valor; /// Lançar evento sobre a ataulização de preço emit PrecoAtualizado(objeto.id, objeto.nome, valor); } /// Comprar a posse do objeto function comprar() public payable { /// O objeto deve estar com a venda liberada require(avenda, "Objeto não está à venda"); /// O valor da compra deve ser idêntico ao valor do objeto require(msg.value == valor, "O valor da compra está errado"); /// Transferir o valor pago ao antigo dono dono.transfer(msg.value); /// Atribuir novo dono dono = msg.sender; /// Objeto volta a bloquear sua venda avenda = false; /// Lançar evento sobre a venda da posse emit Comprada(msg.sender, objeto.id, objeto.nome, msg.value); } /// Doar a posse do objeto function doar(address destino) public { /// Somente o dono pode doar require(msg.sender == dono, "Somente o dono pode doar a posse"); /// Destino não pode ser o dono require(destino != dono, "A doação não deve ser para si mesmo"); /// Atribuir novo dono dono = destino; /// Objeto volta a bloquear sua venda avenda = false; emit Doada(destino, objeto.id, objeto.nome); } }
Evento lançado toda vez que a posse for vendida para novo dono
event Comprada(address novo, uint objetoId, string objeto, uint valor);
12,789,138
[ 1, 1133, 83, 328, 304, 132, 105, 6821, 358, 2414, 331, 6664, 6597, 279, 949, 307, 364, 331, 409, 350, 69, 12602, 1158, 12307, 2727, 83, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 871, 5427, 354, 2414, 12, 2867, 1158, 12307, 16, 2254, 1081, 11453, 548, 16, 533, 1081, 11453, 16, 2254, 23325, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./interfaces/IMasterChef.sol"; import "./interfaces/IVault.sol"; import "./interfaces/ILockManager.sol"; import "./lib/SafeMath.sol"; import "./lib/SafeERC20.sol"; import "./lib/ReentrancyGuard.sol"; /** * @title RewardsManager * @dev Controls rewards distribution for network */ contract RewardsManager is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Current owner of this contract address public owner; /// @notice Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardTokenDebt; // Reward debt for reward token. See explanation below. uint256 sushiRewardDebt; // Reward debt for Sushi rewards. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } /// @notice Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per block. uint256 lastRewardBlock; // Last block number where reward tokens were distributed. uint256 accRewardsPerShare; // Accumulated reward tokens per share, times 1e12. See below. uint32 vestingPercent; // Percentage of rewards that vest (measured in bips: 500,000 bips = 50% of rewards) uint16 vestingPeriod; // Vesting period in days for vesting rewards uint16 vestingCliff; // Vesting cliff in days for vesting rewards uint256 totalStaked; // Total amount of token staked via Rewards Manager bool vpForDeposit; // Do users get voting power for deposits of this token? bool vpForVesting; // Do users get voting power for vesting balances? } /// @notice Reward token IERC20 public rewardToken; /// @notice SUSHI token IERC20 public sushiToken; /// @notice Sushi Master Chef IMasterChef public masterChef; /// @notice Vault for vesting tokens IVault public vault; /// @notice LockManager contract ILockManager public lockManager; /// @notice Reward tokens rewarded per block. uint256 public rewardTokensPerBlock; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Mapping of Sushi tokens to MasterChef pids mapping (address => uint256) public sushiPools; /// @notice Info of each user that stakes tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @notice Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; /// @notice The block number when rewards start. uint256 public startBlock; /// @notice The block number when rewards end. uint256 public endBlock; /// @notice only owner can call function modifier onlyOwner { require(msg.sender == owner, "not owner"); _; } /// @notice Event emitted when a user deposits funds in the rewards manager event Deposit(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds + rewards from the rewards manager event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds from the rewards manager without claiming rewards event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when new pool is added to the rewards manager event PoolAdded(uint256 indexed pid, address indexed token, uint256 allocPoints, uint256 totalAllocPoints, uint256 rewardStartBlock, uint256 sushiPid, bool vpForDeposit, bool vpForVesting); /// @notice Event emitted when pool allocation points are updated event PoolUpdated(uint256 indexed pid, uint256 oldAllocPoints, uint256 newAllocPoints, uint256 newTotalAllocPoints); /// @notice Event emitted when the owner of the rewards manager contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /// @notice Event emitted when the amount of reward tokens per block is updated event ChangedRewardTokensPerBlock(uint256 indexed oldRewardTokensPerBlock, uint256 indexed newRewardTokensPerBlock); /// @notice Event emitted when the rewards start block is set event SetRewardsStartBlock(uint256 indexed startBlock); /// @notice Event emitted when the rewards end block is updated event ChangedRewardsEndBlock(uint256 indexed oldEndBlock, uint256 indexed newEndBlock); /// @notice Event emitted when contract address is changed event ChangedAddress(string indexed addressType, address indexed oldAddress, address indexed newAddress); /** * @notice Create a new Rewards Manager contract * @param _owner owner of contract * @param _lockManager address of LockManager contract * @param _vault address of Vault contract * @param _rewardToken address of token that is being offered as a reward * @param _sushiToken address of SUSHI token * @param _masterChef address of SushiSwap MasterChef contract * @param _startBlock block number when rewards will start * @param _rewardTokensPerBlock initial amount of reward tokens to be distributed per block */ constructor( address _owner, address _lockManager, address _vault, address _rewardToken, address _sushiToken, address _masterChef, uint256 _startBlock, uint256 _rewardTokensPerBlock ) { owner = _owner; emit ChangedOwner(address(0), _owner); lockManager = ILockManager(_lockManager); emit ChangedAddress("LOCK_MANAGER", address(0), _lockManager); vault = IVault(_vault); emit ChangedAddress("VAULT", address(0), _vault); rewardToken = IERC20(_rewardToken); emit ChangedAddress("REWARD_TOKEN", address(0), _rewardToken); sushiToken = IERC20(_sushiToken); emit ChangedAddress("SUSHI_TOKEN", address(0), _sushiToken); masterChef = IMasterChef(_masterChef); emit ChangedAddress("MASTER_CHEF", address(0), _masterChef); startBlock = _startBlock == 0 ? block.number : _startBlock; emit SetRewardsStartBlock(startBlock); rewardTokensPerBlock = _rewardTokensPerBlock; emit ChangedRewardTokensPerBlock(0, _rewardTokensPerBlock); rewardToken.safeIncreaseAllowance(address(vault), uint256(-1)); } /** * @notice View function to see current poolInfo array length * @return pool length */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Add a new reward token to the pool * @dev Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. * @param allocPoint Number of allocation points to allot to this token/pool * @param token The token that will be staked for rewards * @param vestingPercent The percentage of rewards from this pool that will vest * @param vestingPeriod The number of days for the vesting period * @param vestingCliff The number of days for the vesting cliff * @param withUpdate if specified, update all pools before adding new pool * @param sushiPid The pid of the Sushiswap pool in the Masterchef contract (if exists, otherwise provide zero) * @param vpForDeposit If true, users get voting power for deposits * @param vpForVesting If true, users get voting power for vesting balances */ function add( uint256 allocPoint, address token, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool withUpdate, uint256 sushiPid, bool vpForDeposit, bool vpForVesting ) external onlyOwner { if (withUpdate) { massUpdatePools(); } uint256 rewardStartBlock = block.number > startBlock ? block.number : startBlock; if (totalAllocPoint == 0) { _setRewardsEndBlock(); } totalAllocPoint = totalAllocPoint.add(allocPoint); poolInfo.push(PoolInfo({ token: IERC20(token), allocPoint: allocPoint, lastRewardBlock: rewardStartBlock, accRewardsPerShare: 0, vestingPercent: vestingPercent, vestingPeriod: vestingPeriod, vestingCliff: vestingCliff, totalStaked: 0, vpForDeposit: vpForDeposit, vpForVesting: vpForVesting })); if (sushiPid != uint256(0)) { sushiPools[token] = sushiPid; IERC20(token).safeIncreaseAllowance(address(masterChef), uint256(-1)); } IERC20(token).safeIncreaseAllowance(address(vault), uint256(-1)); emit PoolAdded(poolInfo.length - 1, token, allocPoint, totalAllocPoint, rewardStartBlock, sushiPid, vpForDeposit, vpForVesting); } /** * @notice Update the given pool's allocation points * @dev Can only be called by the owner * @param pid The RewardManager pool id * @param allocPoint New number of allocation points for pool * @param withUpdate if specified, update all pools before setting allocation points */ function set( uint256 pid, uint256 allocPoint, bool withUpdate ) external onlyOwner { if (withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[pid].allocPoint).add(allocPoint); emit PoolUpdated(pid, poolInfo[pid].allocPoint, allocPoint, totalAllocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Returns true if rewards are actively being accumulated */ function rewardsActive() public view returns (bool) { return block.number >= startBlock && block.number <= endBlock && totalAllocPoint > 0 ? true : false; } /** * @notice Return reward multiplier over the given from to to block. * @param from From block number * @param to To block number * @return multiplier */ function getMultiplier(uint256 from, uint256 to) public view returns (uint256) { uint256 toBlock = to > endBlock ? endBlock : to; return toBlock > from ? toBlock.sub(from) : 0; } /** * @notice View function to see pending reward tokens on frontend. * @param pid pool id * @param account user account to check * @return pending rewards */ function pendingRewardTokens(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 accRewardsPerShare = pool.accRewardsPerShare; uint256 tokenSupply = pool.totalStaked; if (block.number > pool.lastRewardBlock && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier.mul(rewardTokensPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRewardsPerShare = accRewardsPerShare.add(totalReward.mul(1e12).div(tokenSupply)); } uint256 accumulatedRewards = user.amount.mul(accRewardsPerShare).div(1e12); if (accumulatedRewards < user.rewardTokenDebt) { return 0; } return accumulatedRewards.sub(user.rewardTokenDebt); } /** * @notice View function to see pending SUSHI on frontend. * @param pid pool id * @param account user account to check * @return pending SUSHI rewards */ function pendingSushi(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid == uint256(0)) { return 0; } IMasterChef.PoolInfo memory sushiPool = masterChef.poolInfo(sushiPid); uint256 sushiPerBlock = masterChef.sushiPerBlock(); uint256 totalSushiAllocPoint = masterChef.totalAllocPoint(); uint256 accSushiPerShare = sushiPool.accSushiPerShare; uint256 lpSupply = sushiPool.lpToken.balanceOf(address(masterChef)); if (block.number > sushiPool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = masterChef.getMultiplier(sushiPool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(sushiPool.allocPoint).div(totalSushiAllocPoint); accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); } uint256 accumulatedSushi = user.amount.mul(accSushiPerShare).div(1e12); if (accumulatedSushi < user.sushiRewardDebt) { return 0; } return accumulatedSushi.sub(user.sushiRewardDebt); } /** * @notice Update reward variables for all pools * @dev Be careful of gas spending! */ function massUpdatePools() public { for (uint256 pid = 0; pid < poolInfo.length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date * @param pid pool id */ function updatePool(uint256 pid) public { PoolInfo storage pool = poolInfo[pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 tokenSupply = pool.totalStaked; if (tokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier.mul(rewardTokensPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accRewardsPerShare = pool.accRewardsPerShare.add(totalReward.mul(1e12).div(tokenSupply)); pool.lastRewardBlock = block.number; } /** * @notice Deposit tokens to RewardsManager for rewards allocation. * @param pid pool id * @param amount number of tokens to deposit */ function deposit(uint256 pid, uint256 amount) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _deposit(pid, amount, pool, user); } /** * @notice Deposit tokens to RewardsManager for rewards allocation, using permit for approval * @dev It is up to the frontend developer to ensure the pool token implements permit - otherwise this will fail * @param pid pool id * @param amount number of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit( uint256 pid, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.token.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(pid, amount, pool, user); } /** * @notice Withdraw tokens from RewardsManager, claiming rewards. * @param pid pool id * @param amount number of tokens to withdraw */ function withdraw(uint256 pid, uint256 amount) external nonReentrant { require(amount > 0, "RM::withdraw: amount must be > 0"); PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _withdraw(pid, amount, pool, user); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool id */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.withdraw(sushiPid, user.amount); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), user.amount); } pool.totalStaked = pool.totalStaked.sub(user.amount); pool.token.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewardTokenDebt = 0; user.sushiRewardDebt = 0; } } /** * @notice Set approvals for external addresses to use contract tokens * @dev Can only be called by the owner * @param tokensToApprove the tokens to approve * @param approvalAmounts the token approval amounts * @param spender the address to allow spending of token */ function tokenAllow( address[] memory tokensToApprove, uint256[] memory approvalAmounts, address spender ) external onlyOwner { require(tokensToApprove.length == approvalAmounts.length, "RM::tokenAllow: not same length"); for(uint i = 0; i < tokensToApprove.length; i++) { IERC20 token = IERC20(tokensToApprove[i]); if (token.allowance(address(this), spender) != uint256(-1)) { token.safeApprove(spender, approvalAmounts[i]); } } } /** * @notice Rescue (withdraw) tokens from the smart contract * @dev Can only be called by the owner * @param tokens the tokens to withdraw * @param amounts the amount of each token to withdraw. If zero, withdraws the maximum allowed amount for each token * @param receiver the address that will receive the tokens * @param updateRewardsEndBlock if true, update the rewards end block after performing transfers */ function rescueTokens( address[] calldata tokens, uint256[] calldata amounts, address receiver, bool updateRewardsEndBlock ) external onlyOwner { require(tokens.length == amounts.length, "RM::rescueTokens: not same length"); for (uint i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); uint256 withdrawalAmount; uint256 tokenBalance = token.balanceOf(address(this)); uint256 tokenAllowance = token.allowance(address(this), receiver); if (amounts[i] == 0) { if (tokenBalance > tokenAllowance) { withdrawalAmount = tokenAllowance; } else { withdrawalAmount = tokenBalance; } } else { require(tokenBalance >= amounts[i], "RM::rescueTokens: contract balance too low"); require(tokenAllowance >= amounts[i], "RM::rescueTokens: increase token allowance"); withdrawalAmount = amounts[i]; } token.safeTransferFrom(address(this), receiver, withdrawalAmount); } if (updateRewardsEndBlock) { _setRewardsEndBlock(); } } /** * @notice Set new rewards per block * @dev Can only be called by the owner * @param newRewardTokensPerBlock new amount of reward token to reward each block */ function setRewardsPerBlock(uint256 newRewardTokensPerBlock) external onlyOwner { emit ChangedRewardTokensPerBlock(rewardTokensPerBlock, newRewardTokensPerBlock); rewardTokensPerBlock = newRewardTokensPerBlock; _setRewardsEndBlock(); } /** * @notice Set new reward token address * @param newToken address of new reward token * @param newRewardTokensPerBlock new amount of reward token to reward each block */ function setRewardToken(address newToken, uint256 newRewardTokensPerBlock) external onlyOwner { emit ChangedAddress("REWARD_TOKEN", address(rewardToken), newToken); rewardToken = IERC20(newToken); rewardTokensPerBlock = newRewardTokensPerBlock; _setRewardsEndBlock(); } /** * @notice Set new SUSHI token address * @dev Can only be called by the owner * @param newToken address of new SUSHI token */ function setSushiToken(address newToken) external onlyOwner { emit ChangedAddress("SUSHI_TOKEN", address(sushiToken), newToken); sushiToken = IERC20(newToken); } /** * @notice Set new MasterChef address * @dev Can only be called by the owner * @param newAddress address of new MasterChef */ function setMasterChef(address newAddress) external onlyOwner { emit ChangedAddress("MASTER_CHEF", address(masterChef), newAddress); masterChef = IMasterChef(newAddress); } /** * @notice Set new Vault address * @param newAddress address of new Vault */ function setVault(address newAddress) external onlyOwner { emit ChangedAddress("VAULT", address(vault), newAddress); vault = IVault(newAddress); } /** * @notice Set new LockManager address * @param newAddress address of new LockManager */ function setLockManager(address newAddress) external onlyOwner { emit ChangedAddress("LOCK_MANAGER", address(lockManager), newAddress); lockManager = ILockManager(newAddress); } /** * @notice Add rewards to contract * @dev Can only be called by the owner * @param amount amount of tokens to add */ function addRewardsBalance(uint256 amount) external onlyOwner { rewardToken.safeTransferFrom(msg.sender, address(this), amount); _setRewardsEndBlock(); } /** * @notice Reset rewards end block manually based on new balances */ function resetRewardsEndBlock() external onlyOwner { _setRewardsEndBlock(); } /** * @notice Change owner of vesting contract * @dev Can only be called by the owner * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "RM::changeOwner: not valid address"); emit ChangedOwner(owner, newOwner); owner = newOwner; } /** * @notice Internal implementation of deposit * @param pid pool id * @param amount number of tokens to deposit * @param pool the pool info * @param user the user info */ function _deposit( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; uint256 pendingSushiTokens = 0; if (user.amount > 0) { uint256 pendingRewards = user.amount.mul(pool.accRewardsPerShare).div(1e12).sub(user.rewardTokenDebt); if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); pendingSushiTokens = user.amount.mul(masterChef.poolInfo(sushiPid).accSushiPerShare).div(1e12).sub(user.sushiRewardDebt); } } pool.token.safeTransferFrom(msg.sender, address(this), amount); pool.totalStaked = pool.totalStaked.add(amount); user.amount = user.amount.add(amount); user.rewardTokenDebt = user.amount.mul(pool.accRewardsPerShare).div(1e12); if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); user.sushiRewardDebt = user.amount.mul(masterChef.poolInfo(sushiPid).accSushiPerShare).div(1e12); masterChef.deposit(sushiPid, amount); } if (amount > 0 && pool.vpForDeposit) { lockManager.grantVotingPower(msg.sender, address(pool.token), amount); } if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } emit Deposit(msg.sender, pid, amount); } /** * @notice Internal implementation of withdraw * @param pid pool id * @param amount number of tokens to withdraw * @param pool the pool info * @param user the user info */ function _withdraw( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { require(user.amount >= amount, "RM::_withdraw: amount > user balance"); updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); uint256 pendingSushiTokens = user.amount.mul(masterChef.poolInfo(sushiPid).accSushiPerShare).div(1e12).sub(user.sushiRewardDebt); masterChef.withdraw(sushiPid, amount); user.sushiRewardDebt = user.amount.sub(amount).mul(masterChef.poolInfo(sushiPid).accSushiPerShare).div(1e12); if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } } uint256 pendingRewards = user.amount.mul(pool.accRewardsPerShare).div(1e12).sub(user.rewardTokenDebt); user.amount = user.amount.sub(amount); user.rewardTokenDebt = user.amount.mul(pool.accRewardsPerShare).div(1e12); if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), amount); } pool.totalStaked = pool.totalStaked.sub(amount); pool.token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } /** * @notice Internal function used to distribute rewards, optionally vesting a % * @param account account that is due rewards * @param amount amount of rewards to distribute * @param vestingPercent percent of rewards to vest in bips * @param vestingPeriod number of days over which to vest rewards * @param vestingCliff number of days for vesting cliff * @param vestingVotingPower if true, grant voting power for vesting balance */ function _distributeRewards( address account, uint256 amount, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool vestingVotingPower ) internal { uint256 rewardAmount = amount > rewardToken.balanceOf(address(this)) ? rewardToken.balanceOf(address(this)) : amount; uint256 vestingRewards = rewardAmount.mul(vestingPercent).div(1000000); vault.lockTokens(address(rewardToken), address(this), account, 0, vestingRewards, vestingPeriod, vestingCliff, vestingVotingPower); _safeRewardsTransfer(msg.sender, rewardAmount.sub(vestingRewards)); } /** * @notice Safe reward transfer function, just in case if rounding error causes pool to not have enough reward token. * @param to account that is receiving rewards * @param amount amount of rewards to send */ function _safeRewardsTransfer(address to, uint256 amount) internal { uint256 rewardTokenBalance = rewardToken.balanceOf(address(this)); if (amount > rewardTokenBalance) { rewardToken.safeTransfer(to, rewardTokenBalance); } else { rewardToken.safeTransfer(to, amount); } } /** * @notice Safe SUSHI transfer function, just in case if rounding error causes pool to not have enough SUSHI. * @param to account that is receiving SUSHI * @param amount amount of SUSHI to send */ function _safeSushiTransfer(address to, uint256 amount) internal { uint256 sushiBalance = sushiToken.balanceOf(address(this)); if (amount > sushiBalance) { sushiToken.safeTransfer(to, sushiBalance); } else { sushiToken.safeTransfer(to, amount); } } /** * @notice Internal function that updates rewards end block based on tokens per block and the token balance of the contract */ function _setRewardsEndBlock() internal { if(rewardTokensPerBlock > 0) { uint256 rewardFromBlock = block.number >= startBlock ? block.number : startBlock; uint256 newEndBlock = rewardFromBlock.add(rewardToken.balanceOf(address(this)).div(rewardTokensPerBlock)); if(newEndBlock > rewardFromBlock && newEndBlock != endBlock) { emit ChangedRewardsEndBlock(endBlock, newEndBlock); endBlock = newEndBlock; } } } }
@notice Info of each pool.
struct PoolInfo { }
1,768,148
[ 1, 966, 434, 1517, 2845, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 8828, 966, 288, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 377, 203, 203, 377, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./YFBitcoin.sol"; import "./UniswapV2Pair.sol"; import "./IUniSwapV2Factory.sol"; // MasterChef is the master of YFBTC. He can make YFBTC and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once YFBTC is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. // live net token0 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 // livenet factory 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f // kovan token0 0xd0a1e359811322d97991e03f863a0c30c2cf029c // kovan token1 0x551733cf73465a007BD441d0A1BBE1b30355B28A // kovan factory 0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f contract YFBTCMaster is Ownable { using SafeMath for *; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; uint256 rewardDebt; } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. //EDIT - Per Pool last block reward is removed uint256 accYfbtcPerShare; // Accumulated YFBTC per share, times 1e12. See below. uint256 totalSupply; } struct RewardInfo{ uint256 startBlock; uint256 endBlock; uint256 rewardFrom; uint256 rewardTo; uint256 rewardPerBlock; } uint256 public lastPrice = 0; uint public constant PERIOD = 24 hours; uint constant YFBTC_MULTIPLIER = 5; // holds the WETH address address public token0; // holds the YFBTC address address public token1; // hold factory address that will be used to fetch pair address address public factory; // block time of last update uint32 public blockTimestampLast; // The YFBTC TOKEN! YFBitcoin public yfbtc; // Info of each pool. PoolInfo[] public poolInfo; //info of reward pools RewardInfo[] public rewardInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // The block number when YFBTC mining starts. uint256 public startedBlock; // hold the block number of last rewarded block uint256 lastRewardBlock = 0; //EDIT adding uni-v2 address as variable address univ2; event SetDevAddress(address indexed _devAddress); event SetTransferFee(uint256 _fee); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawExceptional(address indexed user, uint256 amount); constructor( YFBitcoin _yfbtc, address _univ2, address _factory, address _token0, address _token1, uint256 _startedBlock ) public { yfbtc = _yfbtc; univ2 = _univ2; factory = _factory; token0 = _token0; token1 = _token1; startedBlock = _startedBlock; address pairAddress = IUniswapV2Factory(factory).getPair(token0, token1); (uint112 reserve0, uint112 reserve1, uint32 blockTime) = UniswapV2Pair(pairAddress).getReserves(); // gas savings blockTimestampLast = blockTime; lastPrice = reserve1.mul(1e18).div(reserve0); require(reserve0 != 0 && reserve1 != 0, 'ORACLE: NO_RESERVES'); // ensure that there's liquidity in the pair addRewardSet(); } function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } function setDevAddress(address _devAddress) external onlyOwner { yfbtc.setDevAddress(_devAddress); emit SetDevAddress(_devAddress); } function setTransferFee(uint256 _fee) external onlyOwner { require(_fee > 0 && _fee < 1000, "YFBTC: fee should be between 0 and 10"); yfbtc.setTransferFee(_fee); emit SetTransferFee(_fee); } function mint(address _to, uint256 _amount) public onlyOwner { yfbtc.mint(_to, _amount); } function burn(address _sender, uint256 _amount) public onlyOwner { yfbtc.burn(_sender, _amount); } function update() public returns(bool) { uint32 blockTimestamp = currentBlockTimestamp(); address pairAddress = IUniswapV2Factory(factory).getPair(token0, token1); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update if(timeElapsed >= PERIOD){ (uint112 _reserve0, uint112 _reserve1, ) = UniswapV2Pair(pairAddress).getReserves(); // gas savings uint256 curretPrice = _reserve1.mul(1e18).div(_reserve0); if ( curretPrice < lastPrice){ uint256 change = lastPrice.sub(curretPrice).mul(100).div(lastPrice); lastPrice = curretPrice; blockTimestampLast = blockTimestamp; if ( change >= 5 ) return false; }else{ lastPrice = curretPrice; } } return true; } function updateOwnerShip(address newOwner) public onlyOwner{ yfbtc.transferOwnership(newOwner); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(IERC20 _lpToken) external onlyOwner { //EDIT commenting lastRewardBlock per pool (it is now common for all pools) //uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; require (address(_lpToken) != address(0), "MC: _lpToken should not be address zero"); for(uint i=0; i < poolInfo.length; i++){ require (address(poolInfo[i].lpToken)!= address(_lpToken), "MC: DO NOT add the same LP token more than once"); } poolInfo.push(PoolInfo({ lpToken: _lpToken, accYfbtcPerShare: 0, totalSupply: 0 })); } function addRewardSet() internal returns (uint){ rewardInfo.push( RewardInfo({ startBlock : startedBlock, endBlock: startedBlock.add(172800), rewardFrom: 1900 * 10 ** 18, rewardTo: 3150 * 10 ** 18, rewardPerBlock: 6837344620000000 })); rewardInfo.push( RewardInfo({ startBlock : startedBlock.add(172800), endBlock: startedBlock.add(1036800), rewardFrom: 3150 * 10 ** 18, rewardTo: 8960 * 10 ** 18, rewardPerBlock: 8641973370000000 })); rewardInfo.push( RewardInfo({ startBlock : startedBlock.add(1036800), endBlock: startedBlock.add(2073600), rewardFrom: 8960 * 10 ** 18, rewardTo: 16590 * 10 ** 18, rewardPerBlock: 4320987650000000 })); rewardInfo.push( RewardInfo({ startBlock : startedBlock.add(2073600), endBlock: startedBlock.add(3110400), rewardFrom: 16590 * 10 ** 18, rewardTo: 18830 * 10 ** 18, rewardPerBlock: 2160493820000000 })); rewardInfo.push( RewardInfo({ startBlock : startedBlock.add(3110400), endBlock: startedBlock.add(4147200), rewardFrom: 18830 * 10 ** 18, rewardTo: 19950 * 10 ** 18, rewardPerBlock: 1080246910000000 })); rewardInfo.push( RewardInfo({ startBlock : startedBlock.add(4147200), endBlock: startedBlock.add(5184000), rewardFrom: 19950 * 10 ** 18, rewardTo: 20510 * 10 ** 18, rewardPerBlock: 540123450000000 })); rewardInfo.push( RewardInfo({ startBlock : startedBlock.add(5184000), endBlock: startedBlock.add(6220800), rewardFrom: 20510 * 10 ** 18, rewardTo: 20790 * 10 ** 18, rewardPerBlock: 270061720000000 })); rewardInfo.push( RewardInfo({ startBlock : startedBlock.add(6220800), endBlock: startedBlock.add(7257600), rewardFrom: 20790 * 10 ** 18, rewardTo: 20930 * 10 ** 18, rewardPerBlock: 135030860000000 })); rewardInfo.push( RewardInfo({ startBlock : startedBlock.add(7257600), endBlock: startedBlock.add(8294400), rewardFrom: 20930 * 10 ** 18, rewardTo: 21000 * 10 ** 18, rewardPerBlock: 67515430000000 })); return 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 difference = _to.sub(_from); if ( difference <= 0 || _from < startedBlock) return 0; // test by adding supply // test complete minting // add update ownership function uint256 totalReward = 0; uint256 supply = yfbtc.totalSupply(); uint256 rewardSetlength = rewardInfo.length; if (_to >= rewardInfo[rewardInfo.length.sub(1)].endBlock && supply < rewardInfo[rewardInfo.length.sub(1)].rewardTo){ totalReward = _to.sub(_from).mul(rewardInfo[3].rewardPerBlock); }else{ for (uint256 rid = 0; rid < rewardSetlength; ++rid) { if ( supply >= rewardInfo[rid].rewardFrom){ if(_to <= rewardInfo[rid].endBlock){ totalReward = totalReward.add(((_to.sub(_from)).mul(rewardInfo[rid].rewardPerBlock))); break; }else{ totalReward = totalReward.add(((rewardInfo[rid].endBlock.sub(_from)).mul(rewardInfo[rid].rewardPerBlock))); supply = rewardInfo[rid].rewardTo; _from = rewardInfo[rid].endBlock; } } } } return totalReward; } // View function to see pending YFBTC on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo memory pool = poolInfo[_pid]; require (address(pool.lpToken) != address(0), "MC: _pid is incorrect"); UserInfo memory user = userInfo[_pid][_user]; uint256 accYfbtcPerShare = pool.accYfbtcPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > lastRewardBlock && lpSupply != 0) { uint256 yfbtcReward = getMultiplier(lastRewardBlock, block.number); uint totalPoolsEligible = getEligiblePools(); uint distribution = YFBTC_MULTIPLIER + totalPoolsEligible - 1; uint256 rewardPerPool = yfbtcReward.div(distribution); if (address(pool.lpToken) == univ2){ accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(YFBTC_MULTIPLIER).mul(1e12).div(lpSupply)); }else{ accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(1e12).div(lpSupply)); } } return user.amount.mul(accYfbtcPerShare).div(1e12).sub(user.rewardDebt); } // View function to see rewardPer YFBTC block on frontend. function rewardPerBlock(uint256 _pid) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; require (address(pool.lpToken) != address(0), "MC: _pid is incorrect"); uint256 accYfbtcPerShare = pool.accYfbtcPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > lastRewardBlock && lpSupply != 0) { uint256 yfbtcReward = getMultiplier(lastRewardBlock, block.number); uint totalPoolsEligible = getEligiblePools(); uint distribution = YFBTC_MULTIPLIER + totalPoolsEligible - 1; uint256 rewardPerPool = yfbtcReward.div(distribution); if (address(pool.lpToken) == univ2){ accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(YFBTC_MULTIPLIER).mul(1e12).div(lpSupply)); }else{ accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(1e12).div(lpSupply)); } } return accYfbtcPerShare; } function getEligiblePools() internal view returns(uint){ uint totalPoolsEligible = 0; uint256 length = poolInfo.length; // Reward will only be assign to pools when they the staked balance is > 0 for (uint256 pid = 0; pid < length; ++pid) { if( poolInfo[pid].totalSupply > 0){ totalPoolsEligible = totalPoolsEligible.add(1); } } return totalPoolsEligible; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require (address(pool.lpToken) != address(0), "MC: _pid is incorrect"); if (block.number <= lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { lastRewardBlock = block.number; return; } bool doMint = update(); if ( doMint ){ uint256 yfbtcReward = getMultiplier(lastRewardBlock, block.number); if ( yfbtcReward <= 0 ) return; uint totalPoolsEligible = getEligiblePools(); if ( totalPoolsEligible == 0 ) return; yfbtc.mint(address(this), yfbtcReward); uint distribution = YFBTC_MULTIPLIER + totalPoolsEligible - 1; uint256 rewardPerPool = yfbtcReward.div(distribution); if (address(pool.lpToken) == univ2){ pool.accYfbtcPerShare = pool.accYfbtcPerShare.add(rewardPerPool.mul(YFBTC_MULTIPLIER).mul(1e12).div(lpSupply)); }else{ pool.accYfbtcPerShare = pool.accYfbtcPerShare.add(rewardPerPool.mul(1e12).div(lpSupply)); } lastRewardBlock = block.number; // TODO update stage } } // Deposit LP tokens to MasterChef for YFBTC allocation. function deposit(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; require (address(pool.lpToken) != address(0), "MC: _pid is incorrect"); UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYfbtcPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeYfbtcTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); pool.totalSupply = pool.totalSupply.add(_amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accYfbtcPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; require (address(pool.lpToken) != address(0), "MC: _pid is incorrect"); UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accYfbtcPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeYfbtcTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); pool.totalSupply = pool.totalSupply.sub(_amount); } user.rewardDebt = user.amount.mul(pool.accYfbtcPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // let user exist in case of emergency function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require (address(pool.lpToken) == address(0), "MC: _pid is incorrect"); UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); pool.totalSupply = pool.totalSupply.sub(amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe yfbtcReward transfer function, just in case if rounding error causes pool to not have enough YFBTC. function safeYfbtcTransfer(address _to, uint256 _amount) internal { uint256 yfbtcBal = yfbtc.balanceOf(address(this)); if (_amount > yfbtcBal) { yfbtc.transfer(_to, yfbtcBal); emit EmergencyWithdrawExceptional(_to, _amount); } else { yfbtc.transfer(_to, _amount); } } }
View function to see rewardPer YFBTC block on frontend.
function rewardPerBlock(uint256 _pid) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; require (address(pool.lpToken) != address(0), "MC: _pid is incorrect"); uint256 accYfbtcPerShare = pool.accYfbtcPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > lastRewardBlock && lpSupply != 0) { uint256 yfbtcReward = getMultiplier(lastRewardBlock, block.number); uint totalPoolsEligible = getEligiblePools(); uint distribution = YFBTC_MULTIPLIER + totalPoolsEligible - 1; uint256 rewardPerPool = yfbtcReward.div(distribution); if (address(pool.lpToken) == univ2){ accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(YFBTC_MULTIPLIER).mul(1e12).div(lpSupply)); accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(1e12).div(lpSupply)); } } return accYfbtcPerShare; }
5,438,545
[ 1, 1767, 445, 358, 2621, 19890, 2173, 1624, 22201, 15988, 1203, 225, 603, 15442, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 19890, 2173, 1768, 12, 11890, 5034, 389, 6610, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 2583, 261, 2867, 12, 6011, 18, 9953, 1345, 13, 480, 1758, 12, 20, 3631, 315, 20022, 30, 389, 6610, 353, 11332, 8863, 203, 3639, 2254, 5034, 4078, 61, 19192, 5111, 2173, 9535, 273, 2845, 18, 8981, 61, 19192, 5111, 2173, 9535, 31, 203, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 2629, 18, 2696, 405, 1142, 17631, 1060, 1768, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 203, 5411, 2254, 5034, 677, 19192, 5111, 17631, 1060, 273, 31863, 5742, 12, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 5411, 2254, 2078, 16639, 4958, 16057, 273, 4774, 80, 16057, 16639, 5621, 203, 203, 5411, 2254, 7006, 273, 1624, 22201, 15988, 67, 24683, 2053, 654, 397, 2078, 16639, 4958, 16057, 300, 404, 31, 203, 5411, 2254, 5034, 19890, 2173, 2864, 273, 677, 19192, 5111, 17631, 1060, 18, 2892, 12, 16279, 1769, 203, 540, 203, 5411, 309, 261, 2867, 12, 6011, 18, 9953, 1345, 13, 422, 28772, 22, 15329, 203, 2868, 4078, 61, 19192, 5111, 2173, 9535, 273, 4078, 61, 19192, 5111, 2173, 9535, 18, 1289, 12, 266, 2913, 2173, 2864, 18, 16411, 12, 61, 22201, 15988, 67, 24683, 2053, 654, 2934, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * * @author Rao Nagos * KaveuERC721 - Kaveu - KVU * Repository URL : https://github.com/Kaveu/kaveu-core * Website URL : https://kaveu.io * * Kaveu is a project based on NFTs which are used as a key to be allowed to use an arbitration bot (IA) on CEXs/DEXs. * Each NFT has a basic `claws` to arbitrate 2 tokens on the C/DEXs. The same `claws` can be borrowed from third parties if the owners allows it. */ contract KaveuERC721 is ERC721, ERC721Holder, Ownable, ReentrancyGuard { // Identify who the caller is enum AssignState { DEFAULT, BY_OWNER, BY_BORROWER } /** * @param deadline The loan period * @param totalAmount The price of the loan * @param totalBorrow The total number of claw that were borrowed by {borrower} * @param caller The one who called the function and also who will receive the refunds * @param borrower The dedicated account * @param assignState See above */ struct BorrowData { uint256 deadline; uint256 totalAmount; uint256 totalBorrow; address caller; address borrower; AssignState assignState; } /** * @param pricePerDay The price of the loan per day * @param totalBorrow The total number of claws that were borrowed by all borrowers * @param totalAssign The total number of claws that were assigned by the owner * @param totalClaw The total number of claws * @param priceClaw The price of the claw */ struct Claw { uint256 pricePerDay; uint256 totalBorrow; uint256 totalAssign; uint256 totalClaw; uint256 priceClaw; } // Simple events event ClawLoaning(uint256 indexed tokenId, uint256 indexed pricePerDay); event ClawBorrowed(uint256 indexed tokenId, address indexed borrower, uint256 indexed deadline); // The maximum supply that can be mined uint256 public constant MAX_SUPPLY = 15; // $ echo "(7 * 2) + 1" | bc // The safe address to withdraw or to sell tokens address public safeAddress; // The base uri that stores the json file string private _baseUri; // Map {Claw} by the id of token mapping(uint256 => Claw) private _claws; // Map {BorrowData} by borrower address mapping(uint256 => mapping(address => BorrowData)) private _borrowers; address[] private _borrowerArray; /** * @dev Throws if the token does not exist. * See {ERC721-_exists}. * * @param tokenId The id of the token */ modifier existToken(uint256 tokenId) { require(_exists(tokenId), "KaveuERC721: the token does not exist"); _; } /** * @dev Throws if called by any account other than the owner. * See {IERC721-ownerOf}. * * @param tokenId The id of the token */ modifier onlyOwnerOf(uint256 tokenId) { require(ownerOf(tokenId) == msg.sender, "KaveuERC721: you are not the owner"); _; } /** * @dev Set the {Claw.priceClaw} to 12,7 ether (starting price) and {Claw.totalClaw} to 2. * Set the {_baseUri} and the {safeAddress}. * * @param safeAddress_ The safe address of deployer * @param uri_ The CID of ipfs url */ constructor(address safeAddress_, string memory uri_) ERC721("Kaveu", "KVU") { safeAddress = safeAddress_; _baseUri = uri_; for (uint256 id = 1; id <= MAX_SUPPLY; id++) { _claws[id].totalClaw = id > 1 ? 2 : 7; // The one should never be sold _claws[id].priceClaw = 12.7 gwei; // 12.7 ether (matic): 18$ at april 17th 2022 _mint(safeAddress, id); } } /** * @return MAX_SUPPLY The maximum supply */ function totalSupply() external pure returns (uint256) { return MAX_SUPPLY; } /** * @dev See {IERC721Metadata-tokenURI}. * * @param _tokenId The id of the token * @return uri The uri token of the {_tokenId} */ function tokenURI(uint256 _tokenId) public view virtual override existToken(_tokenId) returns (string memory) { return string(abi.encodePacked(_baseUri, Strings.toString(_tokenId), ".json")); } /** * @dev Call once a time all the tokens uri. * * @return uris All tokens uri */ function getTokenURIs() external view virtual returns (string[] memory) { string[] memory uris = new string[](MAX_SUPPLY); for (uint256 tokenId = 1; tokenId <= MAX_SUPPLY; tokenId++) uris[tokenId - 1] = tokenURI(tokenId); return uris; } /** * @return balance The balance of the contract */ function balance() external view returns (uint256) { return address(this).balance; } /** * @dev Allows the deployer to send the contract balance to the {safeAddress}. */ function withdraw() external virtual onlyOwner nonReentrant { (bool success, ) = payable(safeAddress).call{value: address(this).balance}(""); require(success, "Address: unable to send value"); } /** * @dev Allow the deployer to set the {safeAddress} by the {_safeAddress}. * * @param _safeAddress The new safe address */ function setSafeAddress(address _safeAddress) external virtual onlyOwner { safeAddress = _safeAddress; } /** * @dev Allows the deployer to set the {_baseUri} by the {_newUri}. * * @param _newUri The new {_baseUri} */ function setUri(string memory _newUri) external virtual onlyOwner { _baseUri = _newUri; } /** * @dev Allows the owner to increase claws of the {_tokenId} by {_incBy} by sending a minimum amount. * The {Claw.priceClaw} is updated according to the formula: {Claw.totalClaw} * 5,7614 ether. * !! Decreases claws does not exist. * * Throws if the {_tokenId} is less than 1 and if the {value} is less than the required amount. * * @param _tokenId The id of the token * @param _incBy The number of claws to add */ function increaseClaws(uint256 _tokenId, uint256 _incBy) external payable virtual onlyOwnerOf(_tokenId) nonReentrant { require(msg.value >= _incBy * _claws[_tokenId].priceClaw && _tokenId > 1, "KaveuERC721: unable to increase the token"); _claws[_tokenId].totalClaw += _incBy; _claws[_tokenId].priceClaw = _claws[_tokenId].totalClaw * 5.7614 gwei; // 5,7614 = (12,7 / 7,21) + (7 - 2 - 1) } /** * @dev Allows the deployer to increase by 4, all owner claws except the id one. * This function affects the {increaseClaws} function. */ function airdrop() external virtual onlyOwner { for (uint256 id = 2; id <= MAX_SUPPLY; id++) _claws[id].totalClaw += (7 - 2 - 1); } ///////////////////////////////////////////////////////////////////// /////////////////////////// LOAN //////////////////////////////////// ///////////////////////////////////////////////////////////////////// /** * @param _tokenId The id of the token * @return claw The {Claw} of the {_tokenId} */ function clawsOf(uint256 _tokenId) external view existToken(_tokenId) returns (Claw memory) { return _claws[_tokenId]; } /** * @dev The IA uses this function to check if a borrower is allowed to use him. * * @param _tokenId The id of the token * @return borrowDatas An array of {BorrowData} of the {_tokenId} */ function borrowOf(uint256 _tokenId) external view existToken(_tokenId) returns (BorrowData[] memory) { uint256 ln = _borrowerArray.length; if (ln == 0) return new BorrowData[](ln); uint256 cbsIndex; uint256 i; BorrowData[] memory cbs = new BorrowData[](ln); for (i = 0; i < ln; i++) { BorrowData memory cb = _borrowers[_tokenId][_borrowerArray[i]]; if (cb.assignState != AssignState.DEFAULT) { cbs[cbsIndex] = cb; cbsIndex++; } } // use assembly to decrease the size for null data (by null, it means AssignState.DEFAULT) // the first 'if' above makes the following code safe for (i = cbsIndex; i < ln; i++) assembly { mstore(cbs, sub(mload(cbs), 1)) } return cbs; } /** * ~ON-CHAIN~ * @dev The IA uses this function to check if a borrower is allowed to use him. * Check to see if the borrower exists and if the deadline of the loan has been reached. * * @param _borrower The borrower to find * @return isBorrower */ function isBorrower(address _borrower) external view returns (bool) { bool find = false; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowerArray[i] == _borrower) { find = true; break; } if (!find) return find; for (uint256 id = 1; id <= MAX_SUPPLY; id++) if (_borrowers[id][_borrower].assignState != AssignState.DEFAULT && _borrowers[id][_borrower].deadline > block.timestamp) return true; return false; } /** * ~ON-CHAIN~ * @param _borrower The borrower who borrows * @return totalBorrowsOf The number of claws the {_borrower} borrows. */ function totalBorrowsOf(address _borrower) external view returns (uint256) { uint256 total = 0; for (uint256 id = 1; id <= MAX_SUPPLY; id++) total += _borrowers[id][_borrower].totalBorrow; return total; } /** * @dev Removes {index} borrower from the array by calling the pop() function. * In fine : this will decrease the array length by 1. * * @param index The cute index */ function removeBorrower(uint256 index) private { _borrowerArray[index] = _borrowerArray[_borrowerArray.length - 1]; _borrowerArray.pop(); } /** * @dev Manually assigns a {_borrower} once to the token {_tokenId} for 721 years and without paying the loan fee. * The {_borrower} is a dedicated account. Considere checking the website for more info. * !! The {Claw.assignState} is set by the owner. * * Throws if the {Claw.totalAssign} of the {_tokenId} is greater than the {Claw.totalClaw}. * And throws if the {BorrowData.assignState} of the {_borrower} is not an {AssignState.DEFAULT}. * * This emits the {ClawBorrowed} event. * * @param _tokenId The id of the token * @param _forClaws The number of claws the owner wants to borrow * @param _borrower The address of the borrower */ function assign( uint256 _tokenId, uint256 _forClaws, address _borrower ) external virtual onlyOwnerOf(_tokenId) { BorrowData memory cb = _borrowers[_tokenId][_borrower]; Claw memory cl = _claws[_tokenId]; cl.totalAssign += _forClaws; require(cl.totalAssign <= cl.totalClaw && cb.assignState == AssignState.DEFAULT, "KaveuERC721: cannot assign the borrower"); cb.deadline = block.timestamp + (31536000 * 721); // 31536000 YEAR_IN_SECONDS cb.assignState = AssignState.BY_OWNER; cb.totalBorrow = _forClaws; cb.caller = msg.sender; cb.borrower = _borrower; _claws[_tokenId] = cl; _borrowers[_tokenId][_borrower] = cb; _borrowerArray.push(_borrower); emit ClawBorrowed(_tokenId, _borrower, cb.deadline); } /** * @dev Deassigns a {_borrower} who has already been manually assigned from the assign() function. * If {Claw.totalAssign} is 0, then it will clear the data. * * Throws if the {BorrowData.assignState} was not assigned by the owner. * * @param _tokenId The id of the token * @param _forClaws The number of claws the owner wants to borrow * @param _borrower The address of the borrower */ function deassign( uint256 _tokenId, uint256 _forClaws, address _borrower ) external virtual onlyOwnerOf(_tokenId) { Claw storage cl = _claws[_tokenId]; cl.totalAssign -= _forClaws; // reverting on overflow require(_borrowers[_tokenId][_borrower].assignState == AssignState.BY_OWNER, "KaveuERC721: cannot deassign the borrower"); // clear() if (cl.totalAssign == 0) for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowerArray[i] == _borrower) { delete _borrowers[_tokenId][_borrower]; removeBorrower(i); break; } } /** * @dev Create a loan for the {_tokenId} by setting a price {_pricePerDay}. * To stop the loan, set the {_pricePerDay} to 0 but this does not stop the current rentals. * * This emits {ClawLoaning} event. * * @param _tokenId The id of the token * @param _pricePerDay The price the caller wants to loan claws */ function loan(uint256 _tokenId, uint256 _pricePerDay) external virtual onlyOwnerOf(_tokenId) { _claws[_tokenId].pricePerDay = _pricePerDay; emit ClawLoaning(_tokenId, _pricePerDay); } /** * @dev Create a borrow for a {_tokenId} by sending a minimum amount. Borrow until {_forDays} + {block.timestamp}. * If the owner of the {_tokenId} wants to sell it, he will have to pay back {BorrowData.totalAmount} the {BorrowData.caller} completely first, not for the days remaining. * !! The caller cannot cancel the loan until the deadline is reached. * * See {loan} to stop it. * See {_beforeTokenTransfer} to check the refunds. * * Throws if {Claw.pricePerDay} of the {_tokenId} or {_forDays} is 0. * Throws if the {Claw.totalBorrow} is greater than the {Claw.totalClaw}. * Throws if {BorrowData.assignState} is not an {AssignState.DEFAULT}. * And throws if the {value} is less than the required amount. * * This emits the {ClawBorrowed} event. * * @param _tokenId The id of the token * @param _forClaws The number of claws the caller wants to borrow * @param _forDays The number of days the caller wants to borrow * @param _borrower The address of the borrower */ function borrow( uint256 _tokenId, uint256 _forClaws, uint256 _forDays, address _borrower ) external payable virtual existToken(_tokenId) nonReentrant { Claw memory cl = _claws[_tokenId]; cl.totalBorrow += _forClaws; BorrowData memory cb = _borrowers[_tokenId][_borrower]; require(cl.pricePerDay > 0 && _forClaws > 0 && _forDays > 0 && cl.totalBorrow <= cl.totalClaw && cb.assignState == AssignState.DEFAULT, "KaveuERC721: cannot borrow"); cb.deadline = block.timestamp + (_forDays * 86400); // 86400 DAY_IN_SECONDS cb.totalAmount = _forClaws * _forDays * cl.pricePerDay; cb.totalBorrow = _forClaws; cb.caller = msg.sender; // refund the caller cb.borrower = _borrower; cb.assignState = AssignState.BY_BORROWER; _claws[_tokenId] = cl; _borrowers[_tokenId][_borrower] = cb; _borrowerArray.push(_borrower); // pays loan fee require(msg.value >= cb.totalAmount, "KaveuERC721: not enought token"); (bool success, ) = payable(ownerOf(_tokenId)).call{value: msg.value}(""); require(success, "Address: unable to send value"); emit ClawBorrowed(_tokenId, _borrower, cb.deadline); } /** * @dev Clears the data if the {BorrowData.deadline} has been reached. Anyone can call this function. */ function clear() external virtual { uint256 ln = _borrowerArray.length; uint256[] memory array = new uint256[](ln); uint256 counter = 0; uint256 i; for (uint256 id = 1; id <= MAX_SUPPLY; id++) for (i = 0; i < _borrowerArray.length; i++) { BorrowData memory cb = _borrowers[id][_borrowerArray[i]]; if (cb.assignState != AssignState.DEFAULT && cb.deadline < block.timestamp) { Claw storage cl = _claws[id]; if (cb.assignState == AssignState.BY_OWNER) cl.totalAssign -= cb.totalBorrow; else cl.totalBorrow -= cb.totalBorrow; array[counter] = i; counter++; delete _borrowers[id][_borrowerArray[i]]; } } for (i = 0; i < counter; i++) removeBorrower(array[i]); } /** * @param _tokenId The id of the token * @return amountIn The required amount to refund the owner of the {_tokenId} */ function getAmountInToRefund(uint256 _tokenId) public view returns (uint256) { uint256 amountIn = 0; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowers[_tokenId][_borrowerArray[i]].assignState == AssignState.BY_BORROWER) amountIn += _borrowers[_tokenId][_borrowerArray[i]].totalAmount; return amountIn; } /** * @dev Check that there are no refunds to be made prior to the transfer. If there is, a refund is required to the `BorrowData.caller` for `BorrowData.totalAmount`, not for the days remaining. * !! It is recommended to call the {clear} function first. * * Throws if the {value} is less than the required amount. * */ function refundBorrowers(uint256 _tokenId) external payable virtual nonReentrant { require(msg.value >= getAmountInToRefund(_tokenId), "KaveuERC721: not enought token"); for (uint256 i = 0; i < _borrowerArray.length; i++) { BorrowData memory cb = _borrowers[_tokenId][_borrowerArray[i]]; if (cb.assignState == AssignState.BY_BORROWER) { // refunds the caller (bool success, ) = payable(cb.caller).call{value: cb.totalAmount}(""); require(success, "Address: unable to send value"); // to clear() cb.deadline = block.timestamp - 10; _borrowers[_tokenId][_borrowerArray[i]] = cb; } } } /** * See {ERC721-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); // from _mint() or to _burn() if (from == address(0) || to == address(0)) return; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowers[tokenId][_borrowerArray[i]].assignState == AssignState.BY_BORROWER && _borrowers[tokenId][_borrowerArray[i]].deadline > block.timestamp) revert("KaveuERC721: refund borrowers first"); } }
* @dev Allow the deployer to set the {safeAddress} by the {_safeAddress}. @param _safeAddress The new safe address/
function setSafeAddress(address _safeAddress) external virtual onlyOwner { safeAddress = _safeAddress; }
15,811,856
[ 1, 7009, 326, 7286, 264, 358, 444, 326, 288, 4626, 1887, 97, 635, 326, 288, 67, 4626, 1887, 5496, 225, 389, 4626, 1887, 1021, 394, 4183, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 9890, 1887, 12, 2867, 389, 4626, 1887, 13, 3903, 5024, 1338, 5541, 288, 203, 3639, 4183, 1887, 273, 389, 4626, 1887, 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 ]
pragma solidity ^0.4.24; import "./IERC20.sol"; import "../math/SafeMath.sol"; /** * @title Standard ERC20 token. * @dev Implementation of the basic standard token. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @return Total number of tokens in existence. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the given address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Transfers tokens for the specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev 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 The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Approves the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Checks 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 An 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 Increases the amount of tokens that an owner allowed to a spender. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decreases the amount of tokens that an owner allowed to a spender. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfers tokens for a specified address. * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Mints an amount of the token and assigns it to an account. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } }
* @dev Decreases the amount of tokens that an owner allowed to a spender. @param spender The address which will spend the funds. @param subtractedValue The amount of tokens to decrease the allowance by./
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; }
7,229,012
[ 1, 23326, 3304, 326, 3844, 434, 2430, 716, 392, 3410, 2935, 358, 279, 17571, 264, 18, 225, 17571, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 10418, 329, 620, 1021, 3844, 434, 2430, 358, 20467, 326, 1699, 1359, 635, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 87, 1302, 264, 480, 1758, 12, 20, 10019, 203, 203, 3639, 389, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 261, 67, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 8009, 1717, 12, 1717, 1575, 329, 620, 10019, 203, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 389, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 19226, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.9; import "./DelightArmyManagerInterface.sol"; import "./DelightManager.sol"; import "./DelightBuildingManager.sol"; import "./DelightItemManager.sol"; import "./DelightKnightItemInterface.sol"; import "./Util/SafeMath.sol"; contract DelightArmyManager is DelightArmyManagerInterface, DelightManager { using SafeMath for uint; // The maximum number of units on a single tile. // 한 위치에 존재할 수 있는 최대 유닛 수 uint constant private MAX_POSITION_UNIT_COUNT = 50; // The default buff HP of a knight. // 기사의 기본 버프 HP uint constant private KNIGHT_DEFAULT_BUFF_HP = 10; // Delight building manager // Delight 건물 관리자 DelightBuildingManager private buildingManager; // Delight item manager // Delight 아이템 관리자 DelightItemManager private itemManager; // 기사 아이템 DelightKnightItemInterface private knightItem; constructor( DelightInfoInterface info, DelightResource wood, DelightResource stone, DelightResource iron, DelightResource ducat, DelightKnightItemInterface _knightItem ) DelightManager(info, wood, stone, iron, ducat) public { // Knight item. // 기사 아이템 knightItem = _knightItem; // 0번지는 사용하지 않습니다. armies.push(Army({ unitKind : 99, unitCount : 0, knightItemId : 0, col : COL_RANGE, row : ROW_RANGE, owner : address(0), createTime : 0 })); } function setDelightBuildingManagerOnce(address addr) external { // The address must be empty. // 비어있는 주소인 경우에만 require(address(buildingManager) == address(0)); buildingManager = DelightBuildingManager(addr); } function setDelightItemManagerOnce(address addr) external { // The address must be empty. // 비어있는 주소인 경우에만 require(address(itemManager) == address(0)); itemManager = DelightItemManager(addr); } // Executed only when the sender is Delight. // Sender가 Delight일때만 실행 modifier onlyDelight() { require( msg.sender == delight || msg.sender == address(buildingManager) || msg.sender == address(itemManager) ); _; } Army[] internal armies; mapping(uint => mapping(uint => uint[])) internal positionToArmyIds; mapping(uint => Reward) private battleIdToReward; // Returns the total number of armies. // 부대의 총 개수를 반환합니다. function getArmyCount() view external returns (uint) { return armies.length; } // Returns the information of the army. // 부대의 정보를 반환합니다. function getArmyInfo(uint armyId) view external returns ( uint unitKind, uint unitCount, uint knightItemId, uint col, uint row, address owner, uint createTime ) { Army memory army = armies[armyId]; return ( army.unitKind, army.unitCount, army.knightItemId, army.col, army.row, army.owner, army.createTime ); } // 보상 정보를 반환합니다. function getRewardInfo(uint battleId) view external returns ( uint wood, uint stone, uint iron, uint ducat ) { Reward memory reward = battleIdToReward[battleId]; return ( reward.wood, reward.stone, reward.iron, reward.ducat ); } // Gets the IDs of the armies in a specific tile. // 특정 위치에 존재하는 부대의 ID들을 가져옵니다. function getPositionArmyIds(uint col, uint row) view external returns (uint[] memory) { return positionToArmyIds[col][row]; } // Gets the owners of the armies in a specific tile. // 특정 위치에 존재하는 부대의 소유주를 가져옵니다. function getPositionOwner(uint col, uint row) view external returns (address) { uint[] memory armyIds = positionToArmyIds[col][row]; for (uint i = 0; i < armyIds.length; i += 1) { address owner = armies[armyIds[i]].owner; if (owner != address(0)) { return owner; } } return address(0); } // 특정 위치의 총 유닛 숫자를 계산합니다. function getTotalUnitCount(uint distance, uint col, uint row) view public returns (uint) { uint[] memory armyIds = positionToArmyIds[col][row]; uint totalUnitCount = 0; for (uint i = 0; i < armyIds.length; i += 1) { // Check if the unit can reach the distance. // 이동이 가능한 거리인지 확인합니다. if (distance <= info.getUnitMovableDistance(armies[armyIds[i]].unitKind)) { totalUnitCount = totalUnitCount.add(armies[armyIds[i]].unitCount); } } return totalUnitCount; } // Creates armies. // 부대를 생산합니다. function createArmy(address owner, uint col, uint row, uint unitKind, uint unitCount) onlyDelight external { uint[] storage armyIds = positionToArmyIds[col][row]; // The total number of units in the building's tile must not exceed the maximum unit number. // 건물이 위치한 곳의 총 유닛 숫자가 최대 유닛 수를 넘기면 안됩니다. require(getTotalUnitCount(0, col, row).add(unitCount) <= MAX_POSITION_UNIT_COUNT); // 기사는 하나 이상 생성할 수 없습니다. require(unitKind != UNIT_KNIGHT || unitCount == 1); uint materialWood = info.getUnitMaterialWood(unitKind).mul(unitCount); uint materialStone = info.getUnitMaterialStone(unitKind).mul(unitCount); uint materialIron = info.getUnitMaterialIron(unitKind).mul(unitCount); uint materialDucat = info.getUnitMaterialDucat(unitKind).mul(unitCount); // Checks if there's enough amount of required resources to create the army. // 부대를 생성하는데 필요한 자원이 충분한지 확인합니다. require( wood.balanceOf(owner) >= materialWood && stone.balanceOf(owner) >= materialStone && iron.balanceOf(owner) >= materialIron && ducat.balanceOf(owner) >= materialDucat ); armyIds.length = UNIT_KIND_COUNT; // If an army exists already, the number of units in the army increases. // 기존에 부대가 존재하면 부대원의 숫자 증가 if (armyIds[unitKind] != 0) { // 기사는 추가할 수 없습니다. require(unitKind != UNIT_KNIGHT); armies[armyIds[unitKind]].unitCount = armies[armyIds[unitKind]].unitCount.add(unitCount); } // Creates a new army. // 새 부대 생성 else { armyIds[unitKind] = armies.push(Army({ unitKind : unitKind, unitCount : unitCount, knightItemId : 0, col : col, row : row, owner : owner, createTime : now })).sub(1); } // Transfers the resources to Delight. // 자원을 Delight로 이전합니다. wood.transferFrom(owner, delight, materialWood); stone.transferFrom(owner, delight, materialStone); iron.transferFrom(owner, delight, materialIron); ducat.transferFrom(owner, delight, materialDucat); // 이벤트 발생 emit CreateArmy(armyIds[unitKind]); } // Equips items in the army. // 부대에 아이템을 장착합니다. function attachItem(address owner, uint armyId, uint itemKind, uint unitCount) onlyDelight external { Army storage army = armies[armyId]; // Checks the owner of the army. // 부대의 소유주를 확인합니다. require(army.owner == owner); // Checks if there's enough units. // 유닛 수가 충분한지 확인합니다. require(army.unitCount >= unitCount); // Checks if the item is available for the type of army. // 부대의 성격과 아이템의 성격이 일치한지 확인합니다. require( // Swordsmen // 검병 ( army.unitKind == UNIT_SWORDSMAN && ( itemKind == ITEM_AXE || itemKind == ITEM_SPEAR || itemKind == ITEM_SHIELD || itemKind == ITEM_HOOD ) ) || // Archers // 궁수 ( army.unitKind == UNIT_ARCHER && ( itemKind == ITEM_CROSSBOW || itemKind == ITEM_BALLISTA || itemKind == ITEM_CATAPULT ) ) || // Cavalry // 기마병 ( army.unitKind == UNIT_CAVALY && ( itemKind == ITEM_CAMEL || itemKind == ITEM_ELEPHANT ) ) ); // Transfers items to Delight. // 아이템을 Delight로 이전합니다. itemManager.attachItem(owner, itemKind, unitCount); // Creates a new army, changing some of the units. // 유닛의 일부를 변경하여 새로운 부대를 생성합니다. // The type of the units of the new army. // 새 부대 유닛의 성격 uint unitKind; if (itemKind == ITEM_AXE) { unitKind = UNIT_AXEMAN; } else if (itemKind == ITEM_SPEAR) { unitKind = UNIT_SPEARMAN; } else if (itemKind == ITEM_SHIELD) { unitKind = UNIT_SHIELDMAN; } else if (itemKind == ITEM_HOOD) { unitKind = UNIT_SPY; } else if (itemKind == ITEM_CROSSBOW) { unitKind = UNIT_CROSSBOWMAN; } else if (itemKind == ITEM_BALLISTA) { unitKind = UNIT_BALLISTA; } else if (itemKind == ITEM_CATAPULT) { unitKind = UNIT_CATAPULT; } else if (itemKind == ITEM_CAMEL) { unitKind = UNIT_CAMELRY; } else if (itemKind == ITEM_ELEPHANT) { unitKind = UNIT_WAR_ELEPHANT; } army.unitCount = army.unitCount.sub(unitCount); uint[] storage armyIds = positionToArmyIds[army.col][army.row]; // If an army already exists, the number of units in the army increases. // 기존에 부대가 존재하면 부대원의 숫자 증가 uint originArmyId = armyIds[unitKind]; if (originArmyId != 0) { armies[originArmyId].unitCount = armies[originArmyId].unitCount.add(unitCount); } // Creates a new army. // 새 부대 생성 else { armyIds[unitKind] = armies.push(Army({ unitKind : unitKind, unitCount : unitCount, knightItemId : 0, col : army.col, row : army.row, owner : owner, createTime : now })).sub(1); // 이벤트 발생 emit CreateArmy(armyIds[unitKind]); } // 기존 부대원이 남아있지 않으면 제거합니다. if (army.unitCount == 0) { delete armyIds[army.unitKind]; delete armies[armyId]; } // 이벤트 발생 emit AttachItem(armyId, armyIds[unitKind]); } // Equips an item to a knight. // 기사에 아이템을 장착합니다. function attachKnightItem(address owner, uint armyId, uint itemId) onlyDelight external { Army storage army = armies[armyId]; // Check the army's owner. // 부대의 소유주를 확인합니다. require(army.owner == owner); // Check if it's a knight. // 기사인지 확인합니다. require(army.unitKind == UNIT_KNIGHT); // Check if the knight is already equipped with an item. // 기사가 아이템을 장착하고 있지 않은지 확인합니다. require(army.knightItemId == 0); // Transfers the item to Delight. // 아이템을 Delight로 이전합니다. itemManager.attachKnightItem(owner, itemId); // Assigns the knight item. // 기사 아이템을 지정합니다. army.knightItemId = itemId; // 이벤트 발생 emit AttachKnightItem(armyId); } // Moves an army. // 부대의 위치를 이전합니다. function moveArmy(uint fromCol, uint fromRow, uint toCol, uint toRow) onlyDelight external { // 위치가 달라야 합니다. require(fromCol != toCol || fromRow != toRow); // Calculates distance. // 거리 계산 uint distance = (fromCol < toCol ? toCol - fromCol : fromCol - toCol) + (fromRow < toRow ? toRow - fromRow : fromRow - toRow); uint[] storage armyIds = positionToArmyIds[fromCol][fromRow]; uint[] storage targetArmyIds = positionToArmyIds[toCol][toRow]; targetArmyIds.length = UNIT_KIND_COUNT; // Calculate the total number of units in the tile where the merge take place. // 병합할 위치에 존재하는 총 유닛 숫자를 계산합니다. uint totalUnitCount = getTotalUnitCount(0, toCol, toRow); for (uint i = 0; i < UNIT_KIND_COUNT; i += 1) { Army memory army = armies[armyIds[i]]; if ( // The number of units must be bigger than 0. // 유닛의 개수가 0개 이상이어야 합니다. army.unitCount > 0 && // Check if the unit can reach the distance. // 이동이 가능한 거리인지 확인합니다. distance <= info.getUnitMovableDistance(army.unitKind)) { moveArmyOne(totalUnitCount, armyIds[i], army.unitCount, toCol, toRow); } } } // 단일 부대의 위치를 이전합니다. function moveArmyOne(uint totalUnitCount, uint armyId, uint unitCount, uint toCol, uint toRow) onlyDelight public { Army storage army = armies[armyId]; uint[] storage armyIds = positionToArmyIds[army.col][army.row]; uint[] storage targetArmyIds = positionToArmyIds[toCol][toRow]; targetArmyIds.length = UNIT_KIND_COUNT; Army storage targetArmy = armies[targetArmyIds[army.unitKind]]; // If the number of units exceeds the maximum number when just moving, // 그대로 이동했을 때 존재할 수 있는 최대 유닛의 숫자를 넘는 경우 if (totalUnitCount.add(unitCount) > MAX_POSITION_UNIT_COUNT) { uint movableUnitCount = MAX_POSITION_UNIT_COUNT.sub(totalUnitCount); // 이동할 유닛은 1개 이상이어야합니다. require(movableUnitCount > 0); // Creates a new army if it's empty. // 비어있는 곳이면 새 부대를 생성합니다. if (targetArmy.unitCount == 0) { targetArmyIds[army.unitKind] = armies.push(Army({ unitKind : army.unitKind, unitCount : movableUnitCount, knightItemId : 0, col : toCol, row : toRow, owner : army.owner, createTime : now })).sub(1); army.unitCount = army.unitCount.sub(movableUnitCount); // 이벤트 발생 emit CreateArmy(targetArmyIds[army.unitKind]); } // Merges with an existing army if it isn't empty. // 비어있지 않으면 병합합니다. else { // 기사는 병합할 수 없습니다. require(army.unitKind != UNIT_KNIGHT); targetArmy.unitCount = targetArmy.unitCount.add(movableUnitCount); army.unitCount = army.unitCount.sub(movableUnitCount); } // 이벤트 발생 emit MergeArmy(armyId, targetArmyIds[army.unitKind], movableUnitCount); // 기존 부대원이 남아있지 않으면 제거합니다. if (army.unitCount == 0) { delete armyIds[army.unitKind]; delete armies[armyId]; } } // 모든 유닛 이동 else if (army.unitCount == unitCount) { // move if the tile is empty. // 비어있는 곳이면 이전합니다. if (targetArmy.unitCount == 0) { targetArmyIds[army.unitKind] = armyId; army.col = toCol; army.row = toRow; // 이벤트 발생 emit MoveArmy(armyId); delete armyIds[army.unitKind]; } // merge with an existing army if it isn't empty. // 비어있지 않으면 병합합니다. else { // 기사는 병합할 수 없습니다. require(army.unitKind != UNIT_KNIGHT); targetArmy.unitCount = targetArmy.unitCount.add(army.unitCount); // 이벤트 발생 emit MergeArmy(armyId, targetArmyIds[army.unitKind], army.unitCount); delete armyIds[army.unitKind]; delete armies[armyId]; } } // 일부 유닛 이동 else { // Creates a new army if it's empty. // 비어있는 곳이면 새 부대를 생성합니다. if (targetArmy.unitCount == 0) { targetArmyIds[army.unitKind] = armies.push(Army({ unitKind : army.unitKind, unitCount : unitCount, knightItemId : 0, col : toCol, row : toRow, owner : army.owner, createTime : now })).sub(1); army.unitCount = army.unitCount.sub(unitCount); // 이벤트 발생 emit CreateArmy(targetArmyIds[army.unitKind]); } // Merges with an existing army if it isn't empty. // 비어있지 않으면 병합합니다. else { // 기사는 병합할 수 없습니다. require(army.unitKind != UNIT_KNIGHT); targetArmy.unitCount = targetArmy.unitCount.add(unitCount); army.unitCount = army.unitCount.sub(unitCount); } // 이벤트 발생 emit MergeArmy(armyId, targetArmyIds[army.unitKind], unitCount); } } function getItemKindByUnitKind(uint unitKind) pure private returns (uint) { if (unitKind == UNIT_AXEMAN) { return ITEM_AXE; } else if (unitKind == UNIT_SPEARMAN) { return ITEM_SPEAR; } else if (unitKind == UNIT_SHIELDMAN) { return ITEM_SHIELD; } else if (unitKind == UNIT_SPY) { return ITEM_HOOD; } else if (unitKind == UNIT_CROSSBOWMAN) { return ITEM_CROSSBOW; } else if (unitKind == UNIT_BALLISTA) { return ITEM_BALLISTA; } else if (unitKind == UNIT_CATAPULT) { return ITEM_CATAPULT; } else if (unitKind == UNIT_CAMELRY) { return ITEM_CAMEL; } else if (unitKind == UNIT_WAR_ELEPHANT) { return ITEM_ELEPHANT; } return 0; } // Attack // 부대를 공격합니다. function attack(uint battleId, uint totalDamage, uint distance, uint col, uint row) onlyDelight external returns (uint totalDeadUnitCount) { uint damage = totalDamage; // Loot // 전리품 Reward storage reward = battleIdToReward[battleId]; uint[] storage armyIds = positionToArmyIds[col][row]; for (uint i = 0; i < UNIT_KIND_COUNT; i += 1) { Army storage army = armies[armyIds[i]]; if ( // The number of units must be more than 0. // 유닛의 개수가 0개 이상이어야 합니다. army.unitCount > 0 && // Check if the units can reach the distance. // 이동이 가능한 거리인지 확인합니다. distance <= info.getUnitMovableDistance(army.unitKind)) { // 유닛의 체력을 계산합니다. uint unitHP = info.getUnitHP(army.unitKind).add( // Adds the knight item's HP if the unit's a knight. // 기사인 경우 기사 아이템의 HP를 추가합니다. i == UNIT_KNIGHT ? knightItem.getItemHP(army.knightItemId) : ( // If the unit's not a knight, adds the knight's buff HP. // 기사가 아닌 경우 기사의 버프 HP를 추가합니다. armyIds[UNIT_KNIGHT] != 0 && distance <= info.getUnitMovableDistance(UNIT_KNIGHT) ? KNIGHT_DEFAULT_BUFF_HP + knightItem.getItemBuffHP(armies[armyIds[UNIT_KNIGHT]].knightItemId) : 0 ) ).add( // 이동 거리가 0일때만 병사 위치의 건물의 버프 HP를 가져옵니다. distance == 0 ? buildingManager.getBuildingBuffHP(col, row) : 0 ); // Calcultes the HPs of the friendly army. // 아군의 체력을 계산합니다. uint armyHP = unitHP.mul(army.unitCount); armyHP = armyHP <= damage ? 0 : armyHP.sub(damage); // Calculates the result of the battle. // 전투 결과를 계산합니다. uint remainUnitCount = armyHP.add( // 나머지가 남지 않도록 armyHP % unitHP == 0 ? 0 : unitHP.sub(armyHP % unitHP) ).div(unitHP); uint deadUnitCount = army.unitCount.sub(remainUnitCount); // Lowers the total damage of the enemy. // 적의 총 데미지를 낮춥니다. damage = damage <= deadUnitCount.mul(unitHP) ? 0 : damage.sub(deadUnitCount.mul(unitHP)); // 원거리 공격인 경우 if (battleId == 0) { // Gets materials back. // 재료들을 돌려받습니다. wood.transferFrom(delight, army.owner, info.getUnitMaterialWood(army.unitKind).mul(deadUnitCount)); stone.transferFrom(delight, army.owner, info.getUnitMaterialStone(army.unitKind).mul(deadUnitCount)); iron.transferFrom(delight, army.owner, info.getUnitMaterialIron(army.unitKind).mul(deadUnitCount)); ducat.transferFrom(delight, army.owner, info.getUnitMaterialDucat(army.unitKind).mul(deadUnitCount)); } else { // Adds loot. // 전리품을 추가합니다. reward.wood = reward.wood.add(info.getUnitMaterialWood(army.unitKind).mul(deadUnitCount)); reward.stone = reward.stone.add(info.getUnitMaterialStone(army.unitKind).mul(deadUnitCount)); reward.iron = reward.iron.add(info.getUnitMaterialIron(army.unitKind).mul(deadUnitCount)); reward.ducat = reward.ducat.add(info.getUnitMaterialDucat(army.unitKind).mul(deadUnitCount)); } // Dismantles the equipped item. // 장착한 아이템을 분해합니다. if (getItemKindByUnitKind(army.unitKind) != 0) { itemManager.disassembleItem(getItemKindByUnitKind(army.unitKind), deadUnitCount); } // Saves the number of remaining units. // 남은 병사 숫자를 저장합니다. army.unitCount = remainUnitCount; // Adds to the number of total casualties. // 총 사망 병사 숫자에 추가합니다. totalDeadUnitCount = totalDeadUnitCount.add(deadUnitCount); // 이벤트 발생 if (deadUnitCount > 0) { emit DeadUnits(armyIds[i]); } // The army was annihilated. // 부대가 전멸했습니다. if (army.unitCount == 0) { // 기사가 무기를 장착한 경우 if (army.unitKind == UNIT_KNIGHT && army.knightItemId != 0) { // 원거리 공격인 경우 if (battleId == 0) { // 기사 무기를 돌려받습니다. itemManager.transferKnightItem(army.owner, army.knightItemId); } else { // 기사 무기를 전리품에 추가합니다. reward.knightItemId = army.knightItemId; } } delete armies[armyIds[i]]; delete armyIds[i]; } // 살아남은 부대원이 있으면, 그대로 공격 종료 else { break; } } } } // Destroys the building. // 건물을 파괴합니다. function destroyBuilding(uint battleId, uint col, uint row) onlyDelight external { // The building must exist. // 건물이 존재하는 경우에만 if (buildingManager.getPositionBuildingId(col, row) != 0) { // Loot // 전리품 Reward storage reward = battleIdToReward[battleId]; ( uint wood, uint stone, uint iron, uint ducat ) = buildingManager.destroyBuilding(col, row); // Adds to the loot. // 전리품에 추가합니다. reward.wood = reward.wood.add(wood); reward.stone = reward.stone.add(stone); reward.iron = reward.iron.add(iron); reward.ducat = reward.ducat.add(ducat); } } // Achieved victory in the battle. // 전투에서 승리했습니다. function win(uint battleId, address winner) onlyDelight external { // Loot // 전리품 Reward memory reward = battleIdToReward[battleId]; // The winner takes the loot. // 승리자는 전리품을 취합니다. wood.transferFrom(delight, winner, reward.wood); stone.transferFrom(delight, winner, reward.stone); iron.transferFrom(delight, winner, reward.iron); ducat.transferFrom(delight, winner, reward.ducat); // 기사 무기를 전달합니다. if (reward.knightItemId != 0) { itemManager.transferKnightItem(winner, reward.knightItemId); } } }
단일 부대의 위치를 이전합니다. If the number of units exceeds the maximum number when just moving, 그대로 이동했을 때 존재할 수 있는 최대 유닛의 숫자를 넘는 경우 이동할 유닛은 1개 이상이어야합니다. Creates a new army if it's empty. 비어있는 곳이면 새 부대를 생성합니다. Merges with an existing army if it isn't empty. 비어있지 않으면 병합합니다. 기사는 병합할 수 없습니다. 기존 부대원이 남아있지 않으면 제거합니다. 모든 유닛 이동 move if the tile is empty. 비어있는 곳이면 이전합니다. 이벤트 발생 merge with an existing army if it isn't empty. 비어있지 않으면 병합합니다. 기사는 병합할 수 없습니다. 이벤트 발생 일부 유닛 이동 Creates a new army if it's empty. 비어있는 곳이면 새 부대를 생성합니다. Merges with an existing army if it isn't empty. 비어있지 않으면 병합합니다. 기사는 병합할 수 없습니다.
function moveArmyOne(uint totalUnitCount, uint armyId, uint unitCount, uint toCol, uint toRow) onlyDelight public { Army storage army = armies[armyId]; uint[] storage armyIds = positionToArmyIds[army.col][army.row]; uint[] storage targetArmyIds = positionToArmyIds[toCol][toRow]; targetArmyIds.length = UNIT_KIND_COUNT; Army storage targetArmy = armies[targetArmyIds[army.unitKind]]; if (totalUnitCount.add(unitCount) > MAX_POSITION_UNIT_COUNT) { uint movableUnitCount = MAX_POSITION_UNIT_COUNT.sub(totalUnitCount); require(movableUnitCount > 0); if (targetArmy.unitCount == 0) { targetArmyIds[army.unitKind] = armies.push(Army({ unitKind : army.unitKind, unitCount : movableUnitCount, knightItemId : 0, col : toCol, row : toRow, owner : army.owner, createTime : now })).sub(1); army.unitCount = army.unitCount.sub(movableUnitCount); } else { require(army.unitKind != UNIT_KNIGHT); targetArmy.unitCount = targetArmy.unitCount.add(movableUnitCount); army.unitCount = army.unitCount.sub(movableUnitCount); } if (army.unitCount == 0) { delete armyIds[army.unitKind]; delete armies[armyId]; } } else if (army.unitCount == unitCount) { if (targetArmy.unitCount == 0) { targetArmyIds[army.unitKind] = armyId; army.col = toCol; army.row = toRow; emit MoveArmy(armyId); delete armyIds[army.unitKind]; } else { require(army.unitKind != UNIT_KNIGHT); targetArmy.unitCount = targetArmy.unitCount.add(army.unitCount); emit MergeArmy(armyId, targetArmyIds[army.unitKind], army.unitCount); delete armyIds[army.unitKind]; delete armies[armyId]; } } else { if (targetArmy.unitCount == 0) { targetArmyIds[army.unitKind] = armies.push(Army({ unitKind : army.unitKind, unitCount : unitCount, knightItemId : 0, col : toCol, row : toRow, owner : army.owner, createTime : now })).sub(1); army.unitCount = army.unitCount.sub(unitCount); } else { require(army.unitKind != UNIT_KNIGHT); targetArmy.unitCount = targetArmy.unitCount.add(unitCount); army.unitCount = army.unitCount.sub(unitCount); } } }
2,526,320
[ 1, 172, 238, 106, 173, 256, 125, 225, 172, 119, 227, 172, 239, 227, 173, 256, 251, 225, 173, 255, 231, 173, 122, 251, 172, 103, 125, 225, 173, 256, 117, 173, 259, 231, 174, 248, 107, 172, 238, 235, 172, 238, 102, 18, 971, 326, 1300, 434, 4971, 14399, 326, 4207, 1300, 1347, 2537, 12499, 16, 225, 171, 120, 121, 172, 239, 227, 172, 99, 255, 225, 173, 256, 117, 172, 242, 252, 174, 249, 235, 173, 256, 231, 225, 172, 248, 239, 225, 173, 99, 117, 173, 257, 110, 174, 248, 259, 225, 173, 235, 251, 225, 173, 257, 235, 172, 237, 247, 225, 173, 118, 255, 172, 239, 227, 225, 173, 255, 259, 172, 238, 254, 173, 256, 251, 225, 173, 235, 109, 173, 257, 243, 172, 103, 125, 225, 172, 231, 251, 172, 237, 247, 225, 171, 115, 126, 173, 253, 113, 225, 173, 256, 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, 202, 915, 3635, 686, 4811, 3335, 12, 11890, 2078, 2802, 1380, 16, 2254, 419, 4811, 548, 16, 2254, 2836, 1380, 16, 2254, 358, 914, 16, 2254, 358, 1999, 13, 1338, 2837, 750, 1071, 288, 203, 1082, 203, 202, 202, 686, 4811, 2502, 419, 4811, 273, 23563, 606, 63, 4610, 93, 548, 15533, 203, 1082, 203, 202, 202, 11890, 8526, 2502, 419, 4811, 2673, 273, 1754, 774, 686, 4811, 2673, 63, 4610, 93, 18, 1293, 6362, 4610, 93, 18, 492, 15533, 203, 1082, 203, 202, 202, 11890, 8526, 2502, 1018, 686, 4811, 2673, 273, 1754, 774, 686, 4811, 2673, 63, 869, 914, 6362, 869, 1999, 15533, 203, 1082, 203, 202, 202, 3299, 686, 4811, 2673, 18, 2469, 273, 28721, 67, 47, 2356, 67, 7240, 31, 203, 1082, 203, 202, 202, 686, 4811, 2502, 1018, 686, 4811, 273, 23563, 606, 63, 3299, 686, 4811, 2673, 63, 4610, 93, 18, 4873, 5677, 13563, 31, 203, 1082, 203, 202, 202, 430, 261, 4963, 2802, 1380, 18, 1289, 12, 4873, 1380, 13, 405, 4552, 67, 15258, 67, 15736, 67, 7240, 13, 288, 203, 9506, 203, 1082, 202, 11890, 5730, 429, 2802, 1380, 273, 4552, 67, 15258, 67, 15736, 67, 7240, 18, 1717, 12, 4963, 2802, 1380, 1769, 203, 9506, 203, 1082, 202, 6528, 12, 81, 1527, 429, 2802, 1380, 405, 374, 1769, 203, 9506, 203, 1082, 202, 430, 261, 3299, 686, 4811, 18, 4873, 1380, 422, 374, 13, 288, 203, 6862, 203, 9506, 202, 3299, 686, 4811, 2673, 63, 4610, 93, 18, 4873, 5677, 65, 273, 23563, 606, 18, 2 ]
pragma solidity ^0.4.24; import "./ERC20Basic.sol"; import "./SafeMath.sol"; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } pragma solidity ^0.4.21; //通过log函数重载,对不同类型的变量trigger不同的event,实现solidity打印效果,使用方法为:log(string name, var value) contract Console { event LogUint(string, uint); function log(string s , uint x) internal { emit LogUint(s, x); } event LogInt(string, int); function log(string s , int x) internal { emit LogInt(s, x); } event LogBytes(string, bytes); function log(string s , bytes x) internal { emit LogBytes(s, x); } event LogBytes32(string, bytes32); function log(string s , bytes32 x) internal { emit LogBytes32(s, x); } event LogAddress(string, address); function log(string s , address x) internal { emit LogAddress(s, x); } event LogBool(string, bool); function log(string s , bool x) internal { emit LogBool(s, x); } } /* Implements EIP20 token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md .*/ pragma solidity ^0.4.21; import "./EIP20Interface.sol"; contract EIP20 is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function EIP20( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } import "./EIP20.sol"; pragma solidity ^0.4.21; contract EIP20Factory { mapping(address => address[]) public created; mapping(address => bool) public isEIP20; //verify without having to do a bytecode check. bytes public EIP20ByteCode; // solhint-disable-line var-name-mixedcase function EIP20Factory() public { //upon creation of the factory, deploy a EIP20 (parameters are meaningless) and store the bytecode provably. address verifiedToken = createEIP20(10000, "Verify Token", 3, "VTX"); EIP20ByteCode = codeAt(verifiedToken); } //verifies if a contract that has been deployed is a Human Standard Token. //NOTE: This is a very expensive function, and should only be used in an eth_call. ~800k gas function verifyEIP20(address _tokenContract) public view returns (bool) { bytes memory fetchedTokenByteCode = codeAt(_tokenContract); if (fetchedTokenByteCode.length != EIP20ByteCode.length) { return false; //clear mismatch } //starting iterating through it if lengths match for (uint i = 0; i < fetchedTokenByteCode.length; i++) { if (fetchedTokenByteCode[i] != EIP20ByteCode[i]) { return false; } } return true; } function createEIP20(uint256 _initialAmount, string _name, uint8 _decimals, string _symbol) public returns (address) { EIP20 newToken = (new EIP20(_initialAmount, _name, _decimals, _symbol)); created[msg.sender].push(address(newToken)); isEIP20[address(newToken)] = true; //the factory will own the created tokens. You must transfer them. newToken.transfer(msg.sender, _initialAmount); return address(newToken); } //for now, keeping this internal. Ideally there should also be a live version of this that // any contract can use, lib-style. //retrieves the bytecode at a specific address. function codeAt(address _addr) internal view returns (bytes outputCode) { assembly { // solhint-disable-line no-inline-assembly // retrieve the size of the code, this needs assembly let size := extcodesize(_addr) // allocate output byte array - this could also be done without assembly // by using outputCode = new bytes(size) outputCode := mload(0x40) // new "memory end" including padding mstore(0x40, add(outputCode, and(add(add(size, 0x20), 0x1f), not(0x1f)))) // store length in memory mstore(outputCode, size) // actually retrieve the code, this needs assembly extcodecopy(_addr, add(outputCode, 0x20), 0, size) } } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md pragma solidity ^0.4.21; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } pragma solidity ^0.4.24; import "./ERC20Basic.sol"; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } pragma solidity ^0.4.18; // import './zeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import './MintableToken.sol'; /** * @title ERC865Token Token * * ERC865Token allows users paying transfers in tokens instead of gas * https://github.com/ethereum/EIPs/issues/865 * */ contract ERC865 is ERC20 { function transferPreSigned( bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool); function approvePreSigned( bytes _signature, address _spender, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool); function increaseApprovalPreSigned( bytes _signature, address _spender, uint256 _addedValue, uint256 _fee, uint256 _nonce ) public returns (bool); function decreaseApprovalPreSigned( bytes _signature, address _spender, uint256 _subtractedValue, uint256 _fee, uint256 _nonce ) public returns (bool); function transferFromPreSigned( bytes _signature, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool); } pragma solidity ^0.4.18; import './ERC865.sol'; // import './zeppelin-solidity/contracts/token/ERC20/StandardToken.sol'; import './MintableToken.sol'; import "./Console.sol"; // import "./Console.sol"; /** * @title FcsToken Token * * FcsToken allows users paying transfers in tokens instead of gas * https://github.com/ethereum/EIPs/issues/865 * */ contract FcsToken is ERC865, StandardToken, Console { /* Nonces of transfers performed */ mapping(bytes => bool) signatures; event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); event ApprovalPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); /** * @notice Submit a presigned transfer * @param _signature bytes The signature, issued by the owner. * * @param _to address The address which you want to transfer to. * @param _value uint256 The amount of tokens to be transferred. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ // public 等同常數 不可改寫 string public constant name = "金貓幣"; // 名稱 string public constant symbol = "gtCats"; // 幣的真正名 uint8 public constant decimals = 4; // 小數點後4位 uint256 public totalSupply = 1000000000000000; // 發行 gtCats 幣數量 constructor() public { balances[msg.sender] = totalSupply; } function transferPreSigned( // 伺服器用 (post交易) bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_to != address(0)); // address(0) FC服務位址 require(signatures[_signature] == false); // 需要:此簽名未交易過 // log("SEE log >> " , address(this)); // log0(bytes32(address(this))); bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _value, _fee, _nonce); // hash加密 address from = recover(hashedTx, _signature); // 比對解出from require(from != address(0)); // form / to 不可為第三方服務位址(FC) balances[from] = balances[from].sub(_value).sub(_fee); // from的餘額 = 現在餘額 - 轉帳金額 - 手續費 balances[_to] = balances[_to].add(_value); balances[msg.sender] = balances[msg.sender].add(_fee); // 服務方的餘額 signatures[_signature] = true; // 記錄此簽名 已交易 Transfer(from, _to, _value); // 交易 Transfer(from, msg.sender, _fee); TransferPreSigned(from, _to, msg.sender, _value, _fee); // 再做一次 防止失敗 return true; } function debugfnGetFrom(//49 // No Use bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (address) { bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _value, _fee, _nonce); return recover(hashedTx, _signature); } /** * @notice Submit a presigned approval * @param _signature bytes The signature, issued by the owner. * @param _spender address The address which will spend the funds. * @param _value uint256 The amount of tokens to allow. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function approvePreSigned( // No Use bytes _signature, address _spender, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = approvePreSignedHashing(address(this), _spender, _value, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); allowed[from][_spender] = _value; balances[from] = balances[from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Approval(from, _spender, _value); Transfer(from, msg.sender, _fee); ApprovalPreSigned(from, _spender, msg.sender, _value, _fee); return true; } /** * @notice Increase the amount of tokens that an owner allowed to a spender. * @param _signature bytes The signature, issued by the owner. * @param _spender address The address which will spend the funds. * @param _addedValue uint256 The amount of tokens to increase the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function increaseApprovalPreSigned( // No Use bytes _signature, address _spender, uint256 _addedValue, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = increaseApprovalPreSignedHashing(address(this), _spender, _addedValue, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); allowed[from][_spender] = allowed[from][_spender].add(_addedValue); balances[from] = balances[from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Approval(from, _spender, allowed[from][_spender]); Transfer(from, msg.sender, _fee); ApprovalPreSigned(from, _spender, msg.sender, allowed[from][_spender], _fee); return true; } /** * @notice Decrease the amount of tokens that an owner allowed to a spender. * @param _signature bytes The signature, issued by the owner * @param _spender address The address which will spend the funds. * @param _subtractedValue uint256 The amount of tokens to decrease the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function decreaseApprovalPreSigned( // No Use bytes _signature, address _spender, uint256 _subtractedValue, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = decreaseApprovalPreSignedHashing(address(this), _spender, _subtractedValue, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); uint oldValue = allowed[from][_spender]; if (_subtractedValue > oldValue) { allowed[from][_spender] = 0; } else { allowed[from][_spender] = oldValue.sub(_subtractedValue); } balances[from] = balances[from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Approval(from, _spender, _subtractedValue); Transfer(from, msg.sender, _fee); ApprovalPreSigned(from, _spender, msg.sender, allowed[from][_spender], _fee); return true; } /** * @notice Transfer tokens from one address to another * @param _signature bytes The signature, issued by the spender. * @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. * @param _fee uint256 The amount of tokens paid to msg.sender, by the spender. * @param _nonce uint256 Presigned transaction number. */ function transferFromPreSigned( // No Use bytes _signature, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_to != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = transferFromPreSignedHashing(address(this), _from, _to, _value, _fee, _nonce); address spender = recover(hashedTx, _signature); require(spender != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][spender] = allowed[_from][spender].sub(_value); balances[spender] = balances[spender].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Transfer(_from, _to, _value); Transfer(spender, msg.sender, _fee); return true; } /** * @notice Hash (keccak256) of the payload used by transferPreSigned * @param _token address The address of the token. * @param _to address The address which you want to transfer to. * @param _value uint256 The amount of tokens to be transferred. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function transferPreSignedHashing( address _token, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure // 函式不讀取或不修改狀態 returns (bytes32) { /* "48664c16": transferPreSignedHashing(address,address,address,uint256,uint256,uint256) */ bytes32 hash = keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce); // bytes32 hash = keccak256(abi.encodePacked(_token, _to, _value, _fee, _nonce)); //Add prefix to hash return _prefix(hash); } function transferPreSignedHashing2( // 等於1 (拆開 加前綴加密部分) address _token, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure // 函式不讀取或不修改狀態 returns (bytes32) { /* "48664c16": transferPreSignedHashing(address,address,address,uint256,uint256,uint256) */ bytes32 hash = keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce); // bytes32 hash = keccak256(abi.encodePacked(_token, _to, _value, _fee, _nonce)); //Add prefix to hash return hash; } function _prefix(bytes32 _hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); } /** * @notice Hash (keccak256) of the payload used by approvePreSigned * @param _token address The address of the token * @param _spender address The address which will spend the funds. * @param _value uint256 The amount of tokens to allow. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function approvePreSignedHashing( // No Use address _token, address _spender, uint256 _value, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "f7ac9c2e": approvePreSignedHashing(address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0xf7ac9c2e), _token, _spender, _value, _fee, _nonce); } /** * @notice Hash (keccak256) of the payload used by increaseApprovalPreSigned * @param _token address The address of the token * @param _spender address The address which will spend the funds. * @param _addedValue uint256 The amount of tokens to increase the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function increaseApprovalPreSignedHashing( // No Use address _token, address _spender, uint256 _addedValue, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "a45f71ff": increaseApprovalPreSignedHashing(address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0xa45f71ff), _token, _spender, _addedValue, _fee, _nonce); } /** * @notice Hash (keccak256) of the payload used by decreaseApprovalPreSigned * @param _token address The address of the token * @param _spender address The address which will spend the funds. * @param _subtractedValue uint256 The amount of tokens to decrease the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function decreaseApprovalPreSignedHashing( // No Use address _token, address _spender, uint256 _subtractedValue, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "59388d78": decreaseApprovalPreSignedHashing(address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0x59388d78), _token, _spender, _subtractedValue, _fee, _nonce); } /** * @notice Hash (keccak256) of the payload used by transferFromPreSigned * @param _token address The address of the token * @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. * @param _fee uint256 The amount of tokens paid to msg.sender, by the spender. * @param _nonce uint256 Presigned transaction number. */ function transferFromPreSignedHashing( // No Use address _token, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "b7656dc5": transferFromPreSignedHashing(address,address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0xb7656dc5), _token, _from, _to, _value, _fee, _nonce); } /** * @notice Recover signer address from a message by using his signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) public 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, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } } pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.24; import "./StandardToken.sol"; import "./Ownable.sol"; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } pragma solidity ^0.4.24; /** * @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; } } pragma solidity ^0.4.24; import "./BasicToken.sol"; import "./ERC20.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } pragma solidity ^0.4.24; import "./ERC20Basic.sol"; import "./SafeMath.sol"; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } pragma solidity ^0.4.21; //通过log函数重载,对不同类型的变量trigger不同的event,实现solidity打印效果,使用方法为:log(string name, var value) contract Console { event LogUint(string, uint); function log(string s , uint x) internal { emit LogUint(s, x); } event LogInt(string, int); function log(string s , int x) internal { emit LogInt(s, x); } event LogBytes(string, bytes); function log(string s , bytes x) internal { emit LogBytes(s, x); } event LogBytes32(string, bytes32); function log(string s , bytes32 x) internal { emit LogBytes32(s, x); } event LogAddress(string, address); function log(string s , address x) internal { emit LogAddress(s, x); } event LogBool(string, bool); function log(string s , bool x) internal { emit LogBool(s, x); } } /* Implements EIP20 token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md .*/ pragma solidity ^0.4.21; import "./EIP20Interface.sol"; contract EIP20 is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function EIP20( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } import "./EIP20.sol"; pragma solidity ^0.4.21; contract EIP20Factory { mapping(address => address[]) public created; mapping(address => bool) public isEIP20; //verify without having to do a bytecode check. bytes public EIP20ByteCode; // solhint-disable-line var-name-mixedcase function EIP20Factory() public { //upon creation of the factory, deploy a EIP20 (parameters are meaningless) and store the bytecode provably. address verifiedToken = createEIP20(10000, "Verify Token", 3, "VTX"); EIP20ByteCode = codeAt(verifiedToken); } //verifies if a contract that has been deployed is a Human Standard Token. //NOTE: This is a very expensive function, and should only be used in an eth_call. ~800k gas function verifyEIP20(address _tokenContract) public view returns (bool) { bytes memory fetchedTokenByteCode = codeAt(_tokenContract); if (fetchedTokenByteCode.length != EIP20ByteCode.length) { return false; //clear mismatch } //starting iterating through it if lengths match for (uint i = 0; i < fetchedTokenByteCode.length; i++) { if (fetchedTokenByteCode[i] != EIP20ByteCode[i]) { return false; } } return true; } function createEIP20(uint256 _initialAmount, string _name, uint8 _decimals, string _symbol) public returns (address) { EIP20 newToken = (new EIP20(_initialAmount, _name, _decimals, _symbol)); created[msg.sender].push(address(newToken)); isEIP20[address(newToken)] = true; //the factory will own the created tokens. You must transfer them. newToken.transfer(msg.sender, _initialAmount); return address(newToken); } //for now, keeping this internal. Ideally there should also be a live version of this that // any contract can use, lib-style. //retrieves the bytecode at a specific address. function codeAt(address _addr) internal view returns (bytes outputCode) { assembly { // solhint-disable-line no-inline-assembly // retrieve the size of the code, this needs assembly let size := extcodesize(_addr) // allocate output byte array - this could also be done without assembly // by using outputCode = new bytes(size) outputCode := mload(0x40) // new "memory end" including padding mstore(0x40, add(outputCode, and(add(add(size, 0x20), 0x1f), not(0x1f)))) // store length in memory mstore(outputCode, size) // actually retrieve the code, this needs assembly extcodecopy(_addr, add(outputCode, 0x20), 0, size) } } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md pragma solidity ^0.4.21; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } pragma solidity ^0.4.24; import "./ERC20Basic.sol"; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } pragma solidity ^0.4.18; // import './zeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import './MintableToken.sol'; /** * @title ERC865Token Token * * ERC865Token allows users paying transfers in tokens instead of gas * https://github.com/ethereum/EIPs/issues/865 * */ contract ERC865 is ERC20 { function transferPreSigned( bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool); function approvePreSigned( bytes _signature, address _spender, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool); function increaseApprovalPreSigned( bytes _signature, address _spender, uint256 _addedValue, uint256 _fee, uint256 _nonce ) public returns (bool); function decreaseApprovalPreSigned( bytes _signature, address _spender, uint256 _subtractedValue, uint256 _fee, uint256 _nonce ) public returns (bool); function transferFromPreSigned( bytes _signature, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool); } pragma solidity ^0.4.18; import './ERC865.sol'; // import './zeppelin-solidity/contracts/token/ERC20/StandardToken.sol'; import './MintableToken.sol'; import "./Console.sol"; // import "./Console.sol"; /** * @title FcsToken Token * * FcsToken allows users paying transfers in tokens instead of gas * https://github.com/ethereum/EIPs/issues/865 * */ contract FcsToken is ERC865, StandardToken, Console { /* Nonces of transfers performed */ mapping(bytes => bool) signatures; event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); event ApprovalPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); /** * @notice Submit a presigned transfer * @param _signature bytes The signature, issued by the owner. * * @param _to address The address which you want to transfer to. * @param _value uint256 The amount of tokens to be transferred. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ // public 等同常數 不可改寫 string public constant name = "金貓幣"; // 名稱 string public constant symbol = "gtCats"; // 幣的真正名 uint8 public constant decimals = 4; // 小數點後4位 uint256 public totalSupply = 1000000000000000; // 發行 gtCats 幣數量 constructor() public { balances[msg.sender] = totalSupply; } function transferPreSigned( // 伺服器用 (post交易) bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_to != address(0)); // address(0) FC服務位址 require(signatures[_signature] == false); // 需要:此簽名未交易過 // log("SEE log >> " , address(this)); // log0(bytes32(address(this))); bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _value, _fee, _nonce); // hash加密 address from = recover(hashedTx, _signature); // 比對解出from require(from != address(0)); // form / to 不可為第三方服務位址(FC) balances[from] = balances[from].sub(_value).sub(_fee); // from的餘額 = 現在餘額 - 轉帳金額 - 手續費 balances[_to] = balances[_to].add(_value); balances[msg.sender] = balances[msg.sender].add(_fee); // 服務方的餘額 signatures[_signature] = true; // 記錄此簽名 已交易 Transfer(from, _to, _value); // 交易 Transfer(from, msg.sender, _fee); TransferPreSigned(from, _to, msg.sender, _value, _fee); // 再做一次 防止失敗 return true; } function debugfnGetFrom(//49 // No Use bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (address) { bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _value, _fee, _nonce); return recover(hashedTx, _signature); } /** * @notice Submit a presigned approval * @param _signature bytes The signature, issued by the owner. * @param _spender address The address which will spend the funds. * @param _value uint256 The amount of tokens to allow. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function approvePreSigned( // No Use bytes _signature, address _spender, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = approvePreSignedHashing(address(this), _spender, _value, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); allowed[from][_spender] = _value; balances[from] = balances[from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Approval(from, _spender, _value); Transfer(from, msg.sender, _fee); ApprovalPreSigned(from, _spender, msg.sender, _value, _fee); return true; } /** * @notice Increase the amount of tokens that an owner allowed to a spender. * @param _signature bytes The signature, issued by the owner. * @param _spender address The address which will spend the funds. * @param _addedValue uint256 The amount of tokens to increase the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function increaseApprovalPreSigned( // No Use bytes _signature, address _spender, uint256 _addedValue, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = increaseApprovalPreSignedHashing(address(this), _spender, _addedValue, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); allowed[from][_spender] = allowed[from][_spender].add(_addedValue); balances[from] = balances[from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Approval(from, _spender, allowed[from][_spender]); Transfer(from, msg.sender, _fee); ApprovalPreSigned(from, _spender, msg.sender, allowed[from][_spender], _fee); return true; } /** * @notice Decrease the amount of tokens that an owner allowed to a spender. * @param _signature bytes The signature, issued by the owner * @param _spender address The address which will spend the funds. * @param _subtractedValue uint256 The amount of tokens to decrease the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function decreaseApprovalPreSigned( // No Use bytes _signature, address _spender, uint256 _subtractedValue, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = decreaseApprovalPreSignedHashing(address(this), _spender, _subtractedValue, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); uint oldValue = allowed[from][_spender]; if (_subtractedValue > oldValue) { allowed[from][_spender] = 0; } else { allowed[from][_spender] = oldValue.sub(_subtractedValue); } balances[from] = balances[from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Approval(from, _spender, _subtractedValue); Transfer(from, msg.sender, _fee); ApprovalPreSigned(from, _spender, msg.sender, allowed[from][_spender], _fee); return true; } /** * @notice Transfer tokens from one address to another * @param _signature bytes The signature, issued by the spender. * @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. * @param _fee uint256 The amount of tokens paid to msg.sender, by the spender. * @param _nonce uint256 Presigned transaction number. */ function transferFromPreSigned( // No Use bytes _signature, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_to != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = transferFromPreSignedHashing(address(this), _from, _to, _value, _fee, _nonce); address spender = recover(hashedTx, _signature); require(spender != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][spender] = allowed[_from][spender].sub(_value); balances[spender] = balances[spender].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Transfer(_from, _to, _value); Transfer(spender, msg.sender, _fee); return true; } /** * @notice Hash (keccak256) of the payload used by transferPreSigned * @param _token address The address of the token. * @param _to address The address which you want to transfer to. * @param _value uint256 The amount of tokens to be transferred. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function transferPreSignedHashing( address _token, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure // 函式不讀取或不修改狀態 returns (bytes32) { /* "48664c16": transferPreSignedHashing(address,address,address,uint256,uint256,uint256) */ bytes32 hash = keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce); // bytes32 hash = keccak256(abi.encodePacked(_token, _to, _value, _fee, _nonce)); //Add prefix to hash return _prefix(hash); } function transferPreSignedHashing2( // 等於1 (拆開 加前綴加密部分) address _token, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure // 函式不讀取或不修改狀態 returns (bytes32) { /* "48664c16": transferPreSignedHashing(address,address,address,uint256,uint256,uint256) */ bytes32 hash = keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce); // bytes32 hash = keccak256(abi.encodePacked(_token, _to, _value, _fee, _nonce)); //Add prefix to hash return hash; } function _prefix(bytes32 _hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); } /** * @notice Hash (keccak256) of the payload used by approvePreSigned * @param _token address The address of the token * @param _spender address The address which will spend the funds. * @param _value uint256 The amount of tokens to allow. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function approvePreSignedHashing( // No Use address _token, address _spender, uint256 _value, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "f7ac9c2e": approvePreSignedHashing(address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0xf7ac9c2e), _token, _spender, _value, _fee, _nonce); } /** * @notice Hash (keccak256) of the payload used by increaseApprovalPreSigned * @param _token address The address of the token * @param _spender address The address which will spend the funds. * @param _addedValue uint256 The amount of tokens to increase the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function increaseApprovalPreSignedHashing( // No Use address _token, address _spender, uint256 _addedValue, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "a45f71ff": increaseApprovalPreSignedHashing(address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0xa45f71ff), _token, _spender, _addedValue, _fee, _nonce); } /** * @notice Hash (keccak256) of the payload used by decreaseApprovalPreSigned * @param _token address The address of the token * @param _spender address The address which will spend the funds. * @param _subtractedValue uint256 The amount of tokens to decrease the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function decreaseApprovalPreSignedHashing( // No Use address _token, address _spender, uint256 _subtractedValue, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "59388d78": decreaseApprovalPreSignedHashing(address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0x59388d78), _token, _spender, _subtractedValue, _fee, _nonce); } /** * @notice Hash (keccak256) of the payload used by transferFromPreSigned * @param _token address The address of the token * @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. * @param _fee uint256 The amount of tokens paid to msg.sender, by the spender. * @param _nonce uint256 Presigned transaction number. */ function transferFromPreSignedHashing( // No Use address _token, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "b7656dc5": transferFromPreSignedHashing(address,address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0xb7656dc5), _token, _from, _to, _value, _fee, _nonce); } /** * @notice Recover signer address from a message by using his signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) public 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, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } } pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.24; import "./StandardToken.sol"; import "./Ownable.sol"; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } pragma solidity ^0.4.24; /** * @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; } } pragma solidity ^0.4.24; import "./BasicToken.sol"; import "./ERC20.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } pragma solidity ^0.4.24; import "./ERC20Basic.sol"; import "./SafeMath.sol"; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } pragma solidity ^0.4.21; //通过log函数重载,对不同类型的变量trigger不同的event,实现solidity打印效果,使用方法为:log(string name, var value) contract Console { event LogUint(string, uint); function log(string s , uint x) internal { emit LogUint(s, x); } event LogInt(string, int); function log(string s , int x) internal { emit LogInt(s, x); } event LogBytes(string, bytes); function log(string s , bytes x) internal { emit LogBytes(s, x); } event LogBytes32(string, bytes32); function log(string s , bytes32 x) internal { emit LogBytes32(s, x); } event LogAddress(string, address); function log(string s , address x) internal { emit LogAddress(s, x); } event LogBool(string, bool); function log(string s , bool x) internal { emit LogBool(s, x); } } /* Implements EIP20 token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md .*/ pragma solidity ^0.4.21; import "./EIP20Interface.sol"; contract EIP20 is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function EIP20( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } import "./EIP20.sol"; pragma solidity ^0.4.21; contract EIP20Factory { mapping(address => address[]) public created; mapping(address => bool) public isEIP20; //verify without having to do a bytecode check. bytes public EIP20ByteCode; // solhint-disable-line var-name-mixedcase function EIP20Factory() public { //upon creation of the factory, deploy a EIP20 (parameters are meaningless) and store the bytecode provably. address verifiedToken = createEIP20(10000, "Verify Token", 3, "VTX"); EIP20ByteCode = codeAt(verifiedToken); } //verifies if a contract that has been deployed is a Human Standard Token. //NOTE: This is a very expensive function, and should only be used in an eth_call. ~800k gas function verifyEIP20(address _tokenContract) public view returns (bool) { bytes memory fetchedTokenByteCode = codeAt(_tokenContract); if (fetchedTokenByteCode.length != EIP20ByteCode.length) { return false; //clear mismatch } //starting iterating through it if lengths match for (uint i = 0; i < fetchedTokenByteCode.length; i++) { if (fetchedTokenByteCode[i] != EIP20ByteCode[i]) { return false; } } return true; } function createEIP20(uint256 _initialAmount, string _name, uint8 _decimals, string _symbol) public returns (address) { EIP20 newToken = (new EIP20(_initialAmount, _name, _decimals, _symbol)); created[msg.sender].push(address(newToken)); isEIP20[address(newToken)] = true; //the factory will own the created tokens. You must transfer them. newToken.transfer(msg.sender, _initialAmount); return address(newToken); } //for now, keeping this internal. Ideally there should also be a live version of this that // any contract can use, lib-style. //retrieves the bytecode at a specific address. function codeAt(address _addr) internal view returns (bytes outputCode) { assembly { // solhint-disable-line no-inline-assembly // retrieve the size of the code, this needs assembly let size := extcodesize(_addr) // allocate output byte array - this could also be done without assembly // by using outputCode = new bytes(size) outputCode := mload(0x40) // new "memory end" including padding mstore(0x40, add(outputCode, and(add(add(size, 0x20), 0x1f), not(0x1f)))) // store length in memory mstore(outputCode, size) // actually retrieve the code, this needs assembly extcodecopy(_addr, add(outputCode, 0x20), 0, size) } } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md pragma solidity ^0.4.21; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } pragma solidity ^0.4.24; import "./ERC20Basic.sol"; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } pragma solidity ^0.4.18; // import './zeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import './MintableToken.sol'; /** * @title ERC865Token Token * * ERC865Token allows users paying transfers in tokens instead of gas * https://github.com/ethereum/EIPs/issues/865 * */ contract ERC865 is ERC20 { function transferPreSigned( bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool); function approvePreSigned( bytes _signature, address _spender, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool); function increaseApprovalPreSigned( bytes _signature, address _spender, uint256 _addedValue, uint256 _fee, uint256 _nonce ) public returns (bool); function decreaseApprovalPreSigned( bytes _signature, address _spender, uint256 _subtractedValue, uint256 _fee, uint256 _nonce ) public returns (bool); function transferFromPreSigned( bytes _signature, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool); } pragma solidity ^0.4.18; import './ERC865.sol'; // import './zeppelin-solidity/contracts/token/ERC20/StandardToken.sol'; import './MintableToken.sol'; import "./Console.sol"; // import "./Console.sol"; /** * @title FcsToken Token * * FcsToken allows users paying transfers in tokens instead of gas * https://github.com/ethereum/EIPs/issues/865 * */ contract FcsToken is ERC865, StandardToken, Console { /* Nonces of transfers performed */ mapping(bytes => bool) signatures; event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); event ApprovalPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); /** * @notice Submit a presigned transfer * @param _signature bytes The signature, issued by the owner. * * @param _to address The address which you want to transfer to. * @param _value uint256 The amount of tokens to be transferred. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ // public 等同常數 不可改寫 string public constant name = "金貓幣"; // 名稱 string public constant symbol = "gtCats"; // 幣的真正名 uint8 public constant decimals = 4; // 小數點後4位 uint256 public totalSupply = 1000000000000000; // 發行 gtCats 幣數量 constructor() public { balances[msg.sender] = totalSupply; } function transferPreSigned( // 伺服器用 (post交易) bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_to != address(0)); // address(0) FC服務位址 require(signatures[_signature] == false); // 需要:此簽名未交易過 // log("SEE log >> " , address(this)); // log0(bytes32(address(this))); bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _value, _fee, _nonce); // hash加密 address from = recover(hashedTx, _signature); // 比對解出from require(from != address(0)); // form / to 不可為第三方服務位址(FC) balances[from] = balances[from].sub(_value).sub(_fee); // from的餘額 = 現在餘額 - 轉帳金額 - 手續費 balances[_to] = balances[_to].add(_value); balances[msg.sender] = balances[msg.sender].add(_fee); // 服務方的餘額 signatures[_signature] = true; // 記錄此簽名 已交易 Transfer(from, _to, _value); // 交易 Transfer(from, msg.sender, _fee); TransferPreSigned(from, _to, msg.sender, _value, _fee); // 再做一次 防止失敗 return true; } function debugfnGetFrom(//49 // No Use bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (address) { bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _value, _fee, _nonce); return recover(hashedTx, _signature); } /** * @notice Submit a presigned approval * @param _signature bytes The signature, issued by the owner. * @param _spender address The address which will spend the funds. * @param _value uint256 The amount of tokens to allow. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function approvePreSigned( // No Use bytes _signature, address _spender, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = approvePreSignedHashing(address(this), _spender, _value, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); allowed[from][_spender] = _value; balances[from] = balances[from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Approval(from, _spender, _value); Transfer(from, msg.sender, _fee); ApprovalPreSigned(from, _spender, msg.sender, _value, _fee); return true; } /** * @notice Increase the amount of tokens that an owner allowed to a spender. * @param _signature bytes The signature, issued by the owner. * @param _spender address The address which will spend the funds. * @param _addedValue uint256 The amount of tokens to increase the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function increaseApprovalPreSigned( // No Use bytes _signature, address _spender, uint256 _addedValue, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = increaseApprovalPreSignedHashing(address(this), _spender, _addedValue, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); allowed[from][_spender] = allowed[from][_spender].add(_addedValue); balances[from] = balances[from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Approval(from, _spender, allowed[from][_spender]); Transfer(from, msg.sender, _fee); ApprovalPreSigned(from, _spender, msg.sender, allowed[from][_spender], _fee); return true; } /** * @notice Decrease the amount of tokens that an owner allowed to a spender. * @param _signature bytes The signature, issued by the owner * @param _spender address The address which will spend the funds. * @param _subtractedValue uint256 The amount of tokens to decrease the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function decreaseApprovalPreSigned( // No Use bytes _signature, address _spender, uint256 _subtractedValue, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = decreaseApprovalPreSignedHashing(address(this), _spender, _subtractedValue, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); uint oldValue = allowed[from][_spender]; if (_subtractedValue > oldValue) { allowed[from][_spender] = 0; } else { allowed[from][_spender] = oldValue.sub(_subtractedValue); } balances[from] = balances[from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Approval(from, _spender, _subtractedValue); Transfer(from, msg.sender, _fee); ApprovalPreSigned(from, _spender, msg.sender, allowed[from][_spender], _fee); return true; } /** * @notice Transfer tokens from one address to another * @param _signature bytes The signature, issued by the spender. * @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. * @param _fee uint256 The amount of tokens paid to msg.sender, by the spender. * @param _nonce uint256 Presigned transaction number. */ function transferFromPreSigned( // No Use bytes _signature, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_to != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = transferFromPreSignedHashing(address(this), _from, _to, _value, _fee, _nonce); address spender = recover(hashedTx, _signature); require(spender != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][spender] = allowed[_from][spender].sub(_value); balances[spender] = balances[spender].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Transfer(_from, _to, _value); Transfer(spender, msg.sender, _fee); return true; } /** * @notice Hash (keccak256) of the payload used by transferPreSigned * @param _token address The address of the token. * @param _to address The address which you want to transfer to. * @param _value uint256 The amount of tokens to be transferred. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function transferPreSignedHashing( address _token, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure // 函式不讀取或不修改狀態 returns (bytes32) { /* "48664c16": transferPreSignedHashing(address,address,address,uint256,uint256,uint256) */ bytes32 hash = keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce); // bytes32 hash = keccak256(abi.encodePacked(_token, _to, _value, _fee, _nonce)); //Add prefix to hash return _prefix(hash); } function transferPreSignedHashing2( // 等於1 (拆開 加前綴加密部分) address _token, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure // 函式不讀取或不修改狀態 returns (bytes32) { /* "48664c16": transferPreSignedHashing(address,address,address,uint256,uint256,uint256) */ bytes32 hash = keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce); // bytes32 hash = keccak256(abi.encodePacked(_token, _to, _value, _fee, _nonce)); //Add prefix to hash return hash; } function _prefix(bytes32 _hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); } /** * @notice Hash (keccak256) of the payload used by approvePreSigned * @param _token address The address of the token * @param _spender address The address which will spend the funds. * @param _value uint256 The amount of tokens to allow. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function approvePreSignedHashing( // No Use address _token, address _spender, uint256 _value, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "f7ac9c2e": approvePreSignedHashing(address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0xf7ac9c2e), _token, _spender, _value, _fee, _nonce); } /** * @notice Hash (keccak256) of the payload used by increaseApprovalPreSigned * @param _token address The address of the token * @param _spender address The address which will spend the funds. * @param _addedValue uint256 The amount of tokens to increase the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function increaseApprovalPreSignedHashing( // No Use address _token, address _spender, uint256 _addedValue, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "a45f71ff": increaseApprovalPreSignedHashing(address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0xa45f71ff), _token, _spender, _addedValue, _fee, _nonce); } /** * @notice Hash (keccak256) of the payload used by decreaseApprovalPreSigned * @param _token address The address of the token * @param _spender address The address which will spend the funds. * @param _subtractedValue uint256 The amount of tokens to decrease the allowance by. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. */ function decreaseApprovalPreSignedHashing( // No Use address _token, address _spender, uint256 _subtractedValue, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "59388d78": decreaseApprovalPreSignedHashing(address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0x59388d78), _token, _spender, _subtractedValue, _fee, _nonce); } /** * @notice Hash (keccak256) of the payload used by transferFromPreSigned * @param _token address The address of the token * @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. * @param _fee uint256 The amount of tokens paid to msg.sender, by the spender. * @param _nonce uint256 Presigned transaction number. */ function transferFromPreSignedHashing( // No Use address _token, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { /* "b7656dc5": transferFromPreSignedHashing(address,address,address,uint256,uint256,uint256) */ return keccak256(bytes4(0xb7656dc5), _token, _from, _to, _value, _fee, _nonce); } /** * @notice Recover signer address from a message by using his signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) public 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, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } } pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.24; import "./StandardToken.sol"; import "./Ownable.sol"; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } pragma solidity ^0.4.24; /** * @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; } } pragma solidity ^0.4.24; import "./BasicToken.sol"; import "./ERC20.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
bytes32 hash = keccak256(abi.encodePacked(_token, _to, _value, _fee, _nonce));Add prefix to hash
{ bytes32 hash = keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce); return hash; }
6,486,943
[ 1, 3890, 1578, 1651, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 2316, 16, 389, 869, 16, 389, 1132, 16, 389, 21386, 16, 389, 12824, 10019, 986, 1633, 358, 1651, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 3639, 1731, 1578, 1651, 273, 417, 24410, 581, 5034, 12, 3890, 24, 12, 20, 92, 24, 5292, 1105, 71, 2313, 3631, 389, 2316, 16, 389, 869, 16, 389, 1132, 16, 389, 21386, 16, 389, 12824, 1769, 203, 3639, 327, 1651, 31, 203, 565, 289, 203, 377, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-12-21 */ pragma solidity ^0.5.7; // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 interface ERC20Token { /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) external returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) external returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) external view returns (uint256 remaining); /** * @notice return total supply of tokens */ function totalSupply() external view returns (uint256 supply); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Get the contract's 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(), "Only the contract's owner can invoke this function"); _; } /** * @dev Sets an owner address * @param _newOwner new owner address */ function _setOwner(address _newOwner) internal { _owner = _newOwner; } /** * @dev is sender the owner of the contract? * @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. * 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() external 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) external onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0), "New owner cannot be address(0)"); emit OwnershipTransferred(_owner, _newOwner); _owner = _newOwner; } } contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" event Upgraded(address indexed implementation); function updateCodeAddress(address newAddress) internal { require( bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) } emit Upgraded(newAddress); } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public; } contract SafeTransfer { function _safeTransfer(ERC20Token _token, address _to, uint256 _value) internal returns (bool result) { _token.transfer(_to, _value); assembly { switch returndatasize() case 0 { result := not(0) } case 32 { returndatacopy(0, 0, 32) result := mload(0) } default { revert(0, 0) } } require(result, "Unsuccessful token transfer"); } function _safeTransferFrom( ERC20Token _token, address _from, address _to, uint256 _value ) internal returns (bool result) { _token.transferFrom(_from, _to, _value); assembly { switch returndatasize() case 0 { result := not(0) } case 32 { returndatacopy(0, 0, 32) result := mload(0) } default { revert(0, 0) } } require(result, "Unsuccessful token transfer"); } } /* solium-disable security/no-block-members */ /* solium-disable security/no-inline-assembly */ /** * @title License * @dev Contract for buying a license */ contract License is Ownable, ApproveAndCallFallBack, SafeTransfer, Proxiable { uint256 public price; ERC20Token token; address burnAddress; struct LicenseDetails { uint price; uint creationTime; } address[] public licenseOwners; mapping(address => uint) public idxLicenseOwners; mapping(address => LicenseDetails) public licenseDetails; event Bought(address buyer, uint256 price); event PriceChanged(uint256 _price); bool internal _initialized; /** * @param _tokenAddress Address of token used to pay for licenses (SNT) * @param _price Price of the licenses * @param _burnAddress Address where the license fee is going to be sent */ constructor(address _tokenAddress, uint256 _price, address _burnAddress) public { init(_tokenAddress, _price, _burnAddress); } /** * @dev Initialize contract (used with proxy). Can only be called once * @param _tokenAddress Address of token used to pay for licenses (SNT) * @param _price Price of the licenses * @param _burnAddress Address where the license fee is going to be sent */ function init( address _tokenAddress, uint256 _price, address _burnAddress ) public { assert(_initialized == false); _initialized = true; price = _price; token = ERC20Token(_tokenAddress); burnAddress = _burnAddress; _setOwner(msg.sender); } function updateCode(address newCode) public onlyOwner { updateCodeAddress(newCode); } /** * @notice Check if the address already owns a license * @param _address The address to check * @return bool */ function isLicenseOwner(address _address) public view returns (bool) { return licenseDetails[_address].price != 0 && licenseDetails[_address].creationTime != 0; } /** * @notice Buy a license * @dev Requires value to be equal to the price of the license. * The msg.sender must not already own a license. */ function buy() external returns(uint) { uint id = _buyFrom(msg.sender); return id; } /** * @notice Buy a license * @dev Requires value to be equal to the price of the license. * The _owner must not already own a license. */ function _buyFrom(address _licenseOwner) internal returns(uint) { require(licenseDetails[_licenseOwner].creationTime == 0, "License already bought"); licenseDetails[_licenseOwner] = LicenseDetails({ price: price, creationTime: block.timestamp }); uint idx = licenseOwners.push(_licenseOwner); idxLicenseOwners[_licenseOwner] = idx; emit Bought(_licenseOwner, price); require(_safeTransferFrom(token, _licenseOwner, burnAddress, price), "Unsuccessful token transfer"); return idx; } /** * @notice Set the license price * @param _price The new price of the license * @dev Only the owner of the contract can perform this action */ function setPrice(uint256 _price) external onlyOwner { price = _price; emit PriceChanged(_price); } /** * @dev Get number of license owners * @return uint */ function getNumLicenseOwners() external view returns (uint256) { return licenseOwners.length; } /** * @notice Support for "approveAndCall". Callable only by `token()`. * @param _from Who approved. * @param _amount Amount being approved, need to be equal `price()`. * @param _token Token being approved, need to be equal `token()`. * @param _data Abi encoded data with selector of `buy(and)`. */ function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public { require(_amount == price, "Wrong value"); require(_token == address(token), "Wrong token"); require(_token == address(msg.sender), "Wrong call"); require(_data.length == 4, "Wrong data length"); require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()")) _buyFrom(_from); } /** * @dev Decodes abi encoded data with selector for "buy()". * @param _data Abi encoded data. * @return Decoded registry call. */ function _abiDecodeBuy(bytes memory _data) internal pure returns(bytes4 sig) { assembly { sig := mload(add(_data, add(0x20, 0))) } } } /* solium-disable security/no-block-members */ /** * @title ArbitratorLicense * @dev Contract for management of an arbitrator license */ contract ArbitrationLicense is License { enum RequestStatus {NONE,AWAIT,ACCEPTED,REJECTED,CLOSED} struct Request{ address seller; address arbitrator; RequestStatus status; uint date; } struct ArbitratorLicenseDetails { uint id; bool acceptAny;// accept any seller } mapping(address => ArbitratorLicenseDetails) public arbitratorlicenseDetails; mapping(address => mapping(address => bool)) public permissions; mapping(address => mapping(address => bool)) public blacklist; mapping(bytes32 => Request) public requests; event ArbitratorRequested(bytes32 id, address indexed seller, address indexed arbitrator); event RequestAccepted(bytes32 id, address indexed arbitrator, address indexed seller); event RequestRejected(bytes32 id, address indexed arbitrator, address indexed seller); event RequestCanceled(bytes32 id, address indexed arbitrator, address indexed seller); event BlacklistSeller(address indexed arbitrator, address indexed seller); event UnBlacklistSeller(address indexed arbitrator, address indexed seller); /** * @param _tokenAddress Address of token used to pay for licenses (SNT) * @param _price Amount of token needed to buy a license * @param _burnAddress Burn address where the price of the license is sent */ constructor(address _tokenAddress, uint256 _price, address _burnAddress) License(_tokenAddress, _price, _burnAddress) public {} /** * @notice Buy an arbitrator license */ function buy() external returns(uint) { return _buy(msg.sender, false); } /** * @notice Buy an arbitrator license and set if the arbitrator accepts any seller * @param _acceptAny When set to true, all sellers are accepted by the arbitrator */ function buy(bool _acceptAny) external returns(uint) { return _buy(msg.sender, _acceptAny); } /** * @notice Buy an arbitrator license and set if the arbitrator accepts any seller. Sets the arbitrator as the address in params instead of the sender * @param _sender Address of the arbitrator * @param _acceptAny When set to true, all sellers are accepted by the arbitrator */ function _buy(address _sender, bool _acceptAny) internal returns (uint id) { id = _buyFrom(_sender); arbitratorlicenseDetails[_sender].id = id; arbitratorlicenseDetails[_sender].acceptAny = _acceptAny; } /** * @notice Change acceptAny parameter for arbitrator * @param _acceptAny indicates does arbitrator allow to accept any seller/choose sellers */ function changeAcceptAny(bool _acceptAny) public { require(isLicenseOwner(msg.sender), "Message sender should have a valid arbitrator license"); require(arbitratorlicenseDetails[msg.sender].acceptAny != _acceptAny, "Message sender should pass parameter different from the current one"); arbitratorlicenseDetails[msg.sender].acceptAny = _acceptAny; } /** * @notice Allows arbitrator to accept a seller * @param _arbitrator address of a licensed arbitrator */ function requestArbitrator(address _arbitrator) public { require(isLicenseOwner(_arbitrator), "Arbitrator should have a valid license"); require(!arbitratorlicenseDetails[_arbitrator].acceptAny, "Arbitrator already accepts all cases"); bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender)); RequestStatus _status = requests[_id].status; require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, "Invalid request status"); if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){ require(requests[_id].date + 3 days < block.timestamp, "Must wait 3 days before requesting the arbitrator again"); } requests[_id] = Request({ seller: msg.sender, arbitrator: _arbitrator, status: RequestStatus.AWAIT, date: block.timestamp }); emit ArbitratorRequested(_id, msg.sender, _arbitrator); } /** * @dev Get Request Id * @param _arbitrator Arbitrator address * @param _account Seller account * @return Request Id */ function getId(address _arbitrator, address _account) external pure returns(bytes32){ return keccak256(abi.encodePacked(_arbitrator,_account)); } /** * @notice Allows arbitrator to accept a seller's request * @param _id request id */ function acceptRequest(bytes32 _id) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); require(requests[_id].status == RequestStatus.AWAIT, "This request is not pending"); require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator already accepts all cases"); require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator"); requests[_id].status = RequestStatus.ACCEPTED; address _seller = requests[_id].seller; permissions[msg.sender][_seller] = true; emit RequestAccepted(_id, msg.sender, requests[_id].seller); } /** * @notice Allows arbitrator to reject a request * @param _id request id */ function rejectRequest(bytes32 _id) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status"); require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator accepts all cases"); require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator"); requests[_id].status = RequestStatus.REJECTED; requests[_id].date = block.timestamp; address _seller = requests[_id].seller; permissions[msg.sender][_seller] = false; emit RequestRejected(_id, msg.sender, requests[_id].seller); } /** * @notice Allows seller to cancel a request * @param _id request id */ function cancelRequest(bytes32 _id) public { require(requests[_id].seller == msg.sender, "This request id does not belong to the message sender"); require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status"); address arbitrator = requests[_id].arbitrator; requests[_id].status = RequestStatus.CLOSED; requests[_id].date = block.timestamp; address _arbitrator = requests[_id].arbitrator; permissions[_arbitrator][msg.sender] = false; emit RequestCanceled(_id, arbitrator, requests[_id].seller); } /** * @notice Allows arbitrator to blacklist a seller * @param _seller Seller address */ function blacklistSeller(address _seller) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = true; emit BlacklistSeller(msg.sender, _seller); } /** * @notice Allows arbitrator to remove a seller from the blacklist * @param _seller Seller address */ function unBlacklistSeller(address _seller) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = false; emit UnBlacklistSeller(msg.sender, _seller); } /** * @notice Checks if Arbitrator permits to use his/her services * @param _seller sellers's address * @param _arbitrator arbitrator's address */ function isAllowed(address _seller, address _arbitrator) public view returns(bool) { return (arbitratorlicenseDetails[_arbitrator].acceptAny && !blacklist[_arbitrator][_seller]) || permissions[_arbitrator][_seller]; } /** * @notice Support for "approveAndCall". Callable only by `token()`. * @param _from Who approved. * @param _amount Amount being approved, need to be equal `price()`. * @param _token Token being approved, need to be equal `token()`. * @param _data Abi encoded data with selector of `buy(and)`. */ function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public { require(_amount == price, "Wrong value"); require(_token == address(token), "Wrong token"); require(_token == address(msg.sender), "Wrong call"); require(_data.length == 4, "Wrong data length"); require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()")) _buy(_from, false); } } /* solium-disable no-empty-blocks */ /* solium-disable security/no-inline-assembly */ /** * @dev Uses ethereum signed messages */ contract MessageSigned { constructor() internal {} /** * @dev recovers address who signed the message * @param _signHash operation ethereum signed message hash * @param _messageSignature message `_signHash` signature */ function _recoverAddress(bytes32 _signHash, bytes memory _messageSignature) internal pure returns(address) { uint8 v; bytes32 r; bytes32 s; (v,r,s) = signatureSplit(_messageSignature); return ecrecover(_signHash, v, r, s); } /** * @dev Hash a hash with `"\x19Ethereum Signed Message:\n32"` * @param _hash Sign to hash. * @return Hash to be signed. */ function _getSignHash(bytes32 _hash) internal pure returns (bytes32 signHash) { signHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); } /** * @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s` * @param _signature Signature string */ function signatureSplit(bytes memory _signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) { require(_signature.length == 65, "Bad signature length"); // 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(_signature, 32)) s := mload(add(_signature, 64)) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(_signature, 65)), 0xff) } if (v < 27) { v += 27; } require(v == 27 || v == 28, "Bad signature version"); } } contract SecuredFunctions is Ownable { mapping(address => bool) public allowedContracts; /// @notice Only allowed addresses and the same contract can invoke this function modifier onlyAllowedContracts { require(allowedContracts[msg.sender] || msg.sender == address(this), "Only allowed contracts can invoke this function"); _; } /** * @dev Set contract addresses with special privileges to execute special functions * @param _contract Contract address * @param _allowed Is contract allowed? */ function setAllowedContract ( address _contract, bool _allowed ) public onlyOwner { allowedContracts[_contract] = _allowed; } } contract Stakable is Ownable, SafeTransfer { uint public basePrice = 0.01 ether; address payable public burnAddress; struct Stake { uint amount; address payable owner; address token; } mapping(uint => Stake) public stakes; mapping(address => uint) public stakeCounter; event BurnAddressChanged(address sender, address prevBurnAddress, address newBurnAddress); event BasePriceChanged(address sender, uint prevPrice, uint newPrice); event Staked(uint indexed itemId, address indexed owner, uint amount); event Unstaked(uint indexed itemId, address indexed owner, uint amount); event Slashed(uint indexed itemId, address indexed owner, address indexed slasher, uint amount); constructor(address payable _burnAddress) public { burnAddress = _burnAddress; } /** * @dev Changes the burn address * @param _burnAddress New burn address */ function setBurnAddress(address payable _burnAddress) external onlyOwner { emit BurnAddressChanged(msg.sender, burnAddress, _burnAddress); burnAddress = _burnAddress; } /** * @dev Changes the base price * @param _basePrice New burn address */ function setBasePrice(uint _basePrice) external onlyOwner { emit BasePriceChanged(msg.sender, basePrice, _basePrice); basePrice = _basePrice; } function _stake(uint _itemId, address payable _owner, address _tokenAddress) internal { require(stakes[_itemId].owner == address(0), "Already has/had a stake"); stakeCounter[_owner]++; uint stakeAmount = basePrice * stakeCounter[_owner] * stakeCounter[_owner]; // y = basePrice * x^2 // Using only ETH as stake for phase 0 _tokenAddress = address(0); require(msg.value == stakeAmount, "ETH amount is required"); // Uncomment to support tokens /* if (_tokenAddress != address(0)) { require(msg.value == 0, "Cannot send ETH with token address different from 0"); ERC20Token tokenToPay = ERC20Token(_tokenAddress); require(_safeTransferFrom(tokenToPay, _owner, address(this), stakeAmount), "Unsuccessful token transfer"); } else { require(msg.value == stakeAmount, "ETH amount is required"); } */ stakes[_itemId].amount = stakeAmount; stakes[_itemId].owner = _owner; stakes[_itemId].token = _tokenAddress; emit Staked(_itemId, _owner, stakeAmount); } function getAmountToStake(address _owner) public view returns(uint){ uint stakeCnt = stakeCounter[_owner] + 1; return basePrice * stakeCnt * stakeCnt; // y = basePrice * x^2 } function _unstake(uint _itemId) internal { Stake storage s = stakes[_itemId]; if (block.gaslimit == 0) return; // No stake for item //injected CONTRACT AFFECTED BY MINERS uint amount = s.amount; s.amount = 0; assert(stakeCounter[s.owner] > 0); stakeCounter[s.owner]--; if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS (bool success, ) = s.owner.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds"); } emit Unstaked(_itemId, s.owner, amount); } function _slash(uint _itemId) internal { Stake storage s = stakes[_itemId]; // TODO: what happens if offer was previosly validated and the user removed the stake? if (block.timestamp == 0) return; //injected CONTRACT AFFECTED BY MINERS uint amount = s.amount; s.amount = 0; if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS (bool success, ) = burnAddress.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(s.token), burnAddress, amount), "Couldn't transfer funds"); } emit Slashed(_itemId, s.owner, msg.sender, amount); } function _refundStake(uint _itemId) internal { Stake storage s = stakes[_itemId]; if (block.timestamp == 0) return; //injected CONTRACT AFFECTED BY MINERS uint amount = s.amount; s.amount = 0; stakeCounter[s.owner]--; if (block.number != 0) { //injected CONTRACT AFFECTED BY MINERS if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS (bool success, ) = s.owner.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds"); } } } } /** * @title MetadataStore * @dev User and offers registry */ contract MetadataStore is Stakable, MessageSigned, SecuredFunctions, Proxiable { struct User { string contactData; string location; string username; } struct Offer { int16 margin; uint[] paymentMethods; uint limitL; uint limitU; address asset; string currency; address payable owner; address payable arbitrator; bool deleted; } License public sellingLicenses; ArbitrationLicense public arbitrationLicenses; mapping(address => User) public users; mapping(address => uint) public user_nonce; Offer[] public offers; mapping(address => uint256[]) public addressToOffers; mapping(address => mapping (uint256 => bool)) public offerWhitelist; bool internal _initialized; event OfferAdded( address owner, uint256 offerId, address asset, string location, string currency, string username, uint[] paymentMethods, uint limitL, uint limitU, int16 margin ); event OfferRemoved(address owner, uint256 offerId); /** * @param _sellingLicenses Sellers licenses contract address * @param _arbitrationLicenses Arbitrators licenses contract address * @param _burnAddress Address to send slashed offer funds */ constructor(address _sellingLicenses, address _arbitrationLicenses, address payable _burnAddress) public Stakable(_burnAddress) { init(_sellingLicenses, _arbitrationLicenses); } /** * @dev Initialize contract (used with proxy). Can only be called once * @param _sellingLicenses Sellers licenses contract address * @param _arbitrationLicenses Arbitrators licenses contract address */ function init( address _sellingLicenses, address _arbitrationLicenses ) public { assert(_initialized == false); _initialized = true; sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); basePrice = 0.01 ether; _setOwner(msg.sender); } function updateCode(address newCode) public onlyOwner { updateCodeAddress(newCode); } event LicensesChanged(address sender, address oldSellingLicenses, address newSellingLicenses, address oldArbitrationLicenses, address newArbitrationLicenses); /** * @dev Initialize contract (used with proxy). Can only be called once * @param _sellingLicenses Sellers licenses contract address * @param _arbitrationLicenses Arbitrators licenses contract address */ function setLicenses( address _sellingLicenses, address _arbitrationLicenses ) public onlyOwner { emit LicensesChanged(msg.sender, address(sellingLicenses), address(_sellingLicenses), address(arbitrationLicenses), (_arbitrationLicenses)); sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); } /** * @dev Get datahash to be signed * @param _username Username * @param _contactData Contact Data ContactType:UserId * @param _nonce Nonce value (obtained from user_nonce) * @return bytes32 to sign */ function _dataHash(string memory _username, string memory _contactData, uint _nonce) internal view returns (bytes32) { return keccak256(abi.encodePacked(address(this), _username, _contactData, _nonce)); } /** * @notice Get datahash to be signed * @param _username Username * @param _contactData Contact Data ContactType:UserId * @return bytes32 to sign */ function getDataHash(string calldata _username, string calldata _contactData) external view returns (bytes32) { return _dataHash(_username, _contactData, user_nonce[msg.sender]); } /** * @dev Get signer address from signature. This uses the signature parameters to validate the signature * @param _username Status username * @param _contactData Contact Data ContactType:UserId * @param _nonce User nonce * @param _signature Signature obtained from the previous parameters * @return Signing user address */ function _getSigner( string memory _username, string memory _contactData, uint _nonce, bytes memory _signature ) internal view returns(address) { bytes32 signHash = _getSignHash(_dataHash(_username, _contactData, _nonce)); return _recoverAddress(signHash, _signature); } /** * @notice Get signer address from signature * @param _username Status username * @param _contactData Contact Data ContactType:UserId * @param _nonce User nonce * @param _signature Signature obtained from the previous parameters * @return Signing user address */ function getMessageSigner( string calldata _username, string calldata _contactData, uint _nonce, bytes calldata _signature ) external view returns(address) { return _getSigner(_username, _contactData, _nonce, _signature); } /** * @dev Adds or updates user information * @param _user User address to update * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username */ function _addOrUpdateUser( address _user, string memory _contactData, string memory _location, string memory _username ) internal { User storage u = users[_user]; u.contactData = _contactData; u.location = _location; u.username = _username; } /** * @notice Adds or updates user information via signature * @param _signature Signature * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username * @return Signing user address */ function addOrUpdateUser( bytes calldata _signature, string calldata _contactData, string calldata _location, string calldata _username, uint _nonce ) external returns(address payable _user) { _user = address(uint160(_getSigner(_username, _contactData, _nonce, _signature))); require(_nonce == user_nonce[_user], "Invalid nonce"); user_nonce[_user]++; _addOrUpdateUser(_user, _contactData, _location, _username); return _user; } /** * @notice Adds or updates user information * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username * @return Signing user address */ function addOrUpdateUser( string calldata _contactData, string calldata _location, string calldata _username ) external { _addOrUpdateUser(msg.sender, _contactData, _location, _username); } /** * @notice Adds or updates user information * @dev can only be called by the escrow contract * @param _sender Address that sets the user info * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username * @return Signing user address */ function addOrUpdateUser( address _sender, string calldata _contactData, string calldata _location, string calldata _username ) external onlyAllowedContracts { _addOrUpdateUser(_sender, _contactData, _location, _username); } /** * @dev Add a new offer with a new user if needed to the list * @param _asset The address of the erc20 to exchange, pass 0x0 for Eth * @param _contactData Contact Data ContactType:UserId * @param _location The location on earth * @param _currency The currency the user want to receive (USD, EUR...) * @param _username The username of the user * @param _paymentMethods The list of the payment methods the user accept * @param _limitL Lower limit accepted * @param _limitU Upper limit accepted * @param _margin The margin for the user * @param _arbitrator The arbitrator used by the offer */ function addOffer( address _asset, string memory _contactData, string memory _location, string memory _currency, string memory _username, uint[] memory _paymentMethods, uint _limitL, uint _limitU, int16 _margin, address payable _arbitrator ) public payable { //require(sellingLicenses.isLicenseOwner(msg.sender), "Not a license owner"); // @TODO: limit number of offers if the sender is unlicensed? require(arbitrationLicenses.isAllowed(msg.sender, _arbitrator), "Arbitrator does not allow this transaction"); require(_limitL <= _limitU, "Invalid limits"); require(msg.sender != _arbitrator, "Cannot arbitrate own offers"); _addOrUpdateUser( msg.sender, _contactData, _location, _username ); Offer memory newOffer = Offer( _margin, _paymentMethods, _limitL, _limitU, _asset, _currency, msg.sender, _arbitrator, false ); uint256 offerId = offers.push(newOffer) - 1; offerWhitelist[msg.sender][offerId] = true; addressToOffers[msg.sender].push(offerId); emit OfferAdded( msg.sender, offerId, _asset, _location, _currency, _username, _paymentMethods, _limitL, _limitU, _margin); _stake(offerId, msg.sender, _asset); } /** * @notice Remove user offer * @dev Removed offers are marked as deleted instead of being deleted * @param _offerId Id of the offer to remove */ function removeOffer(uint256 _offerId) external { require(offerWhitelist[msg.sender][_offerId], "Offer does not exist"); offers[_offerId].deleted = true; offerWhitelist[msg.sender][_offerId] = false; emit OfferRemoved(msg.sender, _offerId); _unstake(_offerId); } /** * @notice Get the offer by Id * @dev normally we'd access the offers array, but it would not return the payment methods * @param _id Offer id * @return Offer data (see Offer struct) */ function offer(uint256 _id) external view returns ( address asset, string memory currency, int16 margin, uint[] memory paymentMethods, uint limitL, uint limitH, address payable owner, address payable arbitrator, bool deleted ) { Offer memory theOffer = offers[_id]; // In case arbitrator rejects the seller address payable offerArbitrator = theOffer.arbitrator; if(!arbitrationLicenses.isAllowed(theOffer.owner, offerArbitrator)){ offerArbitrator = address(0); } return ( theOffer.asset, theOffer.currency, theOffer.margin, theOffer.paymentMethods, theOffer.limitL, theOffer.limitU, theOffer.owner, offerArbitrator, theOffer.deleted ); } /** * @notice Get the offer's owner by Id * @dev Helper function * @param _id Offer id * @return Seller address */ function getOfferOwner(uint256 _id) external view returns (address payable) { return (offers[_id].owner); } /** * @notice Get the offer's asset by Id * @dev Helper function * @param _id Offer id * @return Token address used in the offer */ function getAsset(uint256 _id) external view returns (address) { return (offers[_id].asset); } /** * @notice Get the offer's arbitrator by Id * @dev Helper function * @param _id Offer id * @return Arbitrator address */ function getArbitrator(uint256 _id) external view returns (address payable) { return (offers[_id].arbitrator); } /** * @notice Get the size of the offers * @return Number of offers stored in the contract */ function offersSize() external view returns (uint256) { return offers.length; } /** * @notice Get all the offer ids of the address in params * @param _address Address of the offers * @return Array of offer ids for a specific address */ function getOfferIds(address _address) external view returns (uint256[] memory) { return addressToOffers[_address]; } /** * @dev Slash offer stake. If the sender is not the escrow contract, nothing will happen * @param _offerId Offer Id to slash */ function slashStake(uint _offerId) external onlyAllowedContracts { _slash(_offerId); } /** * @dev Refunds a stake. Can be called automatically after an escrow is released * @param _offerId Offer Id to slash */ function refundStake(uint _offerId) external onlyAllowedContracts { _refundStake(_offerId); } }
injected CONTRACT AFFECTED BY MINERS
if (block.timestamp == 0) return;
6,474,455
[ 1, 267, 6059, 8020, 2849, 1268, 432, 2246, 4239, 2056, 6953, 6989, 11367, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 2629, 18, 5508, 422, 374, 13, 327, 31, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.4.24; // ---------------------------------------------------------------------------- // 安全的加减乘除 // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns(uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns(uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns(uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns(uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns(uint); function balanceOf(address tokenOwner) public constant returns(uint balance); function allowance(address tokenOwner, address spender) public constant returns(uint remaining); function transfer(address to, uint tokens) public returns(bool success); function approve(address spender, uint tokens) public returns(bool success); function transferFrom(address from, address to, uint tokens) public returns(bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract EttToken{ function tokenAdd(address user,uint tokens) public returns(bool success); function tokenSub(address user,uint tokens) public returns(bool success); function balanceOf(address tokenOwner) public constant returns(uint balance); } // ---------------------------------------------------------------------------- // 核心类 // ---------------------------------------------------------------------------- contract USDT is ERC20Interface{ using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply;//总发行 // uint public sellPrice; //出售价格 1枚代币换多少以太 /1000 uint public buyPrice; //购买价格 多少以太可购买1枚代币 /1000 uint public transper; //转账手续费 /3% bool public actived; uint public teamper1;//团队奖% uint public teamper2;//团队奖% //uint public sellper;//15 uint public sysinteth; mapping(address => uint) balances;//总计 //mapping(address => uint) myeth;//本金 // mapping(address => uint) froeth;//冻结 //mapping(address => uint) used; mapping(address => mapping(address => uint)) allowed; /* 冻结账户 */ mapping(address => bool) public frozenAccount; //上家地址 mapping(address => address) public fromaddr; //管理员帐号 mapping(address => bool) public admins; // 记录各个账户的增量时间 mapping(address => uint) public crontime; // 挖矿次数 // mapping(address => uint) public mintnum; uint[] public permans; mapping(address => uint) public teamget; struct sunsdata{ mapping(uint => uint) n; mapping(uint => uint) n_effective; } mapping(address => sunsdata) suns; address public intertoken; modifier onlyInterface { require(intertoken != address(0)); require(msg.sender == intertoken); _; } /* 通知 */ event FrozenFunds(address target, bool frozen); address public owner; address public financer; modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyFinancer { require(msg.sender == financer); _; } struct record{ //当前可提现本金 uint can_draw_capital; //当前已投资本金 uint not_draw_capital; //总的应释放利润 uint total_profit; //总的已释放利润 uint releasd_profit; //投资时间 uint last_investdate; uint history_releasd_profit; } mapping(address=>record) public user_inverst_record; struct plan{ uint account; uint times; } mapping(uint => plan) public plans; struct node_profit{ uint menber_counts; uint percent; } mapping(uint => node_profit) public node_profits; // uint public min_investment; uint public per; uint public OnceWidrawTime; mapping(address => bool) _effective_son; struct quit_conf{ uint interval; uint rate1; uint rate2; } quit_conf public quit_config; uint teamPrice1; uint teamPrice2; mapping(address=>bool) public isleader; mapping(address =>uint) public leader_eth; mapping(address=>uint) public userineth; address [] public leaders; EttToken public ett; uint public ettRate; uint generation; uint generation_team; mapping(address=>address) public ethtop; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(EttToken _ettAddress,address [] _supernodes) public { symbol = "USDT"; name = "USDT Coin"; decimals = 18; _totalSupply = 1000000000 ether; buyPrice = 138 ether; //购买价格 1eth can buy how much mt transper = uint(0);//转账手续费 /100 teamper1 = 10;//团队奖% /100 teamper2 = 20;//团队奖% /100 //sellper = 85;// /100 actived = true; permans = [40,10,12,6]; //permans = [3,3,2,2];//test balances[this] = _totalSupply; owner = msg.sender; financer = msg.sender; per = 1; plans[1].account = 7000 ether; plans[1].times = 2 ; plans[2].account = 35000 ether; plans[2].times = 3 ; plans[3].account = 70000 ether; plans[3].times = 4 ; plans[4].account = 210000 ether; plans[4].times = 5 ; for(uint i=1;i<=16;i++){ node_profits[i].menber_counts = i; if(i==1){ node_profits[i].percent = 100; }else if(i==2){ node_profits[i].percent = 20; }else if(i==3){ node_profits[i].percent = 15; }else if(i == 4){ node_profits[i].percent = 10; }else{ node_profits[i].percent = 5; } } OnceWidrawTime = 24 hours; //OnceWidrawTime = 10 seconds; //min_investment = plans[1].account ; //quit_config.interval = 30 days //quit_config.interval = 30 seconds; quit_config.interval = 30 days; quit_config.rate1 = 5; quit_config.rate2 = 1; teamPrice1 = 100000 ether; teamPrice2 = 500000 ether; ettRate = 70 ether; generation = 16; generation_team = 8; ett = _ettAddress; for(uint m;m<_supernodes.length;m++){ addLeader(_supernodes[m]); } emit Transfer(address(0), owner, _totalSupply); } /* 获取用户金额 */ function balanceOf(address user) public view returns(uint balance) { return balances[user]; } function ethbalance(address user) public view returns(uint _balance) { _balance = address(user).balance; } /* * 获取用户的挖矿时间 * @param {Object} address */ function getaddtime(address _addr) public view returns(uint) { if(crontime[_addr] < 2) { return(0); }else{ return(crontime[_addr]); } } function getmy(address user) public view returns( uint myblance, uint meth, uint mytime, uint bprice, uint tmoney, uint myineth, bool _isleader, uint _leader_eth, uint [10] _inverst /* uint _can_draw_capital, uint _not_draw_capital, uint _last_investdate, uint _total_profit, uint _releasd_profit, uint _history_releasd_profit */ ){ address _user = user; myblance = balances[_user];//0 meth = ethbalance(_user);//2 mytime = crontime[_user];//5 bprice = buyPrice;//6 tmoney = balances[this];//9 myineth = userineth[_user]; _isleader = isleader[_user]; _leader_eth = leader_eth[_user]; _inverst[0]=user_inverst_record[_user].can_draw_capital; _inverst[1]=user_inverst_record[_user].last_investdate; _inverst[2]=user_inverst_record[_user].not_draw_capital; _inverst[3]=user_inverst_record[_user].total_profit; _inverst[4]=user_inverst_record[_user].releasd_profit; _inverst[5] = user_inverst_record[_user].history_releasd_profit; _inverst[6] = ethbalance(_user); _inverst[7] = getquitfee(_user); _inverst[8] = ettRate; _inverst[9] = getettbalance(_user); /* _can_draw_capital=user_inverst_record[_user].can_draw_capital; _last_investdate=user_inverst_record[_user].last_investdate; _not_draw_capital=user_inverst_record[_user].not_draw_capital; _total_profit=user_inverst_record[_user].total_profit; _releasd_profit=user_inverst_record[_user].releasd_profit; _history_releasd_profit = user_inverst_record[_user].history_releasd_profit; */ } function setRwardGeneration(uint _generation,uint _generation_team) public onlyOwner returns(bool){ if(_generation_team>1&&_generation>1&&_generation<=16){ generation = _generation; generation_team = _generation_team; return true; }else{ return false; } } function getRwardGeneration() public view onlyOwner returns(uint _generation,uint _generation_team){ _generation = generation; _generation_team = generation_team; } function geteam(address _user) public view returns( uint nn1,//0 uint nn2,//1 uint n_effective1, uint n_effective2, uint [16] n, uint [16] n_effective, uint ms,//6 uint tm,//7 uint lid//11 ){ nn1 = suns[_user].n[1]; nn2 = suns[_user].n[2]; n_effective1 = suns[_user].n_effective[1]; n_effective2 = suns[_user].n_effective[2]; for(uint i;i<16;i++){ n[i] = suns[_user].n[i+1]; n_effective[i] = suns[_user].n_effective[i+1]; } ms = teamget[_user]; tm = getaddtime(_user); if(suns[_user].n_effective[2] >= permans[2] && suns[_user].n_effective[1] >= permans[3]){ lid = 1; } if(suns[_user].n_effective[2] >= permans[0] && suns[_user].n_effective[1] >= permans[1]){ lid = 2; } } function getsys() public view returns( uint tmoney,//0 uint _sysinteth ){ tmoney = _totalSupply.sub(balances[this]); _sysinteth = sysinteth; } function _transfer(address from, address to, uint tokens) private returns(bool success) { require(!frozenAccount[from]); require(!frozenAccount[to]); require(actived == true); uint addper = tokens*transper/100; uint allmoney = tokens + addper; require(balances[from] >= allmoney); require(tokens > 0 && tokens < _totalSupply); // 防止转移到0x0, 用burn代替这个功能 require(to != 0x0); require(from != to); // 将此保存为将来的断言, 函数最后会有一个检验103 - 3 + 10 uint previousBalances = balances[from] - addper + balances[to]; //如果用户没有上家 if(fromaddr[to] == address(0) && fromaddr[from] != to) { //指定上家地址 fromaddr[to] = from; address top = fromaddr[to]; if(isleader[ethtop[top]]){ ethtop[to] = ethtop[top]; } if(isleader[top] ){ ethtop[to] = top; } address _to = to; for(uint i = 1;i<=16;i++){ if(top != address(0) && top !=_to){ suns[top].n[i] += 1; _to = top; top = fromaddr[top]; continue; }else{ break; } } } balances[from] = balances[from].sub(allmoney); balances[this] = balances[this].add(addper); balances[to] = balances[to].add(tokens); emit Transfer(from, this, addper); emit Transfer(from, to, tokens); // 断言检测, 不应该为错 assert(balances[from] + balances[to] == previousBalances);//90 10 return true; } /* * 用户转账 * @param {Object} address */ function transfer(address to, uint tokens) public returns(bool success) { _transfer(msg.sender, to, tokens); success = true; } function intertransfer(address from, address to, uint tokens) public onlyInterface returns(bool success) { _transfer(from, to, tokens); success = true; } /* * 获取上家地址 * @param {Object} address */ function getfrom(address _addr) public view returns(address) { return(fromaddr[_addr]); } function approve(address spender, uint tokens) public returns(bool success) { require(tokens > 1 && tokens < _totalSupply); require(balances[msg.sender] >= tokens); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } /* * 授权转账 * @param {Object} address */ function transferFrom(address from, address to, uint tokens) public returns(bool success) { require(actived == true); require(!frozenAccount[from]); require(!frozenAccount[to]); require(tokens > 1 && tokens < _totalSupply); require(balances[from] >= tokens); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } /* * 获取授权信息 * @param {Object} address */ function allowance(address tokenOwner, address spender) public view returns(uint remaining) { return allowed[tokenOwner][spender]; } /// 冻结 or 解冻账户 function freezeAccount(address target, bool freeze) public onlyOwner{ frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /* * 系统设置 * @param {Object} uint */ function setconf( uint _per, uint _newOnceWidrawTime, uint _newBuyPrice, uint _ettRate ) public onlyOwner{ require(_per>0); require(ettRate>0); per = _per; OnceWidrawTime = _newOnceWidrawTime; buyPrice = _newBuyPrice; ettRate = _ettRate; } // * 获取系统设置 function getconf() public view returns( uint _per, uint _newOnceWidrawTime, uint _newBuyPrice, uint _ettRate) { _per = per; _newOnceWidrawTime = OnceWidrawTime; _newBuyPrice = buyPrice; _ettRate = ettRate; } function setother( uint _transper, uint _quit_interval, uint _quit_rate1, uint _quit_rate2 ) public onlyOwner{ transper = _transper; quit_config = quit_conf(_quit_interval,_quit_rate1,_quit_rate2); } function getquitfee(address _user) public view returns(uint ){ uint _fee; //require(actived == true&&!frozenAccount[msg.sender]); if (user_inverst_record[_user].can_draw_capital > 0){ uint interval = now.sub(user_inverst_record[_user].last_investdate); uint rate = quit_config.rate2; if(interval<quit_config.interval){ rate = quit_config.rate1; } uint fee = user_inverst_record[_user].can_draw_capital*rate/100; } _fee = fee; return _fee; } function getother() public view returns( uint _onceWidrawTime, uint newBuyPrice, uint _transper, uint _quit_interval, uint _quit_rate1, uint _quit_rate2 ){ _onceWidrawTime = OnceWidrawTime;//0 newBuyPrice = buyPrice;//1 _transper = transper; _quit_interval = quit_config.interval; _quit_rate1 = quit_config.rate1; _quit_rate2 = quit_config.rate2; } function setNodeProfit(uint _node,uint _members,uint _percert) public onlyOwner returns(bool){ //require(_node<=16&&_node>=1); require(_node>=1); require(_members>0&&_percert>0&&_percert<=100); node_profits[_node] = node_profit(_members,_percert); return true; } function setPlan(uint _plan,uint _account,uint _times) public onlyOwner returns(bool){ require(_plan<=4&&_plan>=1); require(_account>0&&_times>0); plans[_plan] = plan(_account,_times); return true; } function getPlan(uint _plan) public view returns(uint _account,uint _times){ require(_plan>0 && _plan <=4); _account=plans[_plan].account; _times = plans[_plan].times; } function getNodeProfit(uint _node) public view returns(uint _members,uint _percert){ require(_node>0 && _node <=16); _members = node_profits[_node].menber_counts; _percert = node_profits[_node].percent; } function setsysteam( uint _newteamPrice1, uint _newteamPrice2, uint teamper1s, uint teamper2s, uint t1, uint t2, uint t3, uint t4 ) public onlyOwner{ teamPrice1=_newteamPrice1; teamPrice2=_newteamPrice2; teamper1 = teamper1s; teamper2 = teamper2s; permans = [t1,t2,t3,t4]; } function getsysteam() public view returns( uint teamprice1, uint teamprice2, uint teamper1s, uint teamper2s, uint t1, uint t2, uint t3, uint t4 ){ teamprice1 = teamPrice1; teamprice2 = teamPrice2; teamper1s = teamper1;//4 teamper2s = teamper2;//5 t1 = permans[0];//6 t2 = permans[1];//7 t3 = permans[2];//8 t4 = permans[3];//9 } /* * 设置是否开启 * @param {Object} bool */ function setactive(bool tags) public onlyOwner { actived = tags; } function setadmin(address adminaddr) onlyOwner public { require(adminaddr != owner && adminaddr != address(0)); owner = adminaddr; } function setfinancer(address financeraddr) onlyOwner public { financer = financeraddr; } /* * 获取总发行 */ function totalSupply() public view returns(uint) { return _totalSupply; } function addusermoney(address target, uint256 mintedAmount) private{ require(!frozenAccount[target]); require(actived == true); require(balances[this] > mintedAmount); balances[target] = balances[target].add(mintedAmount); balances[this] = balances[this].sub(mintedAmount); emit Transfer(this, target, mintedAmount); } function subusermoney(address target, uint256 mintedAmount) private{ require(!frozenAccount[target]); require(actived == true); require(balances[target] > mintedAmount); balances[target] = balances[target].sub(mintedAmount); balances[this] = balances[this].add(mintedAmount); emit Transfer( target,this, mintedAmount); } /* * 向指定账户拨发资金 * @param {Object} address */ function adduser(address target, uint256 mintedAmount) public onlyFinancer{ addusermoney(target, mintedAmount); } function subuser(address target, uint256 mintedAmount) public onlyFinancer{ subusermoney(target, mintedAmount); } /* function interadduser(address target, uint256 mintedAmount) public onlyInterface{ addusermoney(target, mintedAmount); } function intersubuser(address target, uint256 mintedAmount) public onlyInterface{ subusermoney(target, mintedAmount); } */ function setteam(address user, uint amount) private returns(bool) { require(amount >0); teamget[user] += amount; if(suns[user].n_effective[2] >= permans[2] && suns[user].n_effective[1] >= permans[3]){ //teamget[user] += amount; uint chkmoney = teamPrice1; uint sendmoney = teamget[user]*teamper1/100; if(suns[user].n_effective[2] >= permans[0] && suns[user].n_effective[1] >= permans[1]){ chkmoney = teamPrice2; sendmoney = teamget[user]*teamper2/100; } if(teamget[user] >= chkmoney) { _update_user_inverst(user,sendmoney); teamget[user] = uint(0); } } return(true); } function _reset_user_inverst(address user) private returns(bool){ user_inverst_record[user].can_draw_capital = uint(0); user_inverst_record[user].not_draw_capital = uint(0); user_inverst_record[user].releasd_profit = uint(0); //user_inverst_record[user].last_investdate = uint(0); user_inverst_record[user].total_profit = uint(0); crontime[user]=uint(0); return(true); } function _update_user_inverst(address user,uint rewards) private returns(uint){ require(rewards >0); uint _mint_account; if(user_inverst_record[user].not_draw_capital==uint(0)){ return _mint_account; } /*剩余可释放*/ uint releasable = user_inverst_record[user].total_profit.sub(user_inverst_record[user].releasd_profit); if(releasable<=rewards){ _reset_user_inverst(user); _mint_account = releasable; } else{ /* 修改可提现本金 */ _mint_account = rewards; if(user_inverst_record[user].can_draw_capital>0){ if(user_inverst_record[user].can_draw_capital>rewards){ user_inverst_record[user].can_draw_capital=user_inverst_record[user].can_draw_capital.sub(rewards); } else{ user_inverst_record[user].can_draw_capital = uint(0); } } /* 修改已释放利润 */ user_inverst_record[user].releasd_profit += _mint_account; } require(balances[this]>= _mint_account); user_inverst_record[user].history_releasd_profit += _mint_account; balances[user] += _mint_account; balances[this] -= _mint_account; emit Transfer(this, user, _mint_account); return _mint_account; } function hasReward(address _user)public view returns(bool){ if(crontime[_user] <= now - OnceWidrawTime && crontime[_user]!=0){ return true; } else{ return false; } } function reward() public returns(bool){ require(actived == true&&!frozenAccount[msg.sender]); address user = msg.sender; require(crontime[user] <= now - OnceWidrawTime && crontime[user]!=0); /* 静态 */ uint rewards = user_inverst_record[user].not_draw_capital*per/1000; /*挖矿数量*/ uint _mint_account = _update_user_inverst(user,rewards); /* 动态 */ address top = fromaddr[user]; address _user = user; for(uint i=1;i<=generation;i++){ if(top != address(0) && top != _user){ if(suns[top].n_effective[1]>=node_profits[i].menber_counts){ uint upmoney = _mint_account*node_profits[i].percent/100; //settop(top, upmoney); _update_user_inverst(top,upmoney); //setteam(top,_mint_account); } _user = top; top = fromaddr[top]; continue; } break; } //团队业绩统计 _user = user; top = fromaddr[user]; for(uint n=1;n<=generation_team;n++){ if(top != address(0) && top != _user){ setteam(top,_mint_account); _user = top; top = fromaddr[top]; continue; } break; } /*修改下次提现时间*/ if(crontime[user]>uint(0)){ crontime[user] = now + OnceWidrawTime; } return true; } /* * 用户参与挖矿 */ function mint(uint _tokens) public { require(actived == true&&!frozenAccount[msg.sender]); address user = msg.sender; require(_tokens>=plans[1].account && balances[user]>=_tokens); require(!frozenAccount[user]); /*16代以内有效用户设置,可以改成N代*/ address top = fromaddr[user]; address _user = user; for(uint n=1;n<=16;n++){ if(top != address(0) && top !=_user){ if(!_effective_son[user] && n==1){ ++suns[top].n_effective[n]; _effective_son[user] = true; top = fromaddr[top]; continue; } else if(n >=2){ ++suns[top].n_effective[n]; _user = top; top = fromaddr[top]; continue; }else{ break; } } break; } /* 修改投资信息 */ user_inverst_record[user].can_draw_capital += _tokens; user_inverst_record[user].not_draw_capital += _tokens; user_inverst_record[user].last_investdate = now; /* 增加总投资利润 */ uint _profits; for(uint i=4;i>=1;i--){ if(_tokens >= plans[i].account){ _profits = plans[i].times * _tokens; break; } } user_inverst_record[user].total_profit += _profits; balances[user] -= _tokens; balances[this] += _tokens; crontime[user] = now + OnceWidrawTime; } function quitMint() public returns(bool){ require(actived == true&&!frozenAccount[msg.sender]); require(user_inverst_record[msg.sender].can_draw_capital > 0); uint interval = now.sub(user_inverst_record[msg.sender].last_investdate); uint rate = quit_config.rate2; if(interval<quit_config.interval){ rate = quit_config.rate1; } uint fee = user_inverst_record[msg.sender].can_draw_capital*rate/100; uint refund = user_inverst_record[msg.sender].can_draw_capital.sub(fee); _reset_user_inverst(msg.sender); require(balances[this]>=refund); balances[msg.sender] += refund; balances[this] -= refund; emit Transfer(this, msg.sender,refund); return(true); } function addleadereth(address _user,uint _ethvalue) private returns(bool){ address _ethtop = ethtop[_user]; if(_ethtop!=address(0) ){ leader_eth[_ethtop] += _ethvalue; } /* if(isleader[_user]){ leader_eth[_user] += _ethvalue; } */ /* address user = _user; address top = fromaddr[_user]; for(uint i=1;;i++){ if(top!=address(0)&&top!= user){ if(isleader[top]){ leader_eth[top] += _ethvalue; break; } (user,top)=(top,fromaddr[top]); continue; } break; } */ return(true); } function addLeader(address _leader) public onlyOwner returns(bool){ require(_leader!=address(0) && !isleader[_leader]); isleader[_leader] = true; leaders.push(_leader); return(true); } function subLeader(address _leader)public onlyOwner returns(bool){ require(_leader!=address(0) && isleader[_leader]); isleader[_leader] = false; return(true); } /* * */ function getleaders()public view returns(address [] memory _leaders,uint [] memory _eths){ uint l; for(uint i;i<leaders.length;i++){ if(isleader[leaders[i]]){ l++; } } address [] memory _leaders1 = new address[](l); uint [] memory _eths1 = new uint[](l); for(uint n;n<leaders.length;n++){ if(isleader[leaders[n]]){ l--; _leaders1[l] = leaders[n]; _eths1[l] = leader_eth[leaders[n]]; } } _eths = _eths1; _leaders = _leaders1; } function setEttTokenAddress(address _ett) public onlyOwner returns(bool){ require(_ett!=address(0) && _ett != address(this)); ett = EttToken(_ett); return true; } /* function setEttRate(uint _rate) public onlyOwner returns(bool){ require(_rate>0); ettRate = _rate; return true; } */ /* * sell usdt */ function usdt2ett(uint _tokens) public returns(bool){ require(actived); require(_tokens>0 && balances[msg.sender] >= _tokens); require(ett!=address(0)); uint _ettAmount = _tokens * ettRate / 1 ether; ett.tokenAdd(msg.sender,_ettAmount); balances[msg.sender] -= _tokens; emit Transfer(msg.sender,this,_tokens); return true; } /* * sell ett */ function ett2usdt(uint _tokens) public returns(bool){ require(actived); require(_tokens>0); require(ett!=address(0)); if(getettbalance(msg.sender)>= _tokens){ uint _usdts = _tokens*1 ether/ettRate; ett.tokenSub(msg.sender,_tokens); require(balances[this]> _usdts); balances[msg.sender] += _usdts; balances[this] -= _usdts; emit Transfer(this,msg.sender,_tokens); }else{ return false; } return true; } function getettbalance(address _user) public view returns(uint256 _balance){ require(ett!=address(0)); _balance = ett.balanceOf(_user); } /* * 获取总账目 */ function getall() public view returns(uint256 money) { money = address(this).balance; } /* * 购买 */ function buy() public payable returns(uint) { require(msg.value > 0 && actived); address user = msg.sender; require(!frozenAccount[user]); uint amount = msg.value * buyPrice/1 ether; require(balances[this] >= amount && amount < _totalSupply); balances[user] = balances[user].add(amount); sysinteth += msg.value; userineth[user] += msg.value; balances[this] = balances[this].sub(amount); addleadereth(user,msg.value); owner.transfer(msg.value); emit Transfer(this, user, amount); return(amount); } function() payable public { buy(); } /* * 批量发币 * @param {Object} address */ function addBalances(address[] recipients, uint256[] moenys) public onlyOwner{ uint256 sum = 0; for(uint256 i = 0; i < recipients.length; i++) { balances[recipients[i]] = balances[recipients[i]].add(moenys[i]); sum = sum.add(moenys[i]); emit Transfer(this, recipients[i], moenys[i]); } balances[this] = balances[this].sub(sum); } /* * 批量减币 * @param {Object} address */ function subBalances(address[] recipients, uint256[] moenys) public onlyOwner{ uint256 sum = 0; for(uint256 i = 0; i < recipients.length; i++) { balances[recipients[i]] = balances[recipients[i]].sub(moenys[i]); sum = sum.add(moenys[i]); emit Transfer(recipients[i], this, moenys[i]); } balances[this] = balances[this].add(sum); } }
16代以内有效用户设置,可以改成N代*/
function mint(uint _tokens) public { require(actived == true&&!frozenAccount[msg.sender]); address user = msg.sender; require(_tokens>=plans[1].account && balances[user]>=_tokens); require(!frozenAccount[user]); address top = fromaddr[user]; address _user = user; for(uint n=1;n<=16;n++){ if(top != address(0) && top !=_user){ if(!_effective_son[user] && n==1){ ++suns[top].n_effective[n]; _effective_son[user] = true; top = fromaddr[top]; continue; } else if(n >=2){ ++suns[top].n_effective[n]; _user = top; top = fromaddr[top]; continue; break; } } break; } user_inverst_record[user].not_draw_capital += _tokens; user_inverst_record[user].last_investdate = now; for(uint i=4;i>=1;i--){ if(_tokens >= plans[i].account){ _profits = plans[i].times * _tokens; break; } } user_inverst_record[user].total_profit += _profits; balances[user] -= _tokens; balances[this] += _tokens; crontime[user] = now + OnceWidrawTime; }
7,320,222
[ 1, 2313, 165, 124, 101, 165, 124, 103, 166, 233, 232, 167, 255, 236, 167, 248, 235, 168, 247, 106, 167, 235, 120, 169, 111, 127, 168, 126, 111, 176, 125, 239, 166, 242, 112, 165, 124, 103, 167, 247, 122, 167, 235, 243, 50, 165, 124, 101, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 445, 312, 474, 12, 11890, 389, 7860, 13, 1071, 288, 203, 202, 3196, 202, 6528, 12, 621, 2950, 422, 638, 10, 10, 5, 28138, 3032, 63, 3576, 18, 15330, 19226, 203, 202, 3196, 202, 2867, 729, 273, 1234, 18, 15330, 31, 203, 21114, 3196, 202, 6528, 24899, 7860, 34, 33, 412, 634, 63, 21, 8009, 4631, 597, 324, 26488, 63, 1355, 65, 34, 33, 67, 7860, 1769, 203, 202, 3196, 202, 6528, 12, 5, 28138, 3032, 63, 1355, 19226, 203, 9506, 203, 1082, 202, 2867, 1760, 273, 628, 4793, 63, 1355, 15533, 203, 1082, 202, 2867, 389, 1355, 273, 729, 31, 203, 1082, 202, 1884, 12, 11890, 290, 33, 21, 31, 82, 32, 33, 2313, 31, 82, 27245, 95, 202, 203, 9506, 202, 430, 12, 3669, 480, 1758, 12, 20, 13, 597, 1760, 480, 67, 1355, 15329, 203, 6862, 202, 430, 12, 5, 67, 28894, 67, 816, 63, 1355, 65, 597, 290, 631, 21, 15329, 203, 25083, 202, 9904, 16924, 87, 63, 3669, 8009, 82, 67, 28894, 63, 82, 15533, 203, 25083, 202, 67, 28894, 67, 816, 63, 1355, 65, 273, 638, 31, 203, 25083, 202, 3669, 273, 628, 4793, 63, 3669, 15533, 203, 25083, 202, 17143, 31, 1082, 203, 6862, 202, 97, 203, 6862, 202, 12107, 309, 12, 82, 1545, 22, 15329, 203, 25083, 202, 9904, 16924, 87, 63, 3669, 8009, 82, 67, 28894, 63, 82, 15533, 203, 25083, 202, 67, 1355, 273, 1760, 31, 203, 25083, 202, 3669, 273, 628, 4793, 63, 3669, 15533, 203, 25083, 202, 17143, 31, 203, 25083, 2 ]
pragma solidity ^0.4.24; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } 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 Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } 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; } } contract KAA is ERC20,Ownable{ using SafeMath for uint256; //the base info of the token string public constant name="KAA"; string public constant symbol="KAA"; string public constant version = "1.0"; uint256 public constant decimals = 18; //平台基金13395000000 uint256 public constant PLATFORM_FUNDING_SUPPLY=13395000000*10**decimals; //创始团队13395000000 uint256 public constant TEAM_KEEPING=13395000000*10**decimals; //战略伙伴8037000000 uint256 public constant COOPERATE_REWARD=8037000000*10**decimals; //分享奖励8930000000 uint256 public constant SHARDING_REWARD=8930000000*10**decimals; //挖矿奖励45543000000 uint256 public constant MINING_REWARD=45543000000*10**decimals; //可普通提现额度8930000000+45543000000=54473000000 uint256 public constant COMMON_WITHDRAW_SUPPLY=SHARDING_REWARD+MINING_REWARD; //总发行54473000000+13395000000+13395000000+8037000000=89300000000 uint256 public constant MAX_SUPPLY=COMMON_WITHDRAW_SUPPLY+PLATFORM_FUNDING_SUPPLY+TEAM_KEEPING+COOPERATE_REWARD; //基准时间 uint256 startTime; //解锁步长(30天) uint256 unlockStepLong; //平台已提现 uint256 platformFundingSupply; //平台每期可提现 uint256 platformFundingPerEpoch; //团队已提现 uint256 teamKeepingSupply; //团队每期可提现 uint256 teamKeepingPerEpoch; //战略伙伴已经分发额度 uint256 public cooperateRewardSupply; //已经普通提现量 uint256 public totalCommonWithdrawSupply; //战略伙伴锁仓总额度 mapping(address=>uint256) public lockAmount; //ERC20的余额 mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; constructor() public{ totalSupply = 0 ; platformFundingSupply=0; teamKeepingSupply=0; cooperateRewardSupply=0; totalCommonWithdrawSupply=0; platformFundingPerEpoch=372083333; teamKeepingPerEpoch=372083333; //初始时间 20180818 startTime = 1534521600; unlockStepLong=2592000; } event CreateKAA(address indexed _to, uint256 _value); modifier notReachTotalSupply(uint256 _value){ assert(MAX_SUPPLY>=totalSupply.add(_value)); _; } //平台最大提现额度 modifier notReachPlatformFundingSupply(uint256 _value){ assert(PLATFORM_FUNDING_SUPPLY>=platformFundingSupply.add(_value)); _; } modifier notReachTeamKeepingSupply(uint256 _value){ assert(TEAM_KEEPING>=teamKeepingSupply.add(_value)); _; } modifier notReachCooperateRewardSupply(uint256 _value){ assert(COOPERATE_REWARD>=cooperateRewardSupply.add(_value)); _; } modifier notReachCommonWithdrawSupply(uint256 _value){ assert(COMMON_WITHDRAW_SUPPLY>=totalCommonWithdrawSupply.add(_value)); _; } //统一代币分发函数,内部使用 function processFunding(address receiver,uint256 _value) internal notReachTotalSupply(_value) { uint256 amount=_value; totalSupply=totalSupply.add(amount); balances[receiver]=balances[receiver].add(amount); emit CreateKAA(receiver,amount); emit Transfer(0x0, receiver, amount); } //普通分发,给分享和挖矿使用 function commonWithdraw(uint256 _value) external onlyOwner notReachCommonWithdrawSupply(_value) { processFunding(msg.sender,_value); //增加已经普通提现份额 totalCommonWithdrawSupply=totalCommonWithdrawSupply.add(_value); } //平台基金提币(不持币锁仓,36期释放) function withdrawToPlatformFunding(uint256 _value) external onlyOwner notReachPlatformFundingSupply(_value) { //判断可提现额度是否足够 if (!canPlatformFundingWithdraw(_value)) { revert(); }else{ processFunding(msg.sender,_value); //平台已提现额度 platformFundingSupply=platformFundingSupply.add(_value); } } //团队提币(不持币锁仓,36期释放) function withdrawToTeam(uint256 _value) external onlyOwner notReachTeamKeepingSupply(_value) { //判断可提现额度是否足够 if (!canTeamKeepingWithdraw(_value)) { revert(); }else{ processFunding(msg.sender,_value); //团队已提现额度 teamKeepingSupply=teamKeepingSupply.add(_value); } } //提币给战略伙伴(持币锁仓,36期释放) function withdrawToCooperate(address _to,uint256 _value) external onlyOwner notReachCooperateRewardSupply(_value) { processFunding(_to,_value); cooperateRewardSupply=cooperateRewardSupply.add(_value); //记录分发份额 lockAmount[_to]=lockAmount[_to].add(_value); } //平台是否可提现 function canPlatformFundingWithdraw(uint256 _value)internal view returns (bool) { //当前期数=(现时间-初始时间)/期数步长 uint256 epoch=now.sub(startTime).div(unlockStepLong); //如果超出36期时间,那么就设置为36 if (epoch>36) { epoch=36; } //计算已经释放额度 = 每期可提现额度*期数 uint256 releaseAmount = platformFundingPerEpoch.mul(epoch); //计算可提现额度=已经释放额度-已经提现额度 uint256 canWithdrawAmount=releaseAmount.sub(platformFundingSupply); if(canWithdrawAmount>=_value){ return true; }else{ return false; } } function canTeamKeepingWithdraw(uint256 _value)internal view returns (bool) { //当前期数=(现时间-初始时间)/期数步长 uint256 epoch=now.sub(startTime).div(unlockStepLong); //如果超出36期时间,那么就设置为36 if (epoch>36) { epoch=36; } //计算已经释放额度 = 每期可提现额度*期数 uint256 releaseAmount=teamKeepingPerEpoch.mul(epoch); //计算可提现额度=已经释放额度-已经提现额度 uint256 canWithdrawAmount=releaseAmount.sub(teamKeepingSupply); if(canWithdrawAmount>=_value){ return true; }else{ return false; } } function clacCooperateNeedLockAmount(uint256 totalLockAmount)internal view returns (uint256) { //当前期数=(现时间-初始时间)/期数步长 uint256 epoch=now.sub(startTime).div(unlockStepLong); //如果超出36期时间,那么就设置为36 if (epoch>36) { epoch=36; } //剩余期数 uint256 remainingEpoch=uint256(36).sub(epoch); //计算每期可释放转账额度(总分发额度/36) uint256 cooperatePerEpoch= totalLockAmount.div(36); //计算剩余锁仓额度(每期可释放转账额度*剩余期数) return cooperatePerEpoch.mul(remainingEpoch); } function () payable external { revert(); } //转账前,先校验减去转出份额后,是否大于等于锁仓份额 function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); //计算锁仓份额 uint256 needLockBalance=0; if (lockAmount[msg.sender]>0) { needLockBalance=clacCooperateNeedLockAmount(lockAmount[msg.sender]); } require(balances[msg.sender].sub(_value)>=needLockBalance); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } //从委托人账上转出份额时,还要判断委托人的余额-转出份额是否大于等于锁仓份额 function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); //计算锁仓份额 uint256 needLockBalance=0; if (lockAmount[_from]>0) { needLockBalance=clacCooperateNeedLockAmount(lockAmount[_from]); } require(balances[_from].sub(_value)>=needLockBalance); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
计算可提现额度=已经释放额度-已经提现额度
uint256 canWithdrawAmount=releaseAmount.sub(teamKeepingSupply);
13,952,506
[ 1, 169, 111, 99, 168, 111, 250, 166, 242, 112, 167, 242, 243, 168, 241, 113, 170, 100, 256, 166, 123, 104, 33, 166, 120, 115, 168, 124, 242, 170, 234, 237, 167, 247, 127, 170, 100, 256, 166, 123, 104, 17, 166, 120, 115, 168, 124, 242, 167, 242, 243, 168, 241, 113, 170, 100, 256, 166, 123, 104, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 11890, 5034, 848, 1190, 9446, 6275, 33, 9340, 6275, 18, 1717, 12, 10035, 11523, 310, 3088, 1283, 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 ]
./partial_match/1/0x2A168c00310451E7024E1149A433c796c72d515D/sources/CheatmoonToken.sol
Withdraw specified amount of staked tokens
function withdraw(uint256 _amount) external nonReentrant { require( stakers[msg.sender].deposited >= _amount, "Can't withdraw more than you have" ); uint256 _rewards = calculateRewards(msg.sender); stakers[msg.sender].deposited -= _amount; stakers[msg.sender].timeOfLastUpdate = block.timestamp; stakers[msg.sender].unclaimedRewards = _rewards; _mint(msg.sender, _amount); }
9,188,007
[ 1, 1190, 9446, 1269, 3844, 434, 384, 9477, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 8949, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 203, 5411, 384, 581, 414, 63, 3576, 18, 15330, 8009, 323, 1724, 329, 1545, 389, 8949, 16, 203, 5411, 315, 2568, 1404, 598, 9446, 1898, 2353, 1846, 1240, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 389, 266, 6397, 273, 4604, 17631, 14727, 12, 3576, 18, 15330, 1769, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 323, 1724, 329, 3947, 389, 8949, 31, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 957, 951, 3024, 1891, 273, 1203, 18, 5508, 31, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 551, 80, 4581, 329, 17631, 14727, 273, 389, 266, 6397, 31, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.8; library BlockVerifier { function extractStateRootAndTimestamp(bytes memory rlpBytes, bytes32 blockHash) internal view returns (bytes32 stateRoot, uint256 blockTimestamp, uint256 blockNumber) { assembly { function revertWithReason(message, length) { mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(4, 0x20) mstore(0x24, length) mstore(0x44, message) revert(0, add(0x44, length)) } function readDynamic(prefixPointer) -> dataPointer, dataLength { let value := byte(0, mload(prefixPointer)) switch lt(value, 0x80) case 1 { dataPointer := prefixPointer dataLength := 1 } case 0 { dataPointer := add(prefixPointer, 1) dataLength := sub(value, 0x80) } } // get the length of the data let rlpLength := mload(rlpBytes) // move pointer forward, ahead of length rlpBytes := add(rlpBytes, 0x20) // we know the length of the block will be between 483 bytes and 709 bytes, which means it will have 2 length bytes after the prefix byte, so we can skip 3 bytes in // CONSIDER: we could save a trivial amount of gas by compressing most of this into a single add instruction let parentHashPrefixPointer := add(rlpBytes, 3) let parentHashPointer := add(parentHashPrefixPointer, 1) let uncleHashPrefixPointer := add(parentHashPointer, 32) let uncleHashPointer := add(uncleHashPrefixPointer, 1) let minerAddressPrefixPointer := add(uncleHashPointer, 32) let minerAddressPointer := add(minerAddressPrefixPointer, 1) let stateRootPrefixPointer := add(minerAddressPointer, 20) let stateRootPointer := add(stateRootPrefixPointer, 1) let transactionRootPrefixPointer := add(stateRootPointer, 32) let transactionRootPointer := add(transactionRootPrefixPointer, 1) let receiptsRootPrefixPointer := add(transactionRootPointer, 32) let receiptsRootPointer := add(receiptsRootPrefixPointer, 1) let logsBloomPrefixPointer := add(receiptsRootPointer, 32) let logsBloomPointer := add(logsBloomPrefixPointer, 3) let difficultyPrefixPointer := add(logsBloomPointer, 256) let difficultyPointer, difficultyLength := readDynamic(difficultyPrefixPointer) let blockNumberPrefixPointer := add(difficultyPointer, difficultyLength) let blockNumberPointer, blockNumberLength := readDynamic(blockNumberPrefixPointer) let gasLimitPrefixPointer := add(blockNumberPointer, blockNumberLength) let gasLimitPointer, gasLimitLength := readDynamic(gasLimitPrefixPointer) let gasUsedPrefixPointer := add(gasLimitPointer, gasLimitLength) let gasUsedPointer, gasUsedLength := readDynamic(gasUsedPrefixPointer) let timestampPrefixPointer := add(gasUsedPointer, gasUsedLength) let timestampPointer, timestampLength := readDynamic(timestampPrefixPointer) blockNumber := shr(sub(256, mul(blockNumberLength, 8)), mload(blockNumberPointer)) let rlpHash := keccak256(rlpBytes, rlpLength) if iszero(eq(blockHash, rlpHash)) { revertWithReason("blockHash != rlpHash", 20) } stateRoot := mload(stateRootPointer) blockTimestamp := shr(sub(256, mul(timestampLength, 8)), mload(timestampPointer)) } } } pragma solidity 0.6.8; pragma experimental ABIEncoderV2; import { BlockVerifier } from "./BlockVerifier.sol"; import { MerklePatriciaVerifier } from "./MerklePatriciaVerifier.sol"; import { Rlp } from "./Rlp.sol"; import { IUniswapV2Pair } from "./IUniswapV2Pair.sol"; import { UQ112x112 } from "./UQ112x112.sol"; contract SushiOracle { using UQ112x112 for uint224; bytes32 public constant reserveTimestampSlotHash = keccak256(abi.encodePacked(uint256(8))); bytes32 public constant token0Slot = keccak256(abi.encodePacked(uint256(9))); bytes32 public constant token1Slot = keccak256(abi.encodePacked(uint256(10))); struct ProofData { bytes block; bytes accountProofNodesRlp; bytes reserveAndTimestampProofNodesRlp; bytes priceAccumulatorProofNodesRlp; } function getAccountStorageRoot(address uniswapV2Pair, ProofData memory proofData, bytes32 blockHash) public view returns (bytes32 storageRootHash, uint256 blockNumber, uint256 blockTimestamp) { bytes32 stateRoot; (stateRoot, blockTimestamp, blockNumber) = BlockVerifier.extractStateRootAndTimestamp(proofData.block, blockHash); bytes memory accountDetailsBytes = MerklePatriciaVerifier.getValueFromProof(stateRoot, keccak256(abi.encodePacked(uniswapV2Pair)), proofData.accountProofNodesRlp); Rlp.Item[] memory accountDetails = Rlp.toList(Rlp.toItem(accountDetailsBytes)); return (Rlp.toBytes32(accountDetails[2]), blockNumber, blockTimestamp); } // This function verifies the full block is old enough (MIN_BLOCK_COUNT), not too old (or blockhash will return 0x0) and return the proof values for the two storage slots we care about function verifyBlockAndExtractReserveData(IUniswapV2Pair uniswapV2Pair, bytes32 slotHash, ProofData memory proofData, bytes32 blockHash) public view returns (uint256 blockTimestamp, uint256 blockNumber, uint256 priceCumulativeLast, uint112 reserve0, uint112 reserve1, uint256 reserveTimestamp) { bytes32 storageRootHash; (storageRootHash, blockNumber, blockTimestamp) = getAccountStorageRoot(address(uniswapV2Pair), proofData, blockHash); // require (blockNumber <= block.number - minBlocksBack, "Proof does not span enough blocks"); // require (blockNumber >= block.number - maxBlocksBack, "Proof spans too many blocks"); priceCumulativeLast = Rlp.rlpBytesToUint256(MerklePatriciaVerifier.getValueFromProof(storageRootHash, slotHash, proofData.priceAccumulatorProofNodesRlp)); uint256 reserve0Reserve1TimestampPacked = Rlp.rlpBytesToUint256(MerklePatriciaVerifier.getValueFromProof(storageRootHash, reserveTimestampSlotHash, proofData.reserveAndTimestampProofNodesRlp)); reserveTimestamp = reserve0Reserve1TimestampPacked >> (112 + 112); reserve1 = uint112((reserve0Reserve1TimestampPacked >> 112) & (2**112 - 1)); reserve0 = uint112(reserve0Reserve1TimestampPacked & (2**112 - 1)); } function getPrice(IUniswapV2Pair uniswapV2Pair, address denominationToken, uint256 blockNum, ProofData memory proofData) public view returns (uint256 price, uint256 blockNumber) { // exchange = the ExchangeV2Pair. check denomination token (USE create2 check?!) check gas cost bool denominationTokenIs0 = true; if (uniswapV2Pair.token0() == denominationToken) { denominationTokenIs0 = true; } else if (uniswapV2Pair.token1() == denominationToken) { denominationTokenIs0 = false; } else { revert("denominationToken invalid"); } return getPriceRaw(uniswapV2Pair, denominationTokenIs0, proofData, blockhash(blockNum)); } function getPriceRaw(IUniswapV2Pair uniswapV2Pair, bool denominationTokenIs0, ProofData memory proofData, bytes32 blockHash) public view returns (uint256 price, uint256 blockNumber) { uint256 historicBlockTimestamp; uint256 historicPriceCumulativeLast; { // Stack-too-deep workaround, manual scope // Side-note: wtf Solidity? uint112 reserve0; uint112 reserve1; uint256 reserveTimestamp; (historicBlockTimestamp, blockNumber, historicPriceCumulativeLast, reserve0, reserve1, reserveTimestamp) = verifyBlockAndExtractReserveData(uniswapV2Pair, denominationTokenIs0 ? token1Slot : token0Slot, proofData, blockHash); uint256 secondsBetweenReserveUpdateAndHistoricBlock = historicBlockTimestamp - reserveTimestamp; // bring old record up-to-date, in case there was no cumulative update in provided historic block itself if (secondsBetweenReserveUpdateAndHistoricBlock > 0) { historicPriceCumulativeLast += secondsBetweenReserveUpdateAndHistoricBlock * uint(UQ112x112 .encode(denominationTokenIs0 ? reserve0 : reserve1) .uqdiv(denominationTokenIs0 ? reserve1 : reserve0) ); } } uint256 secondsBetweenProvidedBlockAndNow = block.timestamp - historicBlockTimestamp; price = (getCurrentPriceCumulativeLast(uniswapV2Pair, denominationTokenIs0) - historicPriceCumulativeLast) / secondsBetweenProvidedBlockAndNow; return (price, blockNumber); } function getCurrentPriceCumulativeLast(IUniswapV2Pair uniswapV2Pair, bool denominationTokenIs0) public view returns (uint256 priceCumulativeLast) { (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = uniswapV2Pair.getReserves(); priceCumulativeLast = denominationTokenIs0 ? uniswapV2Pair.price1CumulativeLast() : uniswapV2Pair.price0CumulativeLast(); uint256 timeElapsed = block.timestamp - blockTimestampLast; priceCumulativeLast += timeElapsed * uint(UQ112x112 .encode(denominationTokenIs0 ? reserve0 : reserve1) .uqdiv(denominationTokenIs0 ? reserve1 : reserve0) ); } } pragma solidity 0.6.8; import { Rlp } from "./Rlp.sol"; library MerklePatriciaVerifier { /* * @dev Extracts the value from a merkle proof * @param expectedRoot The expected hash of the root node of the trie. * @param path The path in the trie leading to value. * @param proofNodesRlp RLP encoded array of proof nodes. * @return The value proven to exist in the merkle patricia tree whose root is `expectedRoot` at the path `path` * * WARNING: Does not currently support validation of unset/0 values! */ function getValueFromProof(bytes32 expectedRoot, bytes32 path, bytes memory proofNodesRlp) internal pure returns (bytes memory) { Rlp.Item memory rlpParentNodes = Rlp.toItem(proofNodesRlp); Rlp.Item[] memory parentNodes = Rlp.toList(rlpParentNodes); bytes memory currentNode; Rlp.Item[] memory currentNodeList; bytes32 nodeKey = expectedRoot; uint pathPtr = 0; // our input is a 32-byte path, but we have to prepend a single 0 byte to that and pass it along as a 33 byte memory array since that is what getNibbleArray wants bytes memory nibblePath = new bytes(33); assembly { mstore(add(nibblePath, 33), path) } nibblePath = _getNibbleArray(nibblePath); require(path.length != 0, "empty path provided"); currentNode = Rlp.toBytes(parentNodes[0]); for (uint i=0; i<parentNodes.length; i++) { require(pathPtr <= nibblePath.length, "Path overflow"); currentNode = Rlp.toBytes(parentNodes[i]); require(nodeKey == keccak256(currentNode), "node doesn't match key"); currentNodeList = Rlp.toList(parentNodes[i]); if(currentNodeList.length == 17) { if(pathPtr == nibblePath.length) { return Rlp.toData(currentNodeList[16]); } uint8 nextPathNibble = uint8(nibblePath[pathPtr]); require(nextPathNibble <= 16, "nibble too long"); nodeKey = Rlp.toBytes32(currentNodeList[nextPathNibble]); pathPtr += 1; } else if(currentNodeList.length == 2) { pathPtr += _nibblesToTraverse(Rlp.toData(currentNodeList[0]), nibblePath, pathPtr); // leaf node if(pathPtr == nibblePath.length) { return Rlp.toData(currentNodeList[1]); } //extension node require(_nibblesToTraverse(Rlp.toData(currentNodeList[0]), nibblePath, pathPtr) != 0, "invalid extension node"); nodeKey = Rlp.toBytes32(currentNodeList[1]); } else { require(false, "unexpected length array"); } } require(false, "not enough proof nodes"); } function _nibblesToTraverse(bytes memory encodedPartialPath, bytes memory path, uint pathPtr) private pure returns (uint) { uint len; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for(uint i=pathPtr; i<pathPtr+partialPath.length; i++) { byte pathNibble = path[i]; slicedPath[i-pathPtr] = pathNibble; } if(keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes byteArray must be hp encoded function _getNibbleArray(bytes memory byteArray) private pure returns (bytes memory) { bytes memory nibbleArray; if (byteArray.length == 0) return nibbleArray; uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0,byteArray)); if(hpNibble == 1 || hpNibble == 3) { nibbleArray = new bytes(byteArray.length*2-1); byte oddNibble = _getNthNibbleOfBytes(1,byteArray); nibbleArray[0] = oddNibble; offset = 1; } else { nibbleArray = new bytes(byteArray.length*2-2); offset = 0; } for(uint i=offset; i<nibbleArray.length; i++) { nibbleArray[i] = _getNthNibbleOfBytes(i-offset+2,byteArray); } return nibbleArray; } function _getNthNibbleOfBytes(uint n, bytes memory str) private pure returns (byte) { return byte(n%2==0 ? uint8(str[n/2])/0x10 : uint8(str[n/2])%0x10); } } pragma solidity 0.6.8; library Rlp { uint constant DATA_SHORT_START = 0x80; uint constant DATA_LONG_START = 0xB8; uint constant LIST_SHORT_START = 0xC0; uint constant LIST_LONG_START = 0xF8; uint constant DATA_LONG_OFFSET = 0xB7; uint constant LIST_LONG_OFFSET = 0xF7; struct Item { uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes. uint _unsafe_length; // Number of bytes. This is the full length of the string. } struct Iterator { Item _unsafe_item; // Item that's being iterated over. uint _unsafe_nextPtr; // Position of the next item in the list. } /* Iterator */ function next(Iterator memory self) internal pure returns (Item memory subItem) { require(hasNext(self), "Rlp.sol:Rlp:next:1"); uint256 ptr = self._unsafe_nextPtr; uint256 itemLength = _itemLength(ptr); subItem._unsafe_memPtr = ptr; subItem._unsafe_length = itemLength; self._unsafe_nextPtr = ptr + itemLength; } function next(Iterator memory self, bool strict) internal pure returns (Item memory subItem) { subItem = next(self); require(!strict || _validate(subItem), "Rlp.sol:Rlp:next:2"); } function hasNext(Iterator memory self) internal pure returns (bool) { Rlp.Item memory item = self._unsafe_item; return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length; } /* Item */ /// @dev Creates an Item from an array of RLP encoded bytes. /// @param self The RLP encoded bytes. /// @return An Item function toItem(bytes memory self) internal pure returns (Item memory) { uint len = self.length; if (len == 0) { return Item(0, 0); } uint memPtr; assembly { memPtr := add(self, 0x20) } return Item(memPtr, len); } /// @dev Creates an Item from an array of RLP encoded bytes. /// @param self The RLP encoded bytes. /// @param strict Will throw if the data is not RLP encoded. /// @return An Item function toItem(bytes memory self, bool strict) internal pure returns (Item memory) { Rlp.Item memory item = toItem(self); if(strict) { uint len = self.length; require(_payloadOffset(item) <= len, "Rlp.sol:Rlp:toItem4"); require(_itemLength(item._unsafe_memPtr) == len, "Rlp.sol:Rlp:toItem:5"); require(_validate(item), "Rlp.sol:Rlp:toItem:6"); } return item; } /// @dev Check if the Item is null. /// @param self The Item. /// @return 'true' if the item is null. function isNull(Item memory self) internal pure returns (bool) { return self._unsafe_length == 0; } /// @dev Check if the Item is a list. /// @param self The Item. /// @return 'true' if the item is a list. function isList(Item memory self) internal pure returns (bool) { if (self._unsafe_length == 0) return false; uint memPtr = self._unsafe_memPtr; bool result; assembly { result := iszero(lt(byte(0, mload(memPtr)), 0xC0)) } return result; } /// @dev Check if the Item is data. /// @param self The Item. /// @return 'true' if the item is data. function isData(Item memory self) internal pure returns (bool) { if (self._unsafe_length == 0) return false; uint memPtr = self._unsafe_memPtr; bool result; assembly { result := lt(byte(0, mload(memPtr)), 0xC0) } return result; } /// @dev Check if the Item is empty (string or list). /// @param self The Item. /// @return result 'true' if the item is null. function isEmpty(Item memory self) internal pure returns (bool) { if(isNull(self)) return false; uint b0; uint memPtr = self._unsafe_memPtr; assembly { b0 := byte(0, mload(memPtr)) } return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START); } /// @dev Get the number of items in an RLP encoded list. /// @param self The Item. /// @return The number of items. function items(Item memory self) internal pure returns (uint) { if (!isList(self)) return 0; uint b0; uint memPtr = self._unsafe_memPtr; assembly { b0 := byte(0, mload(memPtr)) } uint pos = memPtr + _payloadOffset(self); uint last = memPtr + self._unsafe_length - 1; uint itms; while(pos <= last) { pos += _itemLength(pos); itms++; } return itms; } /// @dev Create an iterator. /// @param self The Item. /// @return An 'Iterator' over the item. function iterator(Item memory self) internal pure returns (Iterator memory) { require(isList(self), "Rlp.sol:Rlp:iterator:1"); uint ptr = self._unsafe_memPtr + _payloadOffset(self); Iterator memory it; it._unsafe_item = self; it._unsafe_nextPtr = ptr; return it; } /// @dev Return the RLP encoded bytes. /// @param self The Item. /// @return The bytes. function toBytes(Item memory self) internal pure returns (bytes memory) { uint256 len = self._unsafe_length; require(len != 0, "Rlp.sol:Rlp:toBytes:2"); bytes memory bts; bts = new bytes(len); _copyToBytes(self._unsafe_memPtr, bts, len); return bts; } /// @dev Decode an Item into bytes. This will not work if the /// Item is a list. /// @param self The Item. /// @return The decoded string. function toData(Item memory self) internal pure returns (bytes memory) { require(isData(self)); (uint256 rStartPos, uint256 len) = _decode(self); bytes memory bts; bts = new bytes(len); _copyToBytes(rStartPos, bts, len); return bts; } /// @dev Get the list of sub-items from an RLP encoded list. /// Warning: This is inefficient, as it requires that the list is read twice. /// @param self The Item. /// @return Array of Items. function toList(Item memory self) internal pure returns (Item[] memory) { require(isList(self), "Rlp.sol:Rlp:toList:1"); uint256 numItems = items(self); Item[] memory list = new Item[](numItems); Rlp.Iterator memory it = iterator(self); uint idx; while(hasNext(it)) { list[idx] = next(it); idx++; } return list; } /// @dev Decode an Item into an ascii string. This will not work if the /// Item is a list. /// @param self The Item. /// @return The decoded string. function toAscii(Item memory self) internal pure returns (string memory) { require(isData(self), "Rlp.sol:Rlp:toAscii:1"); (uint256 rStartPos, uint256 len) = _decode(self); bytes memory bts = new bytes(len); _copyToBytes(rStartPos, bts, len); string memory str = string(bts); return str; } /// @dev Decode an Item into a uint. This will not work if the /// Item is a list. /// @param self The Item. /// @return The decoded string. function toUint(Item memory self) internal pure returns (uint) { require(isData(self), "Rlp.sol:Rlp:toUint:1"); (uint256 rStartPos, uint256 len) = _decode(self); require(len <= 32, "Rlp.sol:Rlp:toUint:3"); require(len != 0, "Rlp.sol:Rlp:toUint:4"); uint data; assembly { data := div(mload(rStartPos), exp(256, sub(32, len))) } return data; } /// @dev Decode an Item into a boolean. This will not work if the /// Item is a list. /// @param self The Item. /// @return The decoded string. function toBool(Item memory self) internal pure returns (bool) { require(isData(self), "Rlp.sol:Rlp:toBool:1"); (uint256 rStartPos, uint256 len) = _decode(self); require(len == 1, "Rlp.sol:Rlp:toBool:3"); uint temp; assembly { temp := byte(0, mload(rStartPos)) } require(temp <= 1, "Rlp.sol:Rlp:toBool:8"); return temp == 1 ? true : false; } /// @dev Decode an Item into a byte. This will not work if the /// Item is a list. /// @param self The Item. /// @return The decoded string. function toByte(Item memory self) internal pure returns (byte) { require(isData(self), "Rlp.sol:Rlp:toByte:1"); (uint256 rStartPos, uint256 len) = _decode(self); require(len == 1, "Rlp.sol:Rlp:toByte:3"); byte temp; assembly { temp := byte(0, mload(rStartPos)) } return byte(temp); } /// @dev Decode an Item into an int. This will not work if the /// Item is a list. /// @param self The Item. /// @return The decoded string. function toInt(Item memory self) internal pure returns (int) { return int(toUint(self)); } /// @dev Decode an Item into a bytes32. This will not work if the /// Item is a list. /// @param self The Item. /// @return The decoded string. function toBytes32(Item memory self) internal pure returns (bytes32) { return bytes32(toUint(self)); } /// @dev Decode an Item into an address. This will not work if the /// Item is a list. /// @param self The Item. /// @return The decoded string. function toAddress(Item memory self) internal pure returns (address) { require(isData(self), "Rlp.sol:Rlp:toAddress:1"); (uint256 rStartPos, uint256 len) = _decode(self); require(len == 20, "Rlp.sol:Rlp:toAddress:3"); address data; assembly { data := div(mload(rStartPos), exp(256, 12)) } return data; } // Get the payload offset. function _payloadOffset(Item memory self) private pure returns (uint) { if(self._unsafe_length == 0) return 0; uint b0; uint memPtr = self._unsafe_memPtr; assembly { b0 := byte(0, mload(memPtr)) } if(b0 < DATA_SHORT_START) return 0; if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START)) return 1; if(b0 < LIST_SHORT_START) return b0 - DATA_LONG_OFFSET + 1; return b0 - LIST_LONG_OFFSET + 1; } // Get the full length of an Item. function _itemLength(uint memPtr) private pure returns (uint len) { uint b0; assembly { b0 := byte(0, mload(memPtr)) } if (b0 < DATA_SHORT_START) len = 1; else if (b0 < DATA_LONG_START) len = b0 - DATA_SHORT_START + 1; else if (b0 < LIST_SHORT_START) { assembly { let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET) let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length len := add(1, add(bLen, dLen)) // total length } } else if (b0 < LIST_LONG_START) len = b0 - LIST_SHORT_START + 1; else { assembly { let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET) let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length len := add(1, add(bLen, dLen)) // total length } } } // Get start position and length of the data. function _decode(Item memory self) private pure returns (uint memPtr, uint len) { require(isData(self), "Rlp.sol:Rlp:_decode:1"); uint b0; uint start = self._unsafe_memPtr; assembly { b0 := byte(0, mload(start)) } if (b0 < DATA_SHORT_START) { memPtr = start; len = 1; return (memPtr, len); } if (b0 < DATA_LONG_START) { len = self._unsafe_length - 1; memPtr = start + 1; } else { uint bLen; assembly { bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET } len = self._unsafe_length - 1 - bLen; memPtr = start + bLen + 1; } return (memPtr, len); } // Assumes that enough memory has been allocated to store in target. function _copyToBytes(uint sourceBytes, bytes memory destinationBytes, uint btsLen) internal pure { // Exploiting the fact that 'tgt' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. assembly { let words := div(add(btsLen, 31), 32) let sourcePointer := sourceBytes let destinationPointer := add(destinationBytes, 32) for { let i := 0 } lt(i, words) { i := add(i, 1) } { let offset := mul(i, 32) mstore(add(destinationPointer, offset), mload(add(sourcePointer, offset))) } mstore(add(destinationBytes, add(32, mload(destinationBytes))), 0) } } // Check that an Item is valid. function _validate(Item memory self) private pure returns (bool ret) { // Check that RLP is well-formed. uint b0; uint b1; uint memPtr = self._unsafe_memPtr; assembly { b0 := byte(0, mload(memPtr)) b1 := byte(1, mload(memPtr)) } if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START) return false; return true; } function rlpBytesToUint256(bytes memory source) internal pure returns (uint256 result) { return Rlp.toUint(Rlp.toItem(source)); } } pragma solidity 0.6.8; interface IUniswapV2Pair { function token0() external view returns (address); function token1() external view returns (address); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast); } pragma solidity 0.6.8; // https://raw.githubusercontent.com/Uniswap/uniswap-v2-core/master/contracts/libraries/UQ112x112.sol // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } }
exchange = the ExchangeV2Pair. check denomination token (USE create2 check?!) check gas cost
function getPrice(IUniswapV2Pair uniswapV2Pair, address denominationToken, uint256 blockNum, ProofData memory proofData) public view returns (uint256 price, uint256 blockNumber) { bool denominationTokenIs0 = true; if (uniswapV2Pair.token0() == denominationToken) { denominationTokenIs0 = true; denominationTokenIs0 = false; revert("denominationToken invalid"); } return getPriceRaw(uniswapV2Pair, denominationTokenIs0, proofData, blockhash(blockNum)); }
13,871,042
[ 1, 16641, 273, 326, 18903, 58, 22, 4154, 18, 866, 10716, 1735, 1147, 261, 8001, 752, 22, 866, 35, 24949, 866, 16189, 6991, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 25930, 12, 45, 984, 291, 91, 438, 58, 22, 4154, 640, 291, 91, 438, 58, 22, 4154, 16, 1758, 10716, 1735, 1345, 16, 2254, 5034, 1203, 2578, 16, 1186, 792, 751, 3778, 14601, 751, 13, 1071, 1476, 1135, 261, 11890, 5034, 6205, 16, 2254, 5034, 1203, 1854, 13, 288, 203, 202, 202, 6430, 10716, 1735, 1345, 2520, 20, 273, 638, 31, 203, 202, 202, 430, 261, 318, 291, 91, 438, 58, 22, 4154, 18, 2316, 20, 1435, 422, 10716, 1735, 1345, 13, 288, 203, 1082, 202, 13002, 362, 1735, 1345, 2520, 20, 273, 638, 31, 203, 1082, 202, 13002, 362, 1735, 1345, 2520, 20, 273, 629, 31, 203, 1082, 202, 266, 1097, 2932, 13002, 362, 1735, 1345, 2057, 8863, 203, 202, 202, 97, 203, 202, 202, 2463, 25930, 4809, 12, 318, 291, 91, 438, 58, 22, 4154, 16, 10716, 1735, 1345, 2520, 20, 16, 14601, 751, 16, 1203, 2816, 12, 2629, 2578, 10019, 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 ]
./partial_match/1313161554/0xc36810Ad3980c08a40FDde4C47e9f7913bc1f7e4/sources/Erc20Token.sol
* Atomically increases the allowance granted to `spender` by the sender(caller). Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./
function increaseApproval(address _spender, uint _addedValue) validAddress(_spender, "_spender is not valid address") public returns (bool) { allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; }
16,941,737
[ 1, 3641, 6478, 7033, 3304, 326, 1699, 1359, 17578, 358, 1375, 87, 1302, 264, 68, 635, 326, 5793, 12, 16140, 2934, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 29076, 30, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10929, 23461, 12, 2867, 389, 87, 1302, 264, 16, 2254, 389, 9665, 620, 13, 923, 1887, 24899, 87, 1302, 264, 16, 4192, 87, 1302, 264, 353, 486, 923, 1758, 7923, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 1699, 6872, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 1699, 6872, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 8009, 1289, 24899, 9665, 620, 1769, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 1699, 6872, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 19226, 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 ]
./full_match/4/0xED3Af2bc053C9A3232d752dD3D51ee6aEbFDf625/sources/contracts/Slimeys.sol
2000 - 2999 : 0.03 ETH
return 0.03 ether;
699,716
[ 1, 17172, 300, 576, 11984, 225, 294, 225, 374, 18, 4630, 565, 512, 2455, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 327, 374, 18, 4630, 225, 2437, 31, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/ICLR.sol"; import "./interfaces/IStakedCLRToken.sol"; import "./interfaces/IRewardEscrow.sol"; import "./interfaces/IxTokenManager.sol"; import "./interfaces/IProxyAdmin.sol"; import "./CLRDeployer.sol"; /** * Liquidity Mining Terminal * Core Management contract for LM Programs */ contract LMTerminal is Initializable, OwnableUpgradeable { using SafeMath for uint256; using SafeERC20 for IERC20; // -- State Variables -- IRewardEscrow public rewardEscrow; // Contract for token vesting after deployment ICLR[] public deployedCLRPools; uint256 public deploymentFee; // Flat CLR pool deployment fee in ETH uint256 public rewardFee; // Fee applied on initiating rewards program as a fee divisor (100 = 1%) uint256 public tradeFee; // Fee applied when collecting CLR fees as a fee divisor (100 = 1%) mapping(address => uint256) public customDeploymentFee; // Premium deployment fees for select partners mapping(address => bool) public customDeploymentFeeEnabled; // True if premium fee is enabled CLRDeployer public clrDeployer; // Deployer contract for CLR pools and Staked CLR Tokens IxTokenManager public xTokenManager; // xTokenManager contract address public proxyAdmin; // Proxy Admin of CLR instances IUniswapV3Factory public uniswapFactory; // Uniswap V3 Factory Contract INonfungiblePositionManager public positionManager; // Uniswap V3 Position Manager contract ICLR.UniswapContracts public uniContracts; // Uniswap V3 Contracts // -- Structs -- struct PositionTicks { int24 lowerTick; int24 upperTick; } struct RewardsProgram { address[] rewardTokens; uint256 vestingPeriod; } struct PoolDetails { uint24 fee; address token0; address token1; uint256 amount0; uint256 amount1; } // -- Events -- // Management event DeployedUniV3Pool( address indexed pool, address indexed token0, address indexed token1, uint24 fee ); event DeployedIncentivizedPool( address indexed clrInstance, address indexed token0, address indexed token1, uint24 fee, int24 lowerTick, int24 upperTick ); event InitiatedRewardsProgram( address indexed clrInstance, address[] rewardTokens, uint256[] totalRewardAmounts, uint256 rewardsDuration ); event TokenFeeWithdraw(address indexed token, uint256 amount); event EthFeeWithdraw(uint256 amount); // --- Management functions --- function initialize( address _xTokenManager, address _rewardEscrow, address _proxyAdmin, address _clrDeployer, address _uniswapFactory, ICLR.UniswapContracts memory _uniContracts, uint256 _deploymentFee, uint256 _rewardFee, uint256 _tradeFee ) external initializer { __Ownable_init(); xTokenManager = IxTokenManager(_xTokenManager); rewardEscrow = IRewardEscrow(_rewardEscrow); proxyAdmin = _proxyAdmin; clrDeployer = CLRDeployer(_clrDeployer); positionManager = INonfungiblePositionManager( _uniContracts.positionManager ); uniswapFactory = IUniswapV3Factory(_uniswapFactory); uniContracts = _uniContracts; deploymentFee = _deploymentFee; rewardFee = _rewardFee; tradeFee = _tradeFee; } /** * @notice Deploys a uniswap pool in case there isn't one * * @param token0 address of token 0 * @param token1 address of token 1 * @param fee pool fee (500 = 0.05%, 3000 = 0.3%, 10000 = 1%) * @param initPrice initial pool price */ function deployUniswapPool( address token0, address token1, uint24 fee, uint160 initPrice ) external returns (address pool) { if (token0 > token1) { (token0, token1) = (token1, token0); } pool = positionManager.createAndInitializePoolIfNecessary( token0, token1, fee, initPrice ); emit DeployedUniV3Pool(pool, token0, token1, fee); } /** * @notice Deploys a Uni V3 pool which is incentivized by a given token * @notice LP Stakers will receive a portion of the totalRewardsAmount * @notice Address calling this function needs to approve token 0 and token 1 to Terminal * * @param symbol CLR Pool token symbol * @param ticks lower and upper ticks of the position * @param rewardsProgram Rewards program parameters * @param pool pool fee, token0, token1 and initial liquidity amounts */ function deployIncentivizedPool( string memory symbol, PositionTicks memory ticks, RewardsProgram memory rewardsProgram, PoolDetails memory pool ) external payable { uint256 feeOwed = customDeploymentFeeEnabled[msg.sender] ? customDeploymentFee[msg.sender] : deploymentFee; require( msg.value == feeOwed, "Need to send ETH for CLR pool deployment" ); // Deploy CLR ICLR clrPool = ICLR(clrDeployer.deployCLRPool(proxyAdmin)); // Deploy Staked CLR Token IStakedCLRToken stakedToken = IStakedCLRToken( clrDeployer.deploySCLRToken(proxyAdmin) ); // Initialize Staked CLR Token stakedToken.initialize( "StakedCLRToken", symbol, address(clrPool), false ); // Initialize CLR if (pool.token0 > pool.token1) { address tmp = pool.token0; pool.token0 = pool.token1; pool.token1 = tmp; } bool rewardsAreEscrowed = rewardsProgram.vestingPeriod > 0 ? true : false; address poolAddress = getPool(pool.token0, pool.token1, pool.fee); ICLR.StakingDetails memory stakingParams = ICLR.StakingDetails({ rewardTokens: rewardsProgram.rewardTokens, rewardEscrow: address(rewardEscrow), rewardsAreEscrowed: rewardsAreEscrowed }); // Initialize CLR clrPool.initialize( symbol, ticks.lowerTick, ticks.upperTick, pool.fee, tradeFee, pool.token0, pool.token1, address(stakedToken), address(this), poolAddress, uniContracts, stakingParams ); // Approve tokens to clr pool IERC20(pool.token0).safeApprove(address(clrPool), type(uint256).max); IERC20(pool.token1).safeApprove(address(clrPool), type(uint256).max); // Transfer initial mint tokens to Terminal IERC20(pool.token0).safeTransferFrom( msg.sender, address(this), pool.amount0 ); IERC20(pool.token1).safeTransferFrom( msg.sender, address(this), pool.amount1 ); // Create Uniswap V3 Position, seed with initial liquidity clrPool.mintInitial(pool.amount0, pool.amount1, msg.sender); // Setup vesting period if rewards are escrowed if (rewardsAreEscrowed) { rewardEscrow.setCLRPoolVestingPeriod( address(clrPool), rewardsProgram.vestingPeriod ); } // Transfer ownership of CLR to deployer clrPool.transferOwnership(msg.sender); // Set CLR and Staked Token proxy admin to deployer IProxyAdmin(proxyAdmin).addProxyAdmin(address(clrPool), msg.sender); IProxyAdmin(proxyAdmin).addProxyAdmin(address(stakedToken), msg.sender); deployedCLRPools.push(clrPool); emit DeployedIncentivizedPool( address(clrPool), pool.token0, pool.token1, pool.fee, ticks.lowerTick, ticks.upperTick ); } /** * @notice Initiate reward accumulation for a given staking rewards contract * @notice Address calling this function needs to approve reward tokens to Terminal */ function initiateRewardsProgram( ICLR clrPool, uint256[] memory totalRewardAmounts, uint256 rewardsDuration ) external { require( clrPool.periodFinish() == 0, "Reward program has been initiated" ); if (clrPool.rewardsAreEscrowed()) { rewardEscrow.addRewardsContract(address(clrPool)); } clrPool.setRewardsDuration(rewardsDuration); _initiateRewardsProgram(clrPool, totalRewardAmounts); } /** * @notice Initiate new reward accumulation for a given staking rewards contract * @notice Address calling this function needs to approve reward token to Terminal * @notice Used only after first rewards program has ended */ function initiateNewRewardsProgram( ICLR clrPool, uint256[] memory totalRewardAmounts, uint256 rewardsDuration ) external { require( clrPool.periodFinish() != 0, "First program must be initialized using initiateRewardsProgram" ); require( block.timestamp > clrPool.periodFinish(), "Previous program must finish before initializing a new one" ); clrPool.setRewardsDuration(rewardsDuration); _initiateRewardsProgram(clrPool, totalRewardAmounts); } /** * Initiate rewards program for all reward tokens in pool * @notice reward amounts must be ordered based on the initial reward token order * @notice each reward token will be initialized with exactly the reward amount set here * @param clrPool pool to initiate rewards for * @param totalRewardAmounts array of reward amounts for each reward token */ function _initiateRewardsProgram( ICLR clrPool, uint256[] memory totalRewardAmounts ) private { address[] memory rewardTokens = clrPool.getRewardTokens(); require( totalRewardAmounts.length == rewardTokens.length, "Total reward amounts count should be the same as reward tokens count" ); address owner = clrPool.owner(); address manager = clrPool.manager(); require( msg.sender == owner || msg.sender == manager, "Only owner or manager can initiate the rewards program" ); for (uint256 i = 0; i < rewardTokens.length; ++i) { address rewardToken = rewardTokens[i]; uint256 rewardAmountFee = totalRewardAmounts[i].div(rewardFee); uint256 rewardAmount = totalRewardAmounts[i].sub(rewardAmountFee); // Transfer *rewardAmountFee* of rewardToken to LM Terminal as fee IERC20(rewardToken).safeTransferFrom( msg.sender, address(this), rewardAmountFee ); // Add fee to reward fees // Transfer *totalRewardsAmount* of rewardToken to StakingRewards address IERC20(rewardToken).safeTransferFrom( msg.sender, address(clrPool), rewardAmount ); clrPool.initializeReward(rewardAmount, rewardToken); } emit InitiatedRewardsProgram( address(clrPool), rewardTokens, totalRewardAmounts, clrPool.rewardsDuration() ); } // --- Miscellaneous --- /** * @notice Get pool address from token0, token1 addresses and fee amount */ function getPool( address token0, address token1, uint24 fee ) public view returns (address pool) { return uniswapFactory.getPool(token0, token1, fee); } /** * @notice Enable custom CLR pool deployment fee for a given address * @param deployer address to enable fee for * @param feeAmount fee amount in eth */ function enableCustomDeploymentFee(address deployer, uint256 feeAmount) public onlyOwner { require( feeAmount < deploymentFee, "Custom fee should be less than flat deployment fee" ); customDeploymentFeeEnabled[deployer] = true; customDeploymentFee[deployer] = feeAmount; } /** * @notice Disable custom CLR pool deployment fee for a given address * @param deployer address to disable fee for */ function disableCustomDeploymentFee(address deployer) public onlyOwner { customDeploymentFeeEnabled[deployer] = false; } /** * @notice Withdraw function for xToken fees for a token * @dev Withdraws both ETH and reward token fees */ function withdrawFees(IERC20 token) external onlyRevenueController { // Withdraw reward token fees uint256 fees = token.balanceOf(address(this)); if (fees > 0) { token.safeTransfer(msg.sender, fees); emit TokenFeeWithdraw(address(token), fees); } // Withdraw ETH fees // Revenue Controller accepts ETH if (address(this).balance > 0) { bool sent = transferETH(address(this).balance, msg.sender); if (sent) { emit EthFeeWithdraw(address(this).balance); } } } function transferETH(uint256 amount, address payable to) private returns (bool sent) { (sent, ) = to.call{value: amount}(""); } receive() external payable {} // --- Modifiers --- // For xToken Fee Claim functions modifier onlyRevenueController() { require( xTokenManager.isRevenueController(msg.sender), "Callable only by Revenue Controller" ); _; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; 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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Extended is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IStakingRewards.sol"; /** * Interface for CLR for Solidity integration */ interface ICLR is IERC20, IStakingRewards { function addManager(address _manager) external; function adminStake(uint256 amount0, uint256 amount1) external; function adminSwap(uint256 amount, bool _0for1) external; function calculateAmountsMintedSingleToken(uint8 inputAsset, uint256 amount) external view returns (uint256 amount0Minted, uint256 amount1Minted); function calculateMintAmount(uint256 amount0, uint256 amount1) external view returns (uint256 mintAmount); function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1) external view returns (uint256 amount0Minted, uint256 amount1Minted); function collect() external returns (uint256 collected0, uint256 collected1); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function deposit(uint8 inputAsset, uint256 amount) external; function getAmountsForLiquidity(uint128 liquidity) external view returns (uint256 amount0, uint256 amount1); function getBufferToken0Balance() external view returns (uint256 amount0); function getBufferToken1Balance() external view returns (uint256 amount1); function getBufferTokenBalance() external view returns (uint256 amount0, uint256 amount1); function getLiquidityForAmounts(uint256 amount0, uint256 amount1) external view returns (uint128 liquidity); function getPositionLiquidity() external view returns (uint128 liquidity); function getStakedTokenBalance() external view returns (uint256 amount0, uint256 amount1); function getTicks() external view returns (int24 tick0, int24 tick1); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function initialize( string memory _symbol, int24 _tickLower, int24 _tickUpper, uint24 _poolFee, uint256 _tradeFee, address _token0, address _token1, address _stakedToken, address _terminal, address _uniswapPool, UniswapContracts memory contracts, // Staking parameters StakingDetails memory stakingParams ) external; function manager() external view returns (address); function mintInitial( uint256 amount0, uint256 amount1, address sender ) external; function name() external view returns (string memory); function owner() external view returns (address); function pauseContract() external returns (bool); function paused() external view returns (bool); function poolFee() external view returns (uint24); function reinvest() external; function renounceOwnership() external; function stakedToken() external view returns (address); function symbol() external view returns (string memory); function token0() external view returns (address); function token0DecimalMultiplier() external view returns (uint256); function token0Decimals() external view returns (uint8); function token1() external view returns (address); function token1DecimalMultiplier() external view returns (uint256); function token1Decimals() external view returns (uint8); function tokenId() external view returns (uint256); function tradeFee() external view returns (uint256); function transferOwnership(address newOwner) external; function uniContracts() external view returns ( address router, address quoter, address positionManager ); function uniswapPool() external view returns (address); function unpauseContract() external returns (bool); function withdraw(uint256 amount) external; function withdrawAndClaimReward(uint256 amount) external; struct UniswapContracts { address router; address quoter; address positionManager; } struct StakingDetails { address[] rewardTokens; address rewardEscrow; bool rewardsAreEscrowed; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IStakedCLRToken is IERC20 { /// @notice Mints SCLR tokens in exchange for LP's provided tokens to CLR instance /// @param _recipient (address) LP's address to send the SCLR tokens to /// @param _amount (uint256) SCLR tokens amount to be minted /// @return (bool) indicates a successful operation function mint(address _recipient, uint256 _amount) external returns (bool); /// @notice Burns SCLR tokens as indicated /// @param _sender (address) LP's address account to burn SCLR tokens from /// @param _amount (uint256) SCLR token amount to be burned /// @return (bool) indicates a successful operation function burnFrom(address _sender, uint256 _amount) external returns (bool); /// @notice Initializes SCLR token /// @param _name (string) SCLR token's name /// @param _symbol (string) SCLR token's symbol /// @param _clrPool (address) Address of the CLR pool the token belongs to /// @param _transferable (bool) Indicates if token is transferable function initialize( string memory _name, string memory _symbol, address _clrPool, bool _transferable ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IRewardEscrow { function MAX_VESTING_ENTRIES() external view returns (uint256); function addRewardsContract(address _rewardContract) external; function appendVestingEntry( address token, address account, address pool, uint256 quantity ) external; function balanceOf(address token, address account) external view returns (uint256); function checkAccountSchedule( address pool, address token, address account ) external view returns (uint256[] memory); function clrPoolVestingPeriod(address) external view returns (uint256); function getNextVestingEntry( address pool, address token, address account ) external view returns (uint256[2] memory); function getNextVestingIndex( address pool, address token, address account ) external view returns (uint256); function getNextVestingQuantity( address pool, address token, address account ) external view returns (uint256); function getNextVestingTime( address pool, address token, address account ) external view returns (uint256); function getVestingQuantity( address pool, address token, address account, uint256 index ) external view returns (uint256); function getVestingScheduleEntry( address pool, address token, address account, uint256 index ) external view returns (uint256[2] memory); function getVestingTime( address pool, address token, address account, uint256 index ) external view returns (uint256); function initialize() external; function isRewardContract(address) external view returns (bool); function numVestingEntries( address pool, address token, address account ) external view returns (uint256); function owner() external view returns (address); function removeRewardsContract(address _rewardContract) external; function renounceOwnership() external; function setCLRPoolVestingPeriod(address pool, uint256 vestingPeriod) external; function totalEscrowedAccountBalance(address, address) external view returns (uint256); function totalEscrowedBalance(address) external view returns (uint256); function totalSupply(address token) external view returns (uint256); function totalVestedAccountBalance(address, address) external view returns (uint256); function transferOwnership(address newOwner) external; function vest(address pool, address token) external; function vestAll(address pool, address[] memory tokens) external; function vestingSchedules( address, address, address, uint256, uint256 ) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IProxyAdmin { function addProxyAdmin(address proxy, address admin) external; function changeProxyAdmin(address proxy, address newAdmin) external; function getProxyAdmin(address proxy) external view returns (address); function getProxyImplementation(address proxy) external view returns (address); function owner() external view returns (address); function renounceOwnership() external; function transferOwnership(address newOwner) external; function upgrade(address proxy, address implementation) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./proxies/CLRProxy.sol"; import "./proxies/StakedCLRTokenProxy.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * Manages deployment of CLR and StakedCLRToken Proxies * Deploys CLR proxies pointing to CLR implementation * Deploys StakedCLRToken proxies pointing to StakedCLRToken implementation */ contract CLRDeployer is Ownable { address public clrImplementation; address public sCLRTokenImplementation; constructor(address _clrImplementation, address _sclrTokenImplementation) { clrImplementation = _clrImplementation; sCLRTokenImplementation = _sclrTokenImplementation; emit CLRImplementationSet(_clrImplementation); emit CLRTokenImplementationSet(_sclrTokenImplementation); } function deployCLRPool(address _proxyAdmin) external returns (address pool) { CLRProxy clrInstance = new CLRProxy( clrImplementation, _proxyAdmin, address(this) ); return address(clrInstance); } function deploySCLRToken(address _proxyAdmin) external returns (address token) { StakedCLRTokenProxy clrTokenInstance = new StakedCLRTokenProxy( sCLRTokenImplementation, _proxyAdmin, address(this) ); return address(clrTokenInstance); } function setCLRImplementation(address _clrImplementation) external onlyOwner { clrImplementation = _clrImplementation; emit CLRImplementationSet(_clrImplementation); } function setsCLRTokenImplementation(address _sCLRTokenImplementation) external onlyOwner { sCLRTokenImplementation = _sCLRTokenImplementation; emit CLRTokenImplementationSet(_sCLRTokenImplementation); } // Events event CLRImplementationSet(address indexed clrImplementation); event CLRTokenImplementationSet(address indexed sCLRTokenImplementation); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./IRewardEscrow.sol"; interface IStakingRewards { // Views function earned(address account, address token) external view returns (uint256); function getRewardForDuration(address token) external view returns (uint256); function getRewardTokens() external view returns (address[] memory tokens); function getRewardTokensCount() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime(address) external view returns (uint256); function periodFinish() external view returns (uint256); function rewardEscrow() external view returns (IRewardEscrow); function rewardInfo(address) external view returns ( uint256 rewardRate, uint256 rewardPerTokenStored, uint256 totalRewardAmount, uint256 remainingRewardAmount ); function rewardPerToken(address token) external view returns (uint256); function rewardTokens(uint256) external view returns (address); function rewardsAreEscrowed() external view returns (bool); function rewardsDuration() external view returns (uint256); function stakedBalanceOf(address account) external view returns (uint256); function stakedTotalSupply() external view returns (uint256); // Mutative function claimReward() external; function initializeReward(uint256 rewardAmount, address token) external; function setRewardsDuration(uint256 _rewardsDuration) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol"; import "../interfaces/ICLRDeployer.sol"; contract CLRProxy is TransparentUpgradeableProxy { ICLRDeployer clrDeployer; constructor( address _logic, address _proxyAdmin, address _clrDeployer ) TransparentUpgradeableProxy(_logic, _proxyAdmin, "") { clrDeployer = ICLRDeployer(_clrDeployer); } function upgradeTo(address _implementation) external override ifAdmin { require( clrDeployer.clrImplementation() == _implementation, "Can only upgrade to latest CLR implementation" ); _upgradeTo(_implementation); } function upgradeToAndCall(address _implementation, bytes calldata data) external payable override ifAdmin { require( clrDeployer.clrImplementation() == _implementation, "Can only upgrade to latest CLR implementation" ); _upgradeTo(_implementation); Address.functionDelegateCall(_implementation, data); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol"; import "../interfaces/ICLRDeployer.sol"; contract StakedCLRTokenProxy is TransparentUpgradeableProxy { ICLRDeployer clrDeployer; constructor( address _logic, address _proxyAdmin, address _clrDeployer ) TransparentUpgradeableProxy(_logic, _proxyAdmin, "") { clrDeployer = ICLRDeployer(_clrDeployer); } function upgradeTo(address _implementation) external override ifAdmin { require( clrDeployer.sCLRTokenImplementation() == _implementation, "Can only upgrade to latest Staked CLR token implementation" ); _upgradeTo(_implementation); } function upgradeToAndCall(address _implementation, bytes calldata data) external payable override ifAdmin { require( clrDeployer.sCLRTokenImplementation() == _implementation, "Can only upgrade to latest Staked CLR token implementation" ); _upgradeTo(_implementation); Address.functionDelegateCall(_implementation, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./UpgradeableProxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external virtual ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin { _upgradeTo(newImplementation); Address.functionDelegateCall(newImplementation, data); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICLRDeployer { function clrImplementation() external view returns (address); function deployCLRPool(address _proxyAdmin) external returns (address pool); function deploySCLRToken(address _proxyAdmin) external returns (address token); function owner() external view returns (address); function renounceOwnership() external; function sCLRTokenImplementation() external view returns (address); function setCLRImplementation(address _clrImplementation) external; function setsCLRTokenImplementation(address _sCLRTokenImplementation) external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./Proxy.sol"; import "../utils/Address.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT 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; } }
True if premium fee is enabled
mapping(address => bool) public customDeploymentFeeEnabled;
1,513,989
[ 1, 5510, 309, 23020, 5077, 14036, 353, 3696, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 1679, 6733, 14667, 1526, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; contract EthPool { address owner; modifier onlyowner { require(msg.sender == owner, "INVALID USER"); _; } uint totalDeposit = 0; struct DepositorInfo { uint amount; bool isExist; } mapping(address => DepositorInfo) depositors; mapping(address => DepositorInfo) depositorsReward; uint256[] depositorsIds; address[] allDepositors; event Deposit( address indexed depositor, uint amount ); event RewardDistributed( uint amount ); event Withdraw( address indexed depositor, uint amount ); constructor() { owner = msg.sender; } // joinPool by depositors function joinPool() public payable returns(bool) { address from = msg.sender; uint depositAmount = msg.value; require(depositors[from].isExist == false, 'ALREADY DEPOSITED'); require(from != owner, 'YOU ARE NOT ALLOWED TO DEPOSIT'); require(depositAmount > 0, 'DEPOSIT AMOUNT MUST BE GREATER THAN 0'); uint senderBalance = address(from).balance; require(senderBalance > depositAmount, 'INSUFFICIENT AMOUNT IN ACCOUNT'); totalDeposit += depositAmount; DepositorInfo memory newDepositor = depositors[from]; newDepositor.amount = depositAmount; newDepositor.isExist = true; depositors[from] = newDepositor; allDepositors.push(from); emit Deposit(from, depositAmount); return true; } // distribute rewards to depositors function giveReward() public payable onlyowner returns(bool) { uint rewardedAmount = msg.value; require(rewardedAmount > 0, 'REWARD AMOUNT SHOULD BE GREATER THAN 0'); require(allDepositors.length > 0, 'NO DEPOSITOR TO DISTRIBUTE REWARD'); for(uint i = 0; i < allDepositors.length; i++) { uint rewardAmount = (uint(rewardedAmount) * ((uint(depositors[allDepositors[i]].amount) * 100) / uint(totalDeposit))) / 100; if(depositors[allDepositors[i]].isExist == true) { if(depositorsReward[allDepositors[i]].isExist == true) { depositorsReward[allDepositors[i]].amount += rewardAmount; } else { DepositorInfo memory newRewardDepositor = depositorsReward[allDepositors[i]]; newRewardDepositor.amount = rewardAmount; newRewardDepositor.isExist = true; depositorsReward[allDepositors[i]] = newRewardDepositor; } } } emit RewardDistributed(rewardedAmount); return true; } // withdraw deposit Amount & reward function withdraw() public payable returns(bool) { require(depositors[msg.sender].isExist == true, "YOU HAVEN'T DEPOSIT ANY AMOUNT"); uint amountToWithDraw = depositors[msg.sender].amount + depositorsReward[msg.sender].amount; totalDeposit -= depositors[msg.sender].amount; delete depositors[msg.sender]; delete depositorsReward[msg.sender]; payable(msg.sender).transfer(amountToWithDraw); emit Withdraw(msg.sender, amountToWithDraw); return true; } // get total deposit amount function getTotalDeposit() public view returns(uint) { return totalDeposit; } // get specific depositor deposited amount function getDepositorAmount(address despositorAddress) public view returns(uint) { return depositors[despositorAddress].amount; } // get specific depositor reward amount function getDepositorRewardedAmount(address despositorAddress) public view returns(uint) { return depositorsReward[despositorAddress].amount; } }
distribute rewards to depositors
function giveReward() public payable onlyowner returns(bool) { uint rewardedAmount = msg.value; require(rewardedAmount > 0, 'REWARD AMOUNT SHOULD BE GREATER THAN 0'); require(allDepositors.length > 0, 'NO DEPOSITOR TO DISTRIBUTE REWARD'); for(uint i = 0; i < allDepositors.length; i++) { uint rewardAmount = (uint(rewardedAmount) * ((uint(depositors[allDepositors[i]].amount) * 100) / uint(totalDeposit))) / 100; if(depositors[allDepositors[i]].isExist == true) { if(depositorsReward[allDepositors[i]].isExist == true) { depositorsReward[allDepositors[i]].amount += rewardAmount; } else { DepositorInfo memory newRewardDepositor = depositorsReward[allDepositors[i]]; newRewardDepositor.amount = rewardAmount; newRewardDepositor.isExist = true; depositorsReward[allDepositors[i]] = newRewardDepositor; } } } emit RewardDistributed(rewardedAmount); return true; }
12,726,757
[ 1, 2251, 887, 283, 6397, 358, 443, 1724, 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, 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, 8492, 17631, 1060, 1435, 1071, 8843, 429, 1338, 8443, 1135, 12, 6430, 13, 288, 203, 3639, 2254, 283, 11804, 6275, 273, 1234, 18, 1132, 31, 203, 3639, 2583, 12, 266, 11804, 6275, 405, 374, 16, 296, 862, 21343, 432, 5980, 5321, 6122, 31090, 9722, 22428, 7662, 1258, 374, 8284, 203, 3639, 2583, 12, 454, 758, 1724, 1383, 18, 2469, 405, 374, 16, 296, 3417, 2030, 28284, 916, 8493, 3690, 15765, 8885, 2438, 21343, 8284, 203, 203, 3639, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 777, 758, 1724, 1383, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2254, 19890, 6275, 273, 261, 11890, 12, 266, 11804, 6275, 13, 380, 14015, 11890, 12, 323, 1724, 1383, 63, 454, 758, 1724, 1383, 63, 77, 65, 8009, 8949, 13, 380, 2130, 13, 342, 2254, 12, 4963, 758, 1724, 20349, 342, 2130, 31, 203, 5411, 309, 12, 323, 1724, 1383, 63, 454, 758, 1724, 1383, 63, 77, 65, 8009, 291, 4786, 422, 638, 13, 288, 203, 7734, 309, 12, 323, 1724, 1383, 17631, 1060, 63, 454, 758, 1724, 1383, 63, 77, 65, 8009, 291, 4786, 422, 638, 13, 288, 203, 10792, 443, 1724, 1383, 17631, 1060, 63, 454, 758, 1724, 1383, 63, 77, 65, 8009, 8949, 1011, 19890, 6275, 31, 203, 7734, 289, 203, 7734, 469, 288, 203, 10792, 4019, 538, 1811, 966, 3778, 394, 17631, 1060, 758, 1724, 280, 273, 443, 1724, 1383, 17631, 1060, 63, 454, 758, 1724, 1383, 63, 77, 13563, 31, 203, 10792, 394, 17631, 1060, 758, 1724, 280, 18, 8949, 2 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
Огонь возжёгся в храме
rus_verbs:возжечься{},
5,482,234
[ 1, 145, 257, 145, 116, 145, 127, 145, 126, 146, 239, 225, 145, 115, 145, 127, 145, 120, 145, 119, 146, 244, 145, 116, 146, 228, 146, 242, 225, 145, 115, 225, 146, 232, 146, 227, 145, 113, 145, 125, 145, 118, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 436, 407, 67, 502, 2038, 30, 145, 115, 145, 127, 145, 120, 145, 119, 145, 118, 146, 234, 146, 239, 146, 228, 146, 242, 2916, 16, 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 ]
./partial_match/3/0xBcc008d20736433605c6b61f185d3B605440Eb5f/sources/pool.sol
* @notice deposit of Tether USDTS, user needs to approve() to this contract address first, and call with the given amount./
function depositUSDT(uint256 amountUSDT) external whenPoolerNotPaused { require(amountUSDT > 0, "0 value"); USDTContract.safeTransferFrom(msg.sender, address(this), amountUSDT); poolerTokenContract.mint(msg.sender, amountUSDT); collateral += amountUSDT; }
5,123,088
[ 1, 323, 1724, 434, 399, 2437, 587, 9903, 8047, 16, 729, 4260, 358, 6617, 537, 1435, 358, 333, 6835, 1758, 1122, 16, 471, 745, 598, 326, 864, 3844, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 443, 1724, 3378, 9081, 12, 11890, 5034, 3844, 3378, 9081, 13, 3903, 1347, 2864, 264, 1248, 28590, 288, 203, 3639, 2583, 12, 8949, 3378, 9081, 405, 374, 16, 315, 20, 460, 8863, 203, 3639, 11836, 9081, 8924, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 3378, 9081, 1769, 203, 3639, 2845, 264, 1345, 8924, 18, 81, 474, 12, 3576, 18, 15330, 16, 3844, 3378, 9081, 1769, 203, 3639, 4508, 2045, 287, 1011, 3844, 3378, 9081, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-08-09 */ pragma solidity ^0.5.8; /** * @title ERC20 compatible token interface * * - Implements ERC 20 Token standard * - Implements short address attack fix * * #created 29/09/2017 * #author Frank Bonnet */ contract IToken { /** * Get the total supply of tokens * * @return The total supply */ function totalSupply() external view returns (uint); /** * Get balance of `_owner` * * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) external view returns (uint); /** * Send `_value` token to `_to` from `msg.sender` * * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint _value) external returns (bool); /** * Send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint _value) external returns (bool); /** * `msg.sender` approves `_spender` to spend `_value` tokens * * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint _value) external returns (bool); /** * Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner` * * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) external view returns (uint); } /** * @title ManagedToken interface * * Adds the following functionality to the basic ERC20 token * - Locking * - Issuing * - Burning * * #created 29/09/2017 * #author Frank Bonnet */ contract IManagedToken is IToken { /** * Returns true if the token is locked * * @return Whether the token is locked */ function isLocked() external view returns (bool); /** * Locks the token so that the transfering of value is disabled * * @return Whether the unlocking was successful or not */ function lock() external returns (bool); /** * Unlocks the token so that the transfering of value is enabled * * @return Whether the unlocking was successful or not */ function unlock() external returns (bool); /** * Issues `_value` new tokens to `_to` * * @param _to The address to which the tokens will be issued * @param _value The amount of new tokens to issue * @return Whether the tokens where sucessfully issued or not */ function issue(address _to, uint _value) external returns (bool); /** * Burns `_value` tokens of `_from` * * @param _from The address that owns the tokens to be burned * @param _value The amount of tokens to be burned * @return Whether the tokens where sucessfully burned or not */ function burn(address _from, uint _value) external returns (bool); } /** * @title Token observer interface * * Allows a token smart-contract to notify observers * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) external; } /** * @title Abstract token observer * * Allows observers to be notified by an observed token smart-contract * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract TokenObserver is ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) public { onTokensReceived(msg.sender, _from, _value); } /** * Event handler * * Called by `_token` when a token amount is received * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal; } /** * @title Token retrieve interface * * Allows tokens to be retrieved from a contract * * #created 29/09/2017 * #author Frank Bonnet */ contract ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) external; } /** * @title Token retrieve * * Allows tokens to be retrieved from a contract * * #created 18/10/2017 * #author Frank Bonnet */ contract TokenRetriever is ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public { IToken tokenInstance = IToken(_tokenContract); uint tokenBalance = tokenInstance.balanceOf(address(this)); if (tokenBalance > 0) { tokenInstance.transfer(msg.sender, tokenBalance); } } } /** * @title Observable interface * * Allows observers to register and unregister with the * implementing smart-contract that is observable * * #created 09/10/2017 * #author Frank Bonnet */ contract IObservable { /** * Returns true if `_account` is a registered observer * * @param _account The account to test against * @return Whether the account is a registered observer */ function isObserver(address _account) external view returns (bool); /** * Gets the amount of registered observers * * @return The amount of registered observers */ function getObserverCount() external view returns (uint); /** * Gets the observer at `_index` * * @param _index The index of the observer * @return The observers address */ function getObserverAtIndex(uint _index) external view returns (address); /** * Register `_observer` as an observer * * @param _observer The account to add as an observer */ function registerObserver(address _observer) external; /** * Unregister `_observer` as an observer * * @param _observer The account to remove as an observer */ function unregisterObserver(address _observer) external; } /** * @title Ownership interface * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract IOwnership { /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool); /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address); } /** * @title Ownership * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract Ownership is IOwnership { // Owner address internal owner; /** * The publisher is the inital owner */ constructor() public { owner = msg.sender; } /** * Access is restricted to the current owner */ modifier only_owner() { require(msg.sender == owner, "m:only_owner"); _; } /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool) { return _account == owner; } /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address) { return owner; } } /** * @title Transferable ownership interface * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract ITransferableOwnership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) external; } /** * @title Transferable ownership * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract TransferableOwnership is ITransferableOwnership, Ownership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) public only_owner { owner = _newOwner; } } /** * @title Multi-owned interface * * Interface that allows multiple owners * * #created 09/10/2017 * #author Frank Bonnet */ contract IMultiOwned { /** * Returns true if `_account` is an owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool); /** * Returns the amount of owners * * @return The amount of owners */ function getOwnerCount() public view returns (uint); /** * Gets the owner at `_index` * * @param _index The index of the owner * @return The address of the owner found at `_index` */ function getOwnerAt(uint _index) public view returns (address); /** * Adds `_account` as a new owner * * @param _account The account to add as an owner */ function addOwner(address _account) public; /** * Removes `_account` as an owner * * @param _account The account to remove as an owner */ function removeOwner(address _account) public; } /** * @title IAuthenticator * * Authenticator interface * * #created 15/10/2017 * #author Frank Bonnet */ contract IAuthenticator { /** * Authenticate * * Returns whether `_account` is authenticated or not * * @param _account The account to authenticate * @return whether `_account` is successfully authenticated */ function authenticate(address _account) public view returns (bool); } /** * @title Dcorp Dissolvement Proposal * * Serves as a placeholder for the Dcorp funds, allowing the community the ability * to claim their part of the ether. * * This contact is deployed upon receiving the Ether that is currently held by the previous proxy contract. * * #created 18/7/2019 * #author Frank Bonnet */ contract DcorpDissolvementProposal is TokenObserver, TransferableOwnership, TokenRetriever { enum Stages { Deploying, Deployed, Executed } struct Balance { uint drps; uint drpu; uint index; } // State Stages private stage; // Settings uint public constant CLAIMING_DURATION = 60 days; uint public constant WITHDRAW_DURATION = 60 days; uint public constant DISSOLVEMENT_AMOUNT = 948 ether; // +- 150000 euro // Alocated balances mapping (address => Balance) private allocated; address[] private allocatedIndex; // Whitelist IAuthenticator public authenticator; // Tokens IToken public drpsToken; IToken public drpuToken; // Previous proxy address public prevProxy; uint public prevProxyRecordedBalance; // Dissolvement address payable public dissolvementFund; uint public claimTotalWeight; uint public claimTotalEther; uint public claimDeadline; uint public withdrawDeadline; /** * Require that the sender is authentcated */ modifier only_authenticated() { require(authenticator.authenticate(msg.sender), "m:only_authenticated"); _; } /** * Require that the contract is in `_stage` */ modifier only_at_stage(Stages _stage) { require(stage == _stage, "m:only_at_stage"); _; } /** * Require `_token` to be one of the drp tokens * * @param _token The address to test against */ modifier only_accepted_token(address _token) { require(_token == address(drpsToken) || _token == address(drpuToken), "m:only_accepted_token"); _; } /** * Require that `_token` is not one of the drp tokens * * @param _token The address to test against */ modifier not_accepted_token(address _token) { require(_token != address(drpsToken) && _token != address(drpuToken), "m:not_accepted_token"); _; } /** * Require that sender has more than zero tokens */ modifier only_token_holder() { require(allocated[msg.sender].drps > 0 || allocated[msg.sender].drpu > 0, "m:only_token_holder"); _; } /** * Require that the claiming period for the proposal has * not yet ended */ modifier only_during_claiming_period() { require(claimDeadline > 0 && now <= claimDeadline, "m:only_during_claiming_period"); _; } /** * Require that the claiming period for the proposal has ended */ modifier only_after_claiming_period() { require(claimDeadline > 0 && now > claimDeadline, "m:only_after_claiming_period"); _; } /** * Require that the withdraw period for the proposal has * not yet ended */ modifier only_during_withdraw_period() { require(withdrawDeadline > 0 && now <= withdrawDeadline, "m:only_during_withdraw_period"); _; } /** * Require that the withdraw period for the proposal has ended */ modifier only_after_withdraw_period() { require(withdrawDeadline > 0 && now > withdrawDeadline, "m:only_after_withdraw_period"); _; } /** * Construct the proxy * * @param _authenticator Whitelist * @param _drpsToken The new security token * @param _drpuToken The new utility token * @param _prevProxy Proxy accepts and requires ether from the prev proxy * @param _dissolvementFund Ether to be used for the dissolvement of DCORP */ constructor(address _authenticator, address _drpsToken, address _drpuToken, address _prevProxy, address payable _dissolvementFund) public { authenticator = IAuthenticator(_authenticator); drpsToken = IToken(_drpsToken); drpuToken = IToken(_drpuToken); prevProxy = _prevProxy; prevProxyRecordedBalance = _prevProxy.balance; dissolvementFund = _dissolvementFund; stage = Stages.Deploying; } /** * Returns whether the proposal is being deployed * * @return Whether the proposal is in the deploying stage */ function isDeploying() public view returns (bool) { return stage == Stages.Deploying; } /** * Returns whether the proposal is deployed. The proposal is deployed * when it receives Ether from the prev proxy contract * * @return Whether the proposal is deployed */ function isDeployed() public view returns (bool) { return stage == Stages.Deployed; } /** * Returns whether the proposal is executed * * @return Whether the proposal is deployed */ function isExecuted() public view returns (bool) { return stage == Stages.Executed; } /** * Accept eth from the prev proxy while deploying */ function () external payable only_at_stage(Stages.Deploying) { require(msg.sender == address(prevProxy), "f:fallback;e:invalid_sender"); } /** * Deploy the proposal */ function deploy() public only_owner only_at_stage(Stages.Deploying) { require(address(this).balance >= prevProxyRecordedBalance, "f:deploy;e:invalid_balance"); // Mark deployed stage = Stages.Deployed; // Start claiming period claimDeadline = now + CLAIMING_DURATION; // Remove prev proxy as observer IObservable(address(drpsToken)).unregisterObserver(prevProxy); IObservable(address(drpuToken)).unregisterObserver(prevProxy); // Register this proxy as observer IObservable(address(drpsToken)).registerObserver(address(this)); IObservable(address(drpuToken)).registerObserver(address(this)); // Transfer dissolvement funds uint amountToTransfer = DISSOLVEMENT_AMOUNT; if (amountToTransfer > address(this).balance) { amountToTransfer = address(this).balance; } dissolvementFund.transfer(amountToTransfer); } /** * Returns the combined total supply of all drp tokens * * @return The combined total drp supply */ function getTotalSupply() public view returns (uint) { uint sum = 0; sum += drpsToken.totalSupply(); sum += drpuToken.totalSupply(); return sum; } /** * Returns true if `_owner` has a balance allocated * * @param _owner The account that the balance is allocated for * @return True if there is a balance that belongs to `_owner` */ function hasBalance(address _owner) public view returns (bool) { return allocatedIndex.length > 0 && _owner == allocatedIndex[allocated[_owner].index]; } /** * Get the allocated drps or drpu token balance of `_owner` * * @param _token The address to test against * @param _owner The address from which the allocated token balance will be retrieved * @return The allocated drps token balance */ function balanceOf(address _token, address _owner) public view returns (uint) { uint balance = 0; if (address(drpsToken) == _token) { balance = allocated[_owner].drps; } else if (address(drpuToken) == _token) { balance = allocated[_owner].drpu; } return balance; } /** * Executes the proposal * * Dissolves DCORP Decentralized and allows the ether to be withdrawn * * Should only be called after the claiming period */ function execute() public only_at_stage(Stages.Deployed) only_after_claiming_period { // Mark as executed stage = Stages.Executed; withdrawDeadline = now + WITHDRAW_DURATION; // Remaining balance is claimable claimTotalEther = address(this).balance; // Disable tokens IManagedToken(address(drpsToken)).lock(); IManagedToken(address(drpuToken)).lock(); // Remove self token as owner IMultiOwned(address(drpsToken)).removeOwner(address(this)); IMultiOwned(address(drpuToken)).removeOwner(address(this)); } /** * Allows an account to claim ether during the claiming period */ function withdraw() public only_at_stage(Stages.Executed) only_during_withdraw_period only_token_holder only_authenticated { Balance storage b = allocated[msg.sender]; uint weight = b.drpu + _convertDrpsWeight(b.drps); // Mark claimed b.drpu = 0; b.drps = 0; // Transfer amount uint amountToTransfer = weight * claimTotalEther / claimTotalWeight; msg.sender.transfer(amountToTransfer); } /** * Event handler that initializes the token conversion * * Called by `_token` when a token amount is received on * the address of this token changer * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal only_during_claiming_period only_accepted_token(_token) { require(_token == msg.sender, "f:onTokensReceived;e:only_receiving_token"); // Allocate tokens if (!hasBalance(_from)) { allocated[_from] = Balance( 0, 0, allocatedIndex.push(_from) - 1); } Balance storage b = allocated[_from]; if (_token == address(drpsToken)) { b.drps += _value; claimTotalWeight += _convertDrpsWeight(_value); } else { b.drpu += _value; claimTotalWeight += _value; } } /** * Failsafe mechanism * * Allows the owner to retrieve ether from the contract that was not claimed * within the claiming period. */ function retrieveEther() public only_owner only_after_withdraw_period { selfdestruct(msg.sender); } /** * Failsafe mechanism * * Allows the owner to retrieve tokens (other than DRPS and DRPU tokens) from the contract that * might have been send there by accident * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public only_owner not_accepted_token(_tokenContract) { super.retrieveTokens(_tokenContract); } /** * Converts the weight for DRPS tokens * * @param _value The amount of tokens to convert */ function _convertDrpsWeight(uint _value) private pure returns (uint) { return _value * 2; } }
* Returns true if `_owner` has a balance allocated @param _owner The account that the balance is allocated for @return True if there is a balance that belongs to `_owner`/
function hasBalance(address _owner) public view returns (bool) { return allocatedIndex.length > 0 && _owner == allocatedIndex[allocated[_owner].index]; }
997,028
[ 1, 1356, 638, 309, 1375, 67, 8443, 68, 711, 279, 11013, 11977, 225, 389, 8443, 1021, 2236, 716, 326, 11013, 353, 11977, 364, 327, 1053, 309, 1915, 353, 279, 11013, 716, 11081, 358, 1375, 67, 8443, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 711, 13937, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 11977, 1016, 18, 2469, 405, 374, 597, 389, 8443, 422, 11977, 1016, 63, 28172, 63, 67, 8443, 8009, 1615, 15533, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.1; import "./erc721.sol"; import "./erc721-token-receiver.sol"; import "../math/safe-math.sol"; import "../utils/supports-interface.sol"; import "../utils/address-utils.sol"; /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract NFToken is ERC721, SupportsInterface { using SafeMath for uint256; using AddressUtils for address; /** * @dev Magic value of a smart contract that can recieve NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev A mapping from NFT ID to the address that owns it. */ mapping (uint256 => address) internal idToOwner; /** * @dev Mapping from NFT ID to approved address. */ mapping (uint256 => address) internal idToApproval; /** * @dev Mapping from owner address to count of his tokens. */ mapping (address => uint256) private ownerToNFTokenCount; /** * @dev Mapping from owner address to mapping of operator addresses. */ mapping (address => mapping (address => bool)) internal ownerToOperators; /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. * @param _from Sender of NFT (if address is zero address it indicates token creation). * @param _to Receiver of NFT (if address is zero address it indicates token destruction). * @param _tokenId The NFT that got transfered. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. * @param _owner Owner of NFT. * @param _approved Address that we are approving. * @param _tokenId NFT which we are approving. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. * @param _owner Owner of NFT. * @param _operator Address to which we are setting operator rights. * @param _approved Status of operator rights(true if operator rights are given and false if * revoked). */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Guarantees that the msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender]); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender] ); _; } /** * @dev Guarantees that _tokenId is a valid Token. * @param _tokenId ID of the NFT to validate. */ modifier validNFToken( uint256 _tokenId ) { require(idToOwner[_tokenId] != address(0)); _; } /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x80ac58cd] = true; // ERC721 } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they maybe be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from); require(_to != address(0)); _transfer(_to, _tokenId); } /** * @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved Address to be approved for the given NFT ID. * @param _tokenId ID of the token to be approved. */ function approve( address _approved, uint256 _tokenId ) external canOperate(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner); idToApproval[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice This works even if sender doesn't own any tokens at the time. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external { ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external view returns (uint256) { require(_owner != address(0)); return _getOwnerNFTCount(_owner); } /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external view returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0)); } /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId ID of the NFT to query the approval of. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external view validNFToken(_tokenId) returns (address) { return idToApproval[_tokenId]; } /** * @dev Checks if `_operator` is an approved operator for `_owner`. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool) { return ownerToOperators[_owner][_operator]; } /** * @dev Actually preforms the transfer. * @notice Does NO checks. * @param _to Address of a new owner. * @param _tokenId The NFT that is being transferred. */ function _transfer( address _to, uint256 _tokenId ) internal { address from = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(from, _tokenId); _addNFToken(_to, _tokenId); emit Transfer(from, _to, _tokenId); } /** * @dev Mints a new NFT. * @notice This is a private function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal { require(_to != address(0)); require(idToOwner[_tokenId] == address(0)); _addNFToken(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Burns a NFT. * @notice This is a private function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(tokenOwner, _tokenId); emit Transfer(tokenOwner, address(0), _tokenId); } /** * @dev Removes a NFT from owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal { require(idToOwner[_tokenId] == _from); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; } /** * @dev Assignes a new NFT to owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal { require(idToOwner[_tokenId] == address(0)); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1); } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage (gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal view returns (uint256) { return ownerToNFTokenCount[_owner]; } /** * @dev Actually perform the safeTransferFrom. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) private canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from); require(_to != address(0)); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == MAGIC_ON_ERC721_RECEIVED); } } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function _clearApproval( uint256 _tokenId ) private { if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; } } }
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are considered invalid, and this function throws for queries about the zero address. @param _owner Address for whom to query the balance. @return Balance of _owner./
function balanceOf( address _owner ) external view returns (uint256) { require(_owner != address(0)); return _getOwnerNFTCount(_owner); }
6,402,888
[ 1, 1356, 326, 1300, 434, 423, 4464, 87, 16199, 635, 1375, 67, 8443, 8338, 423, 4464, 87, 6958, 358, 326, 3634, 1758, 854, 7399, 2057, 16, 471, 333, 445, 1216, 364, 6218, 2973, 326, 3634, 1758, 18, 225, 389, 8443, 5267, 364, 600, 362, 358, 843, 326, 11013, 18, 327, 30918, 434, 389, 8443, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 11013, 951, 12, 203, 565, 1758, 389, 8443, 203, 225, 262, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 13, 203, 225, 288, 203, 565, 2583, 24899, 8443, 480, 1758, 12, 20, 10019, 203, 565, 327, 389, 588, 5541, 50, 4464, 1380, 24899, 8443, 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 ]
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "../core/State.sol"; import "../events/ProtocolSettingsEvents.sol"; import "../openzeppelin/SafeERC20.sol"; import "../mixins/ProtocolTokenUser.sol"; import "../modules/interfaces/ProtocolSwapExternalInterface.sol"; import "../mixins/ModuleCommonFunctionalities.sol"; import "../swaps/ISwapsImpl.sol"; import "../governance/IFeeSharingProxy.sol"; import "../feeds/IPriceFeeds.sol"; /** * @title Protocol Settings contract. * * @notice This contract code comes from bZx. bZx is a protocol for tokenized * margin trading and lending https://bzx.network similar to the dYdX protocol. * * This contract contains functions to customize protocol settings. * */ contract ProtocolSettings is State, ProtocolTokenUser, ProtocolSettingsEvents, ModuleCommonFunctionalities { using SafeERC20 for IERC20; using SafeMath for uint256; /** * @notice Empty public constructor. * */ constructor() public {} /** * @notice Fallback function is to react to receiving value (rBTC). * */ function() external { revert("fallback not allowed"); } /** * @notice Set function selectors on target contract. * * @param target The address of the target contract. * */ function initialize(address target) external onlyOwner { address prevModuleContractAddress = logicTargets[this.setPriceFeedContract.selector]; _setTarget(this.setPriceFeedContract.selector, target); _setTarget(this.setSwapsImplContract.selector, target); _setTarget(this.setLoanPool.selector, target); _setTarget(this.setSupportedTokens.selector, target); _setTarget(this.setLendingFeePercent.selector, target); _setTarget(this.setTradingFeePercent.selector, target); _setTarget(this.setBorrowingFeePercent.selector, target); _setTarget(this.setSwapExternalFeePercent.selector, target); _setTarget(this.setAffiliateFeePercent.selector, target); _setTarget(this.setAffiliateTradingTokenFeePercent.selector, target); _setTarget(this.setLiquidationIncentivePercent.selector, target); _setTarget(this.setMaxDisagreement.selector, target); _setTarget(this.setSourceBuffer.selector, target); _setTarget(this.setMaxSwapSize.selector, target); _setTarget(this.setFeesController.selector, target); _setTarget(this.withdrawFees.selector, target); _setTarget(this.withdrawLendingFees.selector, target); _setTarget(this.withdrawTradingFees.selector, target); _setTarget(this.withdrawBorrowingFees.selector, target); _setTarget(this.withdrawProtocolToken.selector, target); _setTarget(this.depositProtocolToken.selector, target); _setTarget(this.getLoanPoolsList.selector, target); _setTarget(this.isLoanPool.selector, target); _setTarget(this.setSovrynSwapContractRegistryAddress.selector, target); _setTarget(this.setWrbtcToken.selector, target); _setTarget(this.setProtocolTokenAddress.selector, target); _setTarget(this.setRolloverBaseReward.selector, target); _setTarget(this.setRebatePercent.selector, target); _setTarget(this.setSpecialRebates.selector, target); _setTarget(this.setSovrynProtocolAddress.selector, target); _setTarget(this.setSOVTokenAddress.selector, target); _setTarget(this.setLockedSOVAddress.selector, target); _setTarget(this.setMinReferralsToPayoutAffiliates.selector, target); _setTarget(this.getSpecialRebates.selector, target); _setTarget(this.getProtocolAddress.selector, target); _setTarget(this.getSovTokenAddress.selector, target); _setTarget(this.getLockedSOVAddress.selector, target); _setTarget(this.getFeeRebatePercent.selector, target); _setTarget(this.togglePaused.selector, target); _setTarget(this.isProtocolPaused.selector, target); _setTarget(this.getSwapExternalFeePercent.selector, target); _setTarget(this.setTradingRebateRewardsBasisPoint.selector, target); _setTarget(this.getTradingRebateRewardsBasisPoint.selector, target); _setTarget(this.getDedicatedSOVRebate.selector, target); _setTarget(this.setRolloverFlexFeePercent.selector, target); emit ProtocolModuleContractReplaced(prevModuleContractAddress, target, "ProtocolSettings"); } /** * setting wrong address will break inter module functions calling * should be set once */ function setSovrynProtocolAddress(address newProtocolAddress) external onlyOwner whenNotPaused { address oldProtocolAddress = protocolAddress; protocolAddress = newProtocolAddress; emit SetProtocolAddress(msg.sender, oldProtocolAddress, newProtocolAddress); } function setSOVTokenAddress(address newSovTokenAddress) external onlyOwner whenNotPaused { require(Address.isContract(newSovTokenAddress), "newSovTokenAddress not a contract"); address oldTokenAddress = sovTokenAddress; sovTokenAddress = newSovTokenAddress; emit SetSOVTokenAddress(msg.sender, oldTokenAddress, newSovTokenAddress); } function setLockedSOVAddress(address newLockedSOVAddress) external onlyOwner whenNotPaused { require(Address.isContract(newLockedSOVAddress), "newLockSOVAddress not a contract"); address oldLockedSOVAddress = lockedSOVAddress; lockedSOVAddress = newLockedSOVAddress; emit SetLockedSOVAddress(msg.sender, oldLockedSOVAddress, newLockedSOVAddress); } /** * @notice Set the basis point of trading rebate rewards (SOV), max value is 9999 (99.99% liquid, 0.01% vested). * * @param newBasisPoint Basis point value. */ function setTradingRebateRewardsBasisPoint(uint256 newBasisPoint) external onlyOwner whenNotPaused { require(newBasisPoint <= 9999, "value too high"); uint256 oldBasisPoint = tradingRebateRewardsBasisPoint; tradingRebateRewardsBasisPoint = newBasisPoint; emit SetTradingRebateRewardsBasisPoint(msg.sender, oldBasisPoint, newBasisPoint); } /** * @notice Update the minimum number of referrals to get affiliates rewards. * * @param newMinReferrals The new minimum number of referrals. * */ function setMinReferralsToPayoutAffiliates(uint256 newMinReferrals) external onlyOwner whenNotPaused { uint256 oldMinReferrals = minReferralsToPayout; minReferralsToPayout = newMinReferrals; emit SetMinReferralsToPayoutAffiliates(msg.sender, oldMinReferrals, newMinReferrals); } /** * @notice Set the address of the Price Feed instance. * * @param newContract The address of the Price Feed new instance. * */ function setPriceFeedContract(address newContract) external onlyOwner whenNotPaused { address oldContract = priceFeeds; priceFeeds = newContract; emit SetPriceFeedContract(msg.sender, oldContract, newContract); } /** * @notice Set the address of the asset swapper instance. * * @param newContract The address of the asset swapper new instance. * */ function setSwapsImplContract(address newContract) external onlyOwner whenNotPaused { address oldContract = swapsImpl; swapsImpl = newContract; emit SetSwapsImplContract(msg.sender, oldContract, newContract); } /** * @notice Set a list of loan pools and its tokens. * * @param pools The array of addresses of new loan pool instances. * @param assets The array of addresses of the corresponding underlying tokens. * */ function setLoanPool(address[] calldata pools, address[] calldata assets) external onlyOwner whenNotPaused { require(pools.length == assets.length, "count mismatch"); for (uint256 i = 0; i < pools.length; i++) { require(pools[i] != assets[i], "pool == asset"); require(pools[i] != address(0), "pool == 0"); require( assets[i] != address(0) || loanPoolToUnderlying[pools[i]] != address(0), "pool not exists" ); if (assets[i] == address(0)) { underlyingToLoanPool[loanPoolToUnderlying[pools[i]]] = address(0); loanPoolToUnderlying[pools[i]] = address(0); loanPoolsSet.removeAddress(pools[i]); } else { loanPoolToUnderlying[pools[i]] = assets[i]; underlyingToLoanPool[assets[i]] = pools[i]; loanPoolsSet.addAddress(pools[i]); } emit SetLoanPool(msg.sender, pools[i], assets[i]); } } /** * @notice Set a list of supported tokens by populating the * storage supportedTokens mapping. * * @param addrs The array of addresses of the tokens. * @param toggles The array of flags indicating whether * the corresponding token is supported or not. * */ function setSupportedTokens(address[] calldata addrs, bool[] calldata toggles) external onlyOwner whenNotPaused { require(addrs.length == toggles.length, "count mismatch"); for (uint256 i = 0; i < addrs.length; i++) { supportedTokens[addrs[i]] = toggles[i]; emit SetSupportedTokens(msg.sender, addrs[i], toggles[i]); } } /** * @notice Set the value of lendingFeePercent storage variable. * * @param newValue The new value for lendingFeePercent. * */ function setLendingFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = lendingFeePercent; lendingFeePercent = newValue; emit SetLendingFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of tradingFeePercent storage variable. * * @param newValue The new value for tradingFeePercent. * */ function setTradingFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = tradingFeePercent; tradingFeePercent = newValue; emit SetTradingFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of borrowingFeePercent storage variable. * * @param newValue The new value for borrowingFeePercent. * */ function setBorrowingFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = borrowingFeePercent; borrowingFeePercent = newValue; emit SetBorrowingFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of swapExtrernalFeePercent storage variable * * @param newValue the new value for swapExternalFeePercent */ function setSwapExternalFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = swapExtrernalFeePercent; swapExtrernalFeePercent = newValue; emit SetSwapExternalFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of affiliateFeePercent storage variable. * * @param newValue The new value for affiliateFeePercent. * */ function setAffiliateFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = affiliateFeePercent; affiliateFeePercent = newValue; emit SetAffiliateFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of affiliateTradingTokenFeePercent storage variable. * * @param newValue The new value for affiliateTradingTokenFeePercent. * */ function setAffiliateTradingTokenFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = affiliateTradingTokenFeePercent; affiliateTradingTokenFeePercent = newValue; emit SetAffiliateTradingTokenFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of liquidationIncentivePercent storage variable. * * @param newValue The new value for liquidationIncentivePercent. * */ function setLiquidationIncentivePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = liquidationIncentivePercent; liquidationIncentivePercent = newValue; emit SetLiquidationIncentivePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of the maximum swap spread. * * @param newValue The new value for maxDisagreement. * */ function setMaxDisagreement(uint256 newValue) external onlyOwner whenNotPaused { maxDisagreement = newValue; } /** * @notice Set the value of the maximum source buffer. * * @dev To avoid rounding issues on the swap rate a small buffer is implemented. * * @param newValue The new value for the maximum source buffer. * */ function setSourceBuffer(uint256 newValue) external onlyOwner whenNotPaused { sourceBuffer = newValue; } /** * @notice Set the value of the swap size limit. * * @param newValue The new value for the maximum swap size. * */ function setMaxSwapSize(uint256 newValue) external onlyOwner whenNotPaused { uint256 oldValue = maxSwapSize; maxSwapSize = newValue; emit SetMaxSwapSize(msg.sender, oldValue, newValue); } /** * @notice Set the address of the feesController instance. * * @dev The fee sharing proxy must be the feesController of the * protocol contract. This allows the fee sharing proxy * to withdraw the fees. * * @param newController The new address of the feesController. * */ function setFeesController(address newController) external onlyOwner whenNotPaused { address oldController = feesController; feesController = newController; emit SetFeesController(msg.sender, oldController, newController); } /** * @notice The feesController calls this function to withdraw fees * from three sources: lending, trading and borrowing. * The fees (except SOV) will be converted to wRBTC. * For SOV, it will be deposited directly to feeSharingProxy from the protocol. * * @param tokens The array of address of the token instance. * @param receiver The address of the withdrawal recipient. * * @return The withdrawn total amount in wRBTC * */ function withdrawFees(address[] calldata tokens, address receiver) external whenNotPaused returns (uint256 totalWRBTCWithdrawn) { require(msg.sender == feesController, "unauthorized"); for (uint256 i = 0; i < tokens.length; i++) { uint256 lendingBalance = lendingFeeTokensHeld[tokens[i]]; if (lendingBalance > 0) { lendingFeeTokensHeld[tokens[i]] = 0; lendingFeeTokensPaid[tokens[i]] = lendingFeeTokensPaid[tokens[i]].add( lendingBalance ); } uint256 tradingBalance = tradingFeeTokensHeld[tokens[i]]; if (tradingBalance > 0) { tradingFeeTokensHeld[tokens[i]] = 0; tradingFeeTokensPaid[tokens[i]] = tradingFeeTokensPaid[tokens[i]].add( tradingBalance ); } uint256 borrowingBalance = borrowingFeeTokensHeld[tokens[i]]; if (borrowingBalance > 0) { borrowingFeeTokensHeld[tokens[i]] = 0; borrowingFeeTokensPaid[tokens[i]] = borrowingFeeTokensPaid[tokens[i]].add( borrowingBalance ); } uint256 tempAmount = lendingBalance.add(tradingBalance).add(borrowingBalance); if (tempAmount == 0) { continue; } uint256 amountConvertedToWRBTC; if (tokens[i] == address(sovTokenAddress)) { IERC20(tokens[i]).approve(feesController, tempAmount); IFeeSharingProxy(feesController).transferTokens( address(sovTokenAddress), uint96(tempAmount) ); amountConvertedToWRBTC = 0; } else { if (tokens[i] == address(wrbtcToken)) { amountConvertedToWRBTC = tempAmount; IERC20(address(wrbtcToken)).safeTransfer(receiver, amountConvertedToWRBTC); } else { IERC20(tokens[i]).approve(protocolAddress, tempAmount); (amountConvertedToWRBTC, ) = ProtocolSwapExternalInterface(protocolAddress) .swapExternal( tokens[i], // source token address address(wrbtcToken), // dest token address feesController, // set feeSharingProxy as receiver protocolAddress, // protocol as the sender tempAmount, // source token amount 0, // reqDestToken 0, // minReturn "" // loan data bytes ); /// Will revert if disagreement found. IPriceFeeds(priceFeeds).checkPriceDisagreement( tokens[i], address(wrbtcToken), tempAmount, amountConvertedToWRBTC, maxDisagreement ); } totalWRBTCWithdrawn = totalWRBTCWithdrawn.add(amountConvertedToWRBTC); } emit WithdrawFees( msg.sender, tokens[i], receiver, lendingBalance, tradingBalance, borrowingBalance, amountConvertedToWRBTC ); } return totalWRBTCWithdrawn; } /** * @notice The feesController calls this function to withdraw fees * accrued from lending operations. * * @param token The address of the token instance. * @param receiver The address of the withdrawal recipient. * @param amount The amount of fees to get, ignored if greater than balance. * * @return Whether withdrawal was successful. * */ function withdrawLendingFees( address token, address receiver, uint256 amount ) external whenNotPaused returns (bool) { require(msg.sender == feesController, "unauthorized"); uint256 withdrawAmount = amount; uint256 balance = lendingFeeTokensHeld[token]; if (withdrawAmount > balance) { withdrawAmount = balance; } if (withdrawAmount == 0) { return false; } lendingFeeTokensHeld[token] = balance.sub(withdrawAmount); lendingFeeTokensPaid[token] = lendingFeeTokensPaid[token].add(withdrawAmount); IERC20(token).safeTransfer(receiver, withdrawAmount); emit WithdrawLendingFees(msg.sender, token, receiver, withdrawAmount); return true; } /** * @notice The feesController calls this function to withdraw fees * accrued from trading operations. * * @param token The address of the token instance. * @param receiver The address of the withdrawal recipient. * @param amount The amount of fees to get, ignored if greater than balance. * * @return Whether withdrawal was successful. * */ function withdrawTradingFees( address token, address receiver, uint256 amount ) external whenNotPaused returns (bool) { require(msg.sender == feesController, "unauthorized"); uint256 withdrawAmount = amount; uint256 balance = tradingFeeTokensHeld[token]; if (withdrawAmount > balance) { withdrawAmount = balance; } if (withdrawAmount == 0) { return false; } tradingFeeTokensHeld[token] = balance.sub(withdrawAmount); tradingFeeTokensPaid[token] = tradingFeeTokensPaid[token].add(withdrawAmount); IERC20(token).safeTransfer(receiver, withdrawAmount); emit WithdrawTradingFees(msg.sender, token, receiver, withdrawAmount); return true; } /** * @notice The feesController calls this function to withdraw fees * accrued from borrowing operations. * * @param token The address of the token instance. * @param receiver The address of the withdrawal recipient. * @param amount The amount of fees to get, ignored if greater than balance. * * @return Whether withdrawal was successful. * */ function withdrawBorrowingFees( address token, address receiver, uint256 amount ) external whenNotPaused returns (bool) { require(msg.sender == feesController, "unauthorized"); uint256 withdrawAmount = amount; uint256 balance = borrowingFeeTokensHeld[token]; if (withdrawAmount > balance) { withdrawAmount = balance; } if (withdrawAmount == 0) { return false; } borrowingFeeTokensHeld[token] = balance.sub(withdrawAmount); borrowingFeeTokensPaid[token] = borrowingFeeTokensPaid[token].add(withdrawAmount); IERC20(token).safeTransfer(receiver, withdrawAmount); emit WithdrawBorrowingFees(msg.sender, token, receiver, withdrawAmount); return true; } /** * @notice The owner calls this function to withdraw protocol tokens. * * @dev Wrapper for ProtocolTokenUser::_withdrawProtocolToken internal function. * * @param receiver The address of the withdrawal recipient. * @param amount The amount of tokens to get. * * @return The protocol token address. * @return Withdrawal success (true/false). * */ function withdrawProtocolToken(address receiver, uint256 amount) external onlyOwner whenNotPaused returns (address, bool) { return _withdrawProtocolToken(receiver, amount); } /** * @notice The owner calls this function to deposit protocol tokens. * * @param amount The tokens of fees to send. * */ function depositProtocolToken(uint256 amount) external onlyOwner whenNotPaused { /// @dev Update local balance protocolTokenHeld = protocolTokenHeld.add(amount); /// @dev Send the tokens IERC20(protocolTokenAddress).safeTransferFrom(msg.sender, address(this), amount); } /** * @notice Get a list of loan pools. * * @param start The offset. * @param count The limit. * * @return The array of loan pools. * */ function getLoanPoolsList(uint256 start, uint256 count) external view returns (bytes32[] memory) { return loanPoolsSet.enumerate(start, count); } /** * @notice Check whether a token is a pool token. * * @dev By querying its underlying token. * * @param loanPool The token address to check. * */ function isLoanPool(address loanPool) external view returns (bool) { return loanPoolToUnderlying[loanPool] != address(0); } /** * @notice Set the contract registry address of the SovrynSwap network. * * @param registryAddress the address of the registry contract. * */ function setSovrynSwapContractRegistryAddress(address registryAddress) external onlyOwner whenNotPaused { require(Address.isContract(registryAddress), "registryAddress not a contract"); address oldSovrynSwapContractRegistryAddress = sovrynSwapContractRegistryAddress; sovrynSwapContractRegistryAddress = registryAddress; emit SetSovrynSwapContractRegistryAddress( msg.sender, oldSovrynSwapContractRegistryAddress, sovrynSwapContractRegistryAddress ); } /** * @notice Set the wrBTC contract address. * * @param wrbtcTokenAddress The address of the wrBTC contract. * */ function setWrbtcToken(address wrbtcTokenAddress) external onlyOwner whenNotPaused { require(Address.isContract(wrbtcTokenAddress), "wrbtcTokenAddress not a contract"); address oldwrbtcToken = address(wrbtcToken); wrbtcToken = IWrbtcERC20(wrbtcTokenAddress); emit SetWrbtcToken(msg.sender, oldwrbtcToken, wrbtcTokenAddress); } /** * @notice Set the protocol token contract address. * * @param _protocolTokenAddress The address of the protocol token contract. * */ function setProtocolTokenAddress(address _protocolTokenAddress) external onlyOwner whenNotPaused { require(Address.isContract(_protocolTokenAddress), "_protocolTokenAddress not a contract"); address oldProtocolTokenAddress = protocolTokenAddress; protocolTokenAddress = _protocolTokenAddress; emit SetProtocolTokenAddress(msg.sender, oldProtocolTokenAddress, _protocolTokenAddress); } /** * @notice Set rollover base reward. It should be denominated in wrBTC. * * @param baseRewardValue The base reward. * */ function setRolloverBaseReward(uint256 baseRewardValue) external onlyOwner whenNotPaused { require(baseRewardValue > 0, "Base reward is zero"); uint256 oldValue = rolloverBaseReward; rolloverBaseReward = baseRewardValue; emit SetRolloverBaseReward(msg.sender, oldValue, rolloverBaseReward); } /** * @notice Set the fee rebate percent. * * @param rebatePercent The fee rebate percent. * */ function setRebatePercent(uint256 rebatePercent) external onlyOwner whenNotPaused { require(rebatePercent <= 10**20, "Fee rebate is too high"); uint256 oldRebatePercent = feeRebatePercent; feeRebatePercent = rebatePercent; emit SetRebatePercent(msg.sender, oldRebatePercent, rebatePercent); } /** * @notice Set the special fee rebate percent for specific pair * * @param specialRebatesPercent The new special fee rebate percent. * */ function setSpecialRebates( address sourceToken, address destToken, uint256 specialRebatesPercent ) external onlyOwner whenNotPaused { // Set max special rebates to 1000% require(specialRebatesPercent <= 1000e18, "Special fee rebate is too high"); uint256 oldSpecialRebatesPercent = specialRebates[sourceToken][destToken]; specialRebates[sourceToken][destToken] = specialRebatesPercent; emit SetSpecialRebates( msg.sender, sourceToken, destToken, oldSpecialRebatesPercent, specialRebatesPercent ); } /** * @notice Get a rebate percent of specific pairs. * * @param sourceTokenAddress The source of pairs. * @param destTokenAddress The dest of pairs. * * @return The percent rebates of the pairs. * */ function getSpecialRebates(address sourceTokenAddress, address destTokenAddress) external view returns (uint256 specialRebatesPercent) { return specialRebates[sourceTokenAddress][destTokenAddress]; } function getProtocolAddress() external view returns (address) { return protocolAddress; } function getSovTokenAddress() external view returns (address) { return sovTokenAddress; } function getLockedSOVAddress() external view returns (address) { return lockedSOVAddress; } function getFeeRebatePercent() external view returns (uint256) { return feeRebatePercent; } function togglePaused(bool paused) external onlyOwner { require(paused != pause, "Can't toggle"); pause = paused; emit TogglePaused(msg.sender, !paused, paused); } function isProtocolPaused() external view returns (bool) { return pause; } function getSwapExternalFeePercent() external view returns (uint256) { return swapExtrernalFeePercent; } /** * @notice Get the basis point of trading rebate rewards. * * @return The basis point value. */ function getTradingRebateRewardsBasisPoint() external view returns (uint256) { return tradingRebateRewardsBasisPoint; } /** * @dev Get how much SOV that is dedicated to pay the trading rebate rewards. * @notice If SOV balance is less than the fees held, it will return 0. * * @return total dedicated SOV. */ function getDedicatedSOVRebate() public view returns (uint256) { uint256 sovProtocolBalance = IERC20(sovTokenAddress).balanceOf(address(this)); uint256 sovFees = lendingFeeTokensHeld[sovTokenAddress].add(tradingFeeTokensHeld[sovTokenAddress]).add( borrowingFeeTokensHeld[sovTokenAddress] ); return sovProtocolBalance >= sovFees ? sovProtocolBalance.sub(sovFees) : 0; } /** * @notice Set rolloverFlexFeePercent (max value is 1%) * * @param newRolloverFlexFeePercent uint256 value of new rollover flex fee percentage (0.1 ether = 0.1%) */ function setRolloverFlexFeePercent(uint256 newRolloverFlexFeePercent) external onlyOwner whenNotPaused { require(newRolloverFlexFeePercent <= 1e18, "value too high"); uint256 oldRolloverFlexFeePercent = rolloverFlexFeePercent; rolloverFlexFeePercent = newRolloverFlexFeePercent; emit SetRolloverFlexFeePercent( msg.sender, oldRolloverFlexFeePercent, newRolloverFlexFeePercent ); } }
* @notice Get the basis point of trading rebate rewards. @return The basis point value./
function getTradingRebateRewardsBasisPoint() external view returns (uint256) { return tradingRebateRewardsBasisPoint; }
1,801,182
[ 1, 967, 326, 10853, 1634, 434, 1284, 7459, 283, 70, 340, 283, 6397, 18, 327, 1021, 10853, 1634, 460, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 1609, 7459, 426, 70, 340, 17631, 14727, 11494, 291, 2148, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1284, 7459, 426, 70, 340, 17631, 14727, 11494, 291, 2148, 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 ]
// This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) // You can find more complex example in https://github.com/ConsenSys/Tokens pragma solidity ^0.4.8; import "./BaseToken.sol"; import "./SafeMath.sol"; contract MisoToken is BaseToken { using SafeMath for uint; using SafeMath for uint256; // Standard Solidity Interface string public name; uint8 public decimals; string public symbol; string public version = "MISO"; // MISO Token Specific address owner; // How many MISO tokens are given daily uint256 public dailyTokens = 12; // How many MISO tokens are used per feed uint256 public tokensPerFeed = 3; // When did you last claim your tokens mapping (address => uint) lastClaimed; // Feeding history mapping (address => uint[]) feedingHistory; // How many blocks before you can claim tokens uint public blocksPerClaim = 100; // Callback function everytime someone feeds an address // https://solidity.readthedocs.io/en/v0.4.21/contracts.html#events event feedEvent(address addr); function UsableToken( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { owner = msg.sender; balances[this] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } function changeBlocksPerClaim(uint newB) public { require(msg.sender == owner); blocksPerClaim = newB; } function getBlocksTillClaimable(address addr) public view returns (uint blockNo) { if (lastClaimed[addr] == 0) { return 0; } uint blockDif = (block.number - lastClaimed[addr] - 1); if (blockDif < blocksPerClaim) { return blocksPerClaim.sub(blockDif); } return 0; } function getLastClaimBlock(address addr) public view returns (uint blockNo) { return lastClaimed[addr]; } function getFeedingHistory (address addr) public view returns (uint[]) { return feedingHistory[addr]; } function getBlocksPerClaim () public view returns (uint) { return blocksPerClaim; } function getTokensPerFeed () public view returns (uint) { return tokensPerFeed; } function getDailyTokensNo () public view returns (uint) { return dailyTokens; } function getClaimableTokens (address addr) public view returns (uint) { uint value; if (lastClaimed[addr] == 0) { // Initial claim = set to current block number value = dailyTokens; } else { // How many mutiples of food uint multiples = (block.number - lastClaimed[addr] - 1).div(blocksPerClaim); value = multiples * dailyTokens; } return value; } function claim() public returns (bool success) { // Can only claim tokens every 5k blocks if (block.number - lastClaimed[msg.sender] - 1 < blocksPerClaim) { return false; } uint value; if (lastClaimed[msg.sender] == 0) { // Initial claim = set to current block number value = dailyTokens; } else { // How many mutiples of food uint multiples = (block.number - lastClaimed[msg.sender] - 1).div(blocksPerClaim); value = multiples * dailyTokens; } lastClaimed[msg.sender] = block.number - 1; balances[msg.sender] += value; balances[this] -= value; Transfer(this, msg.sender, value); return true; } function feed() public { require(balances[msg.sender] >= tokensPerFeed); // Add to feeding history feedingHistory[msg.sender].push(block.number - 1); balances[msg.sender] -= tokensPerFeed; balances[this] += tokensPerFeed; emit feedEvent(msg.sender); } }
Add to feeding history
function feed() public { require(balances[msg.sender] >= tokensPerFeed); feedingHistory[msg.sender].push(block.number - 1); balances[msg.sender] -= tokensPerFeed; balances[this] += tokensPerFeed; emit feedEvent(msg.sender); }
954,141
[ 1, 986, 358, 4746, 310, 4927, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4746, 1435, 1071, 288, 203, 3639, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 65, 1545, 2430, 2173, 8141, 1769, 203, 203, 3639, 4746, 310, 5623, 63, 3576, 18, 15330, 8009, 6206, 12, 2629, 18, 2696, 300, 404, 1769, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 3947, 2430, 2173, 8141, 31, 203, 3639, 324, 26488, 63, 2211, 65, 1011, 2430, 2173, 8141, 31, 203, 203, 3639, 3626, 4746, 1133, 12, 3576, 18, 15330, 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 ]
./full_match/5/0x38DB1BF0Fe525564B73fB0b157d969D496B7165d/sources/DividendToken.sol
* @notice Distributes dividends to token holders. @dev It reverts if the total supply is 0. It emits the `FundsDistributed` event if the amount to distribute is greater than 0. About undistributed dividends: In each distribution, there is a small amount which does not get distributed, which is `(amount POINTS_MULTIPLIER) % totalShares()`. With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting distributed in a distribution can be less than 1 (base unit)./
function _distributeDividends(uint256 amount) internal { uint256 shares = getTotalShares(); require(shares > 0, "SHARES"); if (amount > 0) { pointsPerShare = pointsPerShare.add( amount.mul(POINTS_MULTIPLIER) / shares ); emit DividendsDistributed(msg.sender, amount); } }
1,937,506
[ 1, 1669, 1141, 3739, 350, 5839, 358, 1147, 366, 4665, 18, 225, 2597, 15226, 87, 309, 326, 2078, 14467, 353, 374, 18, 2597, 24169, 326, 1375, 42, 19156, 1669, 11050, 68, 871, 309, 326, 3844, 358, 25722, 353, 6802, 2353, 374, 18, 9771, 659, 640, 2251, 11050, 3739, 350, 5839, 30, 282, 657, 1517, 7006, 16, 1915, 353, 279, 5264, 3844, 1492, 1552, 486, 336, 16859, 16, 282, 1492, 353, 1375, 12, 8949, 225, 13803, 3217, 55, 67, 24683, 2053, 654, 13, 738, 2078, 24051, 1435, 8338, 282, 3423, 279, 5492, 17, 343, 8918, 1375, 8941, 55, 67, 24683, 2053, 654, 9191, 326, 3844, 434, 284, 19156, 716, 854, 486, 8742, 282, 16859, 316, 279, 7006, 848, 506, 5242, 2353, 404, 261, 1969, 2836, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 2251, 887, 7244, 350, 5839, 12, 11890, 5034, 3844, 13, 2713, 288, 203, 565, 2254, 5034, 24123, 273, 12831, 24051, 5621, 203, 565, 2583, 12, 30720, 405, 374, 16, 315, 8325, 7031, 8863, 203, 203, 565, 309, 261, 8949, 405, 374, 13, 288, 203, 1377, 3143, 2173, 9535, 273, 3143, 2173, 9535, 18, 1289, 12, 203, 3639, 3844, 18, 16411, 12, 8941, 55, 67, 24683, 2053, 654, 13, 342, 24123, 203, 1377, 11272, 203, 1377, 3626, 21411, 350, 5839, 1669, 11050, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IVORConsumerBase { function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external; } interface BlockHashStoreInterface { function getBlockhash(uint256 number) external view returns (bytes32); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20_Ex { /** * @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 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) external returns (bool); /** * @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) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title VOR */ contract VOR { // See https://www.secg.org/sec2-v2.pdf, section 2.4.1, for these constants. uint256 private constant GROUP_ORDER = // Number of points in Secp256k1 // solium-disable-next-line indentation 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; // Prime characteristic of the galois field over which Secp256k1 is defined uint256 private constant FIELD_SIZE = // solium-disable-next-line indentation 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 private constant WORD_LENGTH_BYTES = 0x20; // (base^exponent) % FIELD_SIZE // Cribbed from https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4 function bigModExp(uint256 base, uint256 exponent) internal view returns (uint256 exponentiation) { uint256 callResult; uint256[6] memory bigModExpContractInputs; bigModExpContractInputs[0] = WORD_LENGTH_BYTES; // Length of base bigModExpContractInputs[1] = WORD_LENGTH_BYTES; // Length of exponent bigModExpContractInputs[2] = WORD_LENGTH_BYTES; // Length of modulus bigModExpContractInputs[3] = base; bigModExpContractInputs[4] = exponent; bigModExpContractInputs[5] = FIELD_SIZE; uint256[1] memory output; assembly { // solhint-disable-line no-inline-assembly callResult := staticcall( not(0), // Gas cost: no limit 0x05, // Bigmodexp contract address bigModExpContractInputs, 0xc0, // Length of input segment: 6*0x20-bytes output, 0x20 // Length of output segment ) } if (callResult == 0) { revert("bigModExp failure!"); } return output[0]; } // Let q=FIELD_SIZE. q % 4 = 3, ∴ x≡r^2 mod q ⇒ x^SQRT_POWER≡±r mod q. See // https://en.wikipedia.org/wiki/Modular_square_root#Prime_or_prime_power_modulus uint256 private constant SQRT_POWER = (FIELD_SIZE + 1) >> 2; // Computes a s.t. a^2 = x in the field. Assumes a exists function squareRoot(uint256 x) internal view returns (uint256) { return bigModExp(x, SQRT_POWER); } // The value of y^2 given that (x,y) is on secp256k1. function ySquared(uint256 x) internal pure returns (uint256) { // Curve is y^2=x^3+7. See section 2.4.1 of https://www.secg.org/sec2-v2.pdf uint256 xCubed = mulmod(x, mulmod(x, x, FIELD_SIZE), FIELD_SIZE); return addmod(xCubed, 7, FIELD_SIZE); } // True iff p is on secp256k1 function isOnCurve(uint256[2] memory p) internal pure returns (bool) { return ySquared(p[0]) == mulmod(p[1], p[1], FIELD_SIZE); } // Hash x uniformly into {0, ..., FIELD_SIZE-1}. function fieldHash(bytes memory b) internal pure returns (uint256 x_) { x_ = uint256(keccak256(b)); // Rejecting if x >= FIELD_SIZE corresponds to step 2.1 in section 2.3.4 of // http://www.secg.org/sec1-v2.pdf , which is part of the definition of // string_to_point in the IETF draft while (x_ >= FIELD_SIZE) { x_ = uint256(keccak256(abi.encodePacked(x_))); } } // Hash b to a random point which hopefully lies on secp256k1. function newCandidateSecp256k1Point(bytes memory b) internal view returns (uint256[2] memory p) { p[0] = fieldHash(b); p[1] = squareRoot(ySquared(p[0])); if (p[1] % 2 == 1) { p[1] = FIELD_SIZE - p[1]; } } // Domain-separation tag for initial hash in hashToCurve. uint256 constant HASH_TO_CURVE_HASH_PREFIX = 1; // Cryptographic hash function onto the curve. // // Corresponds to algorithm in section 5.4.1.1 of the draft standard. (But see // DESIGN NOTES above for slight differences.) // // TODO(alx): Implement a bounded-computation hash-to-curve, as described in // "Construction of Rational Points on Elliptic Curves over Finite Fields" // http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.831.5299&rep=rep1&type=pdf // and suggested by // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-01#section-5.2.2 // (Though we can't used exactly that because secp256k1's j-invariant is 0.) // // This would greatly simplify the analysis in "OTHER SECURITY CONSIDERATIONS" // https://www.pivotaltracker.com/story/show/171120900 function hashToCurve(uint256[2] memory pk, uint256 input) internal view returns (uint256[2] memory rv) { rv = newCandidateSecp256k1Point(abi.encodePacked(HASH_TO_CURVE_HASH_PREFIX, pk, input)); while (!isOnCurve(rv)) { rv = newCandidateSecp256k1Point(abi.encodePacked(rv[0])); } } /** ********************************************************************* * @notice Check that product==scalar*multiplicand * * @dev Based on Vitalik Buterin's idea in ethresear.ch post cited below. * * @param multiplicand: secp256k1 point * @param scalar: non-zero GF(GROUP_ORDER) scalar * @param product: secp256k1 expected to be multiplier * multiplicand * @return verifies true iff product==scalar*multiplicand, with cryptographically high probability */ function ecmulVerify( uint256[2] memory multiplicand, uint256 scalar, uint256[2] memory product ) internal pure returns (bool verifies) { require(scalar != 0, "scalar must not be 0"); // Rules out an ecrecover failure case uint256 x = multiplicand[0]; // x ordinate of multiplicand uint8 v = multiplicand[1] % 2 == 0 ? 27 : 28; // parity of y ordinate // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 // Point corresponding to address ecrecover(0, v, x, s=scalar*x) is // (x⁻¹ mod GROUP_ORDER) * (scalar * x * multiplicand - 0 * g), i.e. // scalar*multiplicand. See https://crypto.stackexchange.com/a/18106 bytes32 scalarTimesX = bytes32(mulmod(scalar, x, GROUP_ORDER)); address actual = ecrecover(bytes32(0), v, bytes32(x), scalarTimesX); // Explicit conversion to address takes bottom 160 bits address expected = address(uint256(keccak256(abi.encodePacked(product)))); return (actual == expected); } // Returns x1/z1-x2/z2=(x1z2-x2z1)/(z1z2) in projective coordinates on P¹(𝔽ₙ) function projectiveSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) internal pure returns (uint256 x3, uint256 z3) { uint256 num1 = mulmod(z2, x1, FIELD_SIZE); uint256 num2 = mulmod(FIELD_SIZE - x2, z1, FIELD_SIZE); (x3, z3) = (addmod(num1, num2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE)); } // Returns x1/z1*x2/z2=(x1x2)/(z1z2), in projective coordinates on P¹(𝔽ₙ) function projectiveMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) internal pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE)); } /** ************************************************************************** @notice Computes elliptic-curve sum, in projective co-ordinates @dev Using projective coordinates avoids costly divisions @dev To use this with p and q in affine coordinates, call @dev projectiveECAdd(px, py, qx, qy). This will return @dev the addition of (px, py, 1) and (qx, qy, 1), in the @dev secp256k1 group. @dev This can be used to calculate the z which is the inverse to zInv @dev in isValidVOROutput. But consider using a faster @dev This function assumes [px,py,1],[qx,qy,1] are valid projective coordinates of secp256k1 points. That is safe in this contract, because this method is only used by linearCombination, which checks points are on the curve via ecrecover. ************************************************************************** @param px The first affine coordinate of the first summand @param py The second affine coordinate of the first summand @param qx The first affine coordinate of the second summand @param qy The second affine coordinate of the second summand (px,py) and (qx,qy) must be distinct, valid secp256k1 points. ************************************************************************** Return values are projective coordinates of [px,py,1]+[qx,qy,1] as points on secp256k1, in P²(𝔽ₙ) @return sx @return sy @return sz */ function projectiveECAdd( uint256 px, uint256 py, uint256 qx, uint256 qy ) internal pure returns (uint256 sx, uint256 sy, uint256 sz) { // See "Group law for E/K : y^2 = x^3 + ax + b", in section 3.1.2, p. 80, // "Guide to Elliptic Curve Cryptography" by Hankerson, Menezes and Vanstone // We take the equations there for (sx,sy), and homogenize them to // projective coordinates. That way, no inverses are required, here, and we // only need the one inverse in affineECAdd. // We only need the "point addition" equations from Hankerson et al. Can // skip the "point doubling" equations because p1 == p2 is cryptographically // impossible, and require'd not to be the case in linearCombination. // Add extra "projective coordinate" to the two points (uint256 z1, uint256 z2) = (1, 1); // (lx, lz) = (qy-py)/(qx-px), i.e., gradient of secant line. uint256 lx = addmod(qy, FIELD_SIZE - py, FIELD_SIZE); uint256 lz = addmod(qx, FIELD_SIZE - px, FIELD_SIZE); uint256 dx; // Accumulates denominator from sx calculation // sx=((qy-py)/(qx-px))^2-px-qx (sx, dx) = projectiveMul(lx, lz, lx, lz); // ((qy-py)/(qx-px))^2 (sx, dx) = projectiveSub(sx, dx, px, z1); // ((qy-py)/(qx-px))^2-px (sx, dx) = projectiveSub(sx, dx, qx, z2); // ((qy-py)/(qx-px))^2-px-qx uint256 dy; // Accumulates denominator from sy calculation // sy=((qy-py)/(qx-px))(px-sx)-py (sy, dy) = projectiveSub(px, z1, sx, dx); // px-sx (sy, dy) = projectiveMul(sy, dy, lx, lz); // ((qy-py)/(qx-px))(px-sx) (sy, dy) = projectiveSub(sy, dy, py, z1); // ((qy-py)/(qx-px))(px-sx)-py if (dx != dy) { // Cross-multiply to put everything over a common denominator sx = mulmod(sx, dy, FIELD_SIZE); sy = mulmod(sy, dx, FIELD_SIZE); sz = mulmod(dx, dy, FIELD_SIZE); } else { // Already over a common denominator, use that for z ordinate sz = dx; } } // p1+p2, as affine points on secp256k1. // // invZ must be the inverse of the z returned by projectiveECAdd(p1, p2). // It is computed off-chain to save gas. // // p1 and p2 must be distinct, because projectiveECAdd doesn't handle // point doubling. function affineECAdd( uint256[2] memory p1, uint256[2] memory p2, uint256 invZ ) internal pure returns (uint256[2] memory) { uint256 x; uint256 y; uint256 z; (x, y, z) = projectiveECAdd(p1[0], p1[1], p2[0], p2[1]); require(mulmod(z, invZ, FIELD_SIZE) == 1, "invZ must be inverse of z"); // Clear the z ordinate of the projective representation by dividing through // by it, to obtain the affine representation return [mulmod(x, invZ, FIELD_SIZE), mulmod(y, invZ, FIELD_SIZE)]; } // True iff address(c*p+s*g) == lcWitness, where g is generator. (With // cryptographically high probability.) function verifyLinearCombinationWithGenerator( uint256 c, uint256[2] memory p, uint256 s, address lcWitness ) internal pure returns (bool) { // Rule out ecrecover failure modes which return address 0. require(lcWitness != address(0), "bad witness"); uint8 v = (p[1] % 2 == 0) ? 27 : 28; // parity of y-ordinate of p bytes32 pseudoHash = bytes32(GROUP_ORDER - mulmod(p[0], s, GROUP_ORDER)); // -s*p[0] bytes32 pseudoSignature = bytes32(mulmod(c, p[0], GROUP_ORDER)); // c*p[0] // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 // The point corresponding to the address returned by // ecrecover(-s*p[0],v,p[0],c*p[0]) is // (p[0]⁻¹ mod GROUP_ORDER)*(c*p[0]-(-s)*p[0]*g)=c*p+s*g. // See https://crypto.stackexchange.com/a/18106 // https://bitcoin.stackexchange.com/questions/38351/ecdsa-v-r-s-what-is-v address computed = ecrecover(pseudoHash, v, bytes32(p[0]), pseudoSignature); return computed == lcWitness; } // c*p1 + s*p2. Requires cp1Witness=c*p1 and sp2Witness=s*p2. Also // requires cp1Witness != sp2Witness (which is fine for this application, // since it is cryptographically impossible for them to be equal. In the // (cryptographically impossible) case that a prover accidentally derives // a proof with equal c*p1 and s*p2, they should retry with a different // proof nonce.) Assumes that all points are on secp256k1 // (which is checked in verifyVORProof below.) function linearCombination( uint256 c, uint256[2] memory p1, uint256[2] memory cp1Witness, uint256 s, uint256[2] memory p2, uint256[2] memory sp2Witness, uint256 zInv ) internal pure returns (uint256[2] memory) { require((cp1Witness[0] - sp2Witness[0]) % FIELD_SIZE != 0, "points in sum must be distinct"); require(ecmulVerify(p1, c, cp1Witness), "First multiplication check failed"); require(ecmulVerify(p2, s, sp2Witness), "Second multiplication check failed"); return affineECAdd(cp1Witness, sp2Witness, zInv); } // Domain-separation tag for the hash taken in scalarFromCurvePoints. uint256 constant SCALAR_FROM_CURVE_POINTS_HASH_PREFIX = 2; // Pseudo-random number from inputs. // TODO(alx): We could save a bit of gas by following the standard here and // using the compressed representation of the points, if we collated the y // parities into a single bytes32. // https://www.pivotaltracker.com/story/show/171120588 function scalarFromCurvePoints( uint256[2] memory hash, uint256[2] memory pk, uint256[2] memory gamma, address uWitness, uint256[2] memory v ) internal pure returns (uint256 s) { return uint256( keccak256( abi.encodePacked( SCALAR_FROM_CURVE_POINTS_HASH_PREFIX, hash, pk, gamma, v, uWitness ) ) ); } // True if (gamma, c, s) is a correctly constructed randomness proof from pk // and seed. zInv must be the inverse of the third ordinate from // projectiveECAdd applied to cGammaWitness and sHashWitness. Corresponds to // section 5.3 of the IETF draft. // // TODO(alx): Since I'm only using pk in the ecrecover call, I could only pass // the x ordinate, and the parity of the y ordinate in the top bit of uWitness // (which I could make a uint256 without using any extra space.) Would save // about 2000 gas. https://www.pivotaltracker.com/story/show/170828567 function verifyVORProof( uint256[2] memory pk, uint256[2] memory gamma, uint256 c, uint256 s, uint256 seed, address uWitness, uint256[2] memory cGammaWitness, uint256[2] memory sHashWitness, uint256 zInv ) internal view { require(isOnCurve(pk), "public key is not on curve"); require(isOnCurve(gamma), "gamma is not on curve"); require(isOnCurve(cGammaWitness), "cGammaWitness is not on curve"); require(isOnCurve(sHashWitness), "sHashWitness is not on curve"); require(verifyLinearCombinationWithGenerator(c, pk, s, uWitness), "addr(c*pk+s*g)≠_uWitness"); // Step 4. of IETF draft section 5.3 (pk corresponds to Y, seed to alpha_string) uint256[2] memory hash = hashToCurve(pk, seed); // Step 6. of IETF draft section 5.3, but see note for step 5 about +/- terms uint256[2] memory v = linearCombination( c, gamma, cGammaWitness, s, hash, sHashWitness, zInv ); // Steps 7. and 8. of IETF draft section 5.3 uint256 derivedC = scalarFromCurvePoints(hash, pk, gamma, uWitness, v); require(c == derivedC, "invalid proof"); } // Domain-separation tag for the hash used as the final VOR output. uint256 constant VOR_RANDOM_OUTPUT_HASH_PREFIX = 3; // Length of proof marshaled to bytes array. Shows layout of proof uint256 public constant PROOF_LENGTH = 64 + // PublicKey (uncompressed format.) 64 + // Gamma 32 + // C 32 + // S 32 + // Seed 0 + // Dummy entry: The following elements are included for gas efficiency: 32 + // uWitness (gets padded to 256 bits, even though it's only 160) 64 + // cGammaWitness 64 + // sHashWitness 32; // zInv (Leave Output out, because that can be efficiently calculated) /* *************************************************************************** * @notice Returns proof's output, if proof is valid. Otherwise reverts * @param proof A binary-encoded proof * * Throws if proof is invalid, otherwise: * @return output i.e., the random output implied by the proof * *************************************************************************** * @dev See the calculation of PROOF_LENGTH for the binary layout of proof. */ function randomValueFromVORProof(bytes memory proof) internal view returns (uint256 output) { require(proof.length == PROOF_LENGTH, "wrong proof length"); uint256[2] memory pk; // parse proof contents into these variables uint256[2] memory gamma; // c, s and seed combined (prevents "stack too deep" compilation error) uint256[3] memory cSSeed; address uWitness; uint256[2] memory cGammaWitness; uint256[2] memory sHashWitness; uint256 zInv; (pk, gamma, cSSeed, uWitness, cGammaWitness, sHashWitness, zInv) = abi.decode(proof, ( uint256[2], uint256[2], uint256[3], address, uint256[2], uint256[2], uint256 ) ); verifyVORProof( pk, gamma, cSSeed[0], // c cSSeed[1], // s cSSeed[2], // seed uWitness, cGammaWitness, sHashWitness, zInv ); output = uint256(keccak256(abi.encode(VOR_RANDOM_OUTPUT_HASH_PREFIX, gamma))); } } /** * @title VORRequestIDBase */ contract VORRequestIDBase { /** * @notice returns the seed which is actually input to the VOR coordinator * * @dev To prevent repetition of VOR output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VOR seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVORInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vORInputSeed The seed to be passed directly to the VOR * @return The id for this request * * @dev Note that _vORInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVORInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vORInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vORInputSeed)); } } /** * @title VORCoordinator * @dev Coordinates on-chain verifiable-randomness requests */ contract VORCoordinator is Ownable, ReentrancyGuard, VOR, VORRequestIDBase { using SafeMath for uint256; using Address for address; IERC20_Ex internal xFUND; BlockHashStoreInterface internal blockHashStore; constructor(address _xfund, address _blockHashStore) public { xFUND = IERC20_Ex(_xfund); blockHashStore = BlockHashStoreInterface(_blockHashStore); } struct Callback { // Tracks an ongoing request address callbackContract; // Requesting contract, which will receive response // Amount of xFUND paid at request time. Total xFUND = 1e9 * 1e18 < 2^96, so // this representation is adequate, and saves a word of storage when this // field follows the 160-bit callbackContract address. uint96 randomnessFee; // Commitment to seed passed to oracle by this contract, and the number of // the block in which the request appeared. This is the keccak256 of the // concatenation of those values. Storing this commitment saves a word of // storage. bytes32 seedAndBlockNum; } struct ServiceAgreement { // Tracks oracle commitments to VOR service address payable vOROracle; // Oracle committing to respond with VOR service uint96 fee; // Minimum payment for oracle response. Total xFUND=1e9*1e18<2^96 mapping(address => uint96) granularFees; // Per consumer fees if required } struct Consumer { uint256 amount; mapping(address => uint256) providers; } /* (provingKey, seed) */ mapping(bytes32 => Callback) public callbacks; /* provingKey */ mapping(bytes32 => ServiceAgreement) public serviceAgreements; /* oracle */ /* xFUND balance */ mapping(address => uint256) public withdrawableTokens; /* provingKey */ /* consumer */ mapping(bytes32 => mapping(address => uint256)) private nonces; event RandomnessRequest( bytes32 keyHash, uint256 seed, address sender, uint256 fee, bytes32 requestID ); event NewServiceAgreement(bytes32 keyHash, uint256 fee); event ChangeFee(bytes32 keyHash, uint256 fee); event ChangeGranularFee(bytes32 keyHash, address consumer, uint256 fee); event RandomnessRequestFulfilled(bytes32 requestId, uint256 output); /** * @dev getProviderAddress - get provider address * @return address */ function getProviderAddress(bytes32 _keyHash) external view returns (address) { return serviceAgreements[_keyHash].vOROracle; } /** * @dev getProviderFee - get provider's base fee * @return address */ function getProviderFee(bytes32 _keyHash) external view returns (uint96) { return serviceAgreements[_keyHash].fee; } /** * @dev getProviderGranularFee - get provider's granular fee for selected consumer * @return address */ function getProviderGranularFee(bytes32 _keyHash, address _consumer) external view returns (uint96) { if(serviceAgreements[_keyHash].granularFees[_consumer] > 0) { return serviceAgreements[_keyHash].granularFees[_consumer]; } else { return serviceAgreements[_keyHash].fee; } } /** * @notice Commits calling address to serve randomness * @param _fee minimum xFUND payment required to serve randomness * @param _oracle the address of the node with the proving key * @param _publicProvingKey public key used to prove randomness */ function registerProvingKey( uint256 _fee, address payable _oracle, uint256[2] calldata _publicProvingKey ) external { bytes32 keyHash = hashOfKey(_publicProvingKey); address oldVOROracle = serviceAgreements[keyHash].vOROracle; require(oldVOROracle == address(0), "please register a new key"); require(_oracle != address(0), "_oracle must not be 0x0"); serviceAgreements[keyHash].vOROracle = _oracle; require(_fee > 0, "fee cannot be zero"); require(_fee <= 1e9 ether, "fee too high"); serviceAgreements[keyHash].fee = uint96(_fee); emit NewServiceAgreement(keyHash, _fee); } /** * @notice Changes the provider's base fee * @param _publicProvingKey public key used to prove randomness * @param _fee minimum xFUND payment required to serve randomness */ function changeFee(uint256[2] calldata _publicProvingKey, uint256 _fee) external { bytes32 keyHash = hashOfKey(_publicProvingKey); require(serviceAgreements[keyHash].vOROracle == _msgSender(), "only oracle can change the fee"); require(_fee > 0, "fee cannot be zero"); require(_fee <= 1e9 ether, "fee too high"); serviceAgreements[keyHash].fee = uint96(_fee); emit ChangeFee(keyHash, _fee); } /** * @notice Changes the provider's fee for a consumer contract * @param _publicProvingKey public key used to prove randomness * @param _fee minimum xFUND payment required to serve randomness */ function changeGranularFee(uint256[2] calldata _publicProvingKey, uint256 _fee, address _consumer) external { bytes32 keyHash = hashOfKey(_publicProvingKey); require(serviceAgreements[keyHash].vOROracle == _msgSender(), "only oracle can change the fee"); require(_fee > 0, "fee cannot be zero"); require(_fee <= 1e9 ether, "fee too high"); serviceAgreements[keyHash].granularFees[_consumer] = uint96(_fee); emit ChangeGranularFee(keyHash, _consumer, _fee); } /** * @dev Allows the oracle operator to withdraw their xFUND * @param _recipient is the address the funds will be sent to * @param _amount is the amount of xFUND transferred from the Coordinator contract */ function withdraw(address _recipient, uint256 _amount) external hasAvailableFunds(_amount) { withdrawableTokens[_msgSender()] = withdrawableTokens[_msgSender()].sub(_amount); assert(xFUND.transfer(_recipient, _amount)); } /** * @notice creates the request for randomness * * @param _keyHash ID of the VOR public key against which to generate output * @param _consumerSeed Input to the VOR, from which randomness is generated * @param _feePaid Amount of xFUND sent with request. Must exceed fee for key * * @dev _consumerSeed is mixed with key hash, sender address and nonce to * @dev obtain preSeed, which is passed to VOR oracle, which mixes it with the * @dev hash of the block containing this request, to compute the final seed. * * @dev The requestId used to store the request data is constructed from the * @dev preSeed and keyHash. */ function randomnessRequest( bytes32 _keyHash, uint256 _consumerSeed, uint256 _feePaid ) external sufficientXFUND(_feePaid, _keyHash) { require(address(_msgSender()).isContract(), "request can only be made by a contract"); xFUND.transferFrom(_msgSender(), address(this), _feePaid); uint256 nonce = nonces[_keyHash][_msgSender()]; uint256 preSeed = makeVORInputSeed(_keyHash, _consumerSeed, _msgSender(), nonce); bytes32 requestId = makeRequestId(_keyHash, preSeed); // Cryptographically guaranteed by preSeed including an increasing nonce assert(callbacks[requestId].callbackContract == address(0)); callbacks[requestId].callbackContract = _msgSender(); assert(_feePaid < 1e27); // Total xFUND fits in uint96 callbacks[requestId].randomnessFee = uint96(_feePaid); callbacks[requestId].seedAndBlockNum = keccak256(abi.encodePacked(preSeed, block.number)); emit RandomnessRequest(_keyHash, preSeed, _msgSender(), _feePaid, requestId); nonces[_keyHash][_msgSender()] = nonces[_keyHash][_msgSender()].add(1); } /** * @notice Returns the serviceAgreements key associated with this public key * @param _publicKey the key to return the address for */ function hashOfKey(uint256[2] memory _publicKey) public pure returns (bytes32) { return keccak256(abi.encodePacked(_publicKey)); } /** * @notice Called by the node to fulfill requests * * @param _proof the proof of randomness. Actual random output built from this */ function fulfillRandomnessRequest(bytes memory _proof) public { (bytes32 currentKeyHash, Callback memory callback, bytes32 requestId, uint256 randomness) = getRandomnessFromProof(_proof); // Pay oracle address payable oracle = serviceAgreements[currentKeyHash].vOROracle; withdrawableTokens[oracle] = withdrawableTokens[oracle].add(callback.randomnessFee); // Forget request. Must precede callback (prevents reentrancy) delete callbacks[requestId]; callBackWithRandomness(requestId, randomness, callback.callbackContract); emit RandomnessRequestFulfilled(requestId, randomness); } // Offsets into fulfillRandomnessRequest's _proof of various values // // Public key. Skips byte array's length prefix. uint256 public constant PUBLIC_KEY_OFFSET = 0x20; // Seed is 7th word in proof, plus word for length, (6+1)*0x20=0xe0 uint256 public constant PRESEED_OFFSET = 0xe0; function callBackWithRandomness(bytes32 requestId, uint256 randomness, address consumerContract) internal { // Dummy variable; allows access to method selector in next line. See // https://github.com/ethereum/solidity/issues/3506#issuecomment-553727797 IVORConsumerBase v; bytes memory resp = abi.encodeWithSelector(v.rawFulfillRandomness.selector, requestId, randomness); // The bound b here comes from https://eips.ethereum.org/EIPS/eip-150. The // actual gas available to the consuming contract will be b-floor(b/64). // This is chosen to leave the consuming contract ~200k gas, after the cost // of the call itself. uint256 b = 206000; require(gasleft() >= b, "not enough gas for consumer"); // A low-level call is necessary, here, because we don't want the consuming // contract to be able to revert this execution, and thus deny the oracle // payment for a valid randomness response. This also necessitates the above // check on the gasleft, as otherwise there would be no indication if the // callback method ran out of gas. // // solhint-disable-next-line avoid-low-level-calls (bool success, ) = consumerContract.call(resp); // Avoid unused-local-variable warning. (success is only present to prevent // a warning that the return value of consumerContract.call is unused.) (success); } function getRandomnessFromProof(bytes memory _proof) internal view returns ( bytes32 currentKeyHash, Callback memory callback, bytes32 requestId, uint256 randomness ) { // blockNum follows proof, which follows length word (only direct-number // constants are allowed in assembly, so have to compute this in code) uint256 blocknumOffset = 0x20 + PROOF_LENGTH; // _proof.length skips the initial length word, so not including the // blocknum in this length check balances out. require(_proof.length == blocknumOffset, "wrong proof length"); uint256[2] memory publicKey; uint256 preSeed; uint256 blockNum; assembly { // solhint-disable-line no-inline-assembly publicKey := add(_proof, PUBLIC_KEY_OFFSET) preSeed := mload(add(_proof, PRESEED_OFFSET)) blockNum := mload(add(_proof, blocknumOffset)) } currentKeyHash = hashOfKey(publicKey); requestId = makeRequestId(currentKeyHash, preSeed); callback = callbacks[requestId]; require(callback.callbackContract != address(0), "no corresponding request"); require(callback.seedAndBlockNum == keccak256(abi.encodePacked(preSeed, blockNum)), "wrong preSeed or block num"); bytes32 blockHash = blockhash(blockNum); if (blockHash == bytes32(0)) { blockHash = blockHashStore.getBlockhash(blockNum); require(blockHash != bytes32(0), "please prove blockhash"); } // The seed actually used by the VOR machinery, mixing in the blockhash uint256 actualSeed = uint256(keccak256(abi.encodePacked(preSeed, blockHash))); // solhint-disable-next-line no-inline-assembly assembly { // Construct the actual proof from the remains of _proof mstore(add(_proof, PRESEED_OFFSET), actualSeed) mstore(_proof, PROOF_LENGTH) } randomness = VOR.randomValueFromVORProof(_proof); // Reverts on failure } /** * @dev Reverts if amount is not at least what was agreed upon in the service agreement * @param _feePaid The payment for the request * @param _keyHash The key which the request is for */ modifier sufficientXFUND(uint256 _feePaid, bytes32 _keyHash) { if(serviceAgreements[_keyHash].granularFees[_msgSender()] > 0) { require(_feePaid >= serviceAgreements[_keyHash].granularFees[_msgSender()], "Below agreed payment"); } else { require(_feePaid >= serviceAgreements[_keyHash].fee, "Below agreed payment"); } _; } /** * @dev Reverts if amount requested is greater than withdrawable balance * @param _amount The given amount to compare to `withdrawableTokens` */ modifier hasAvailableFunds(uint256 _amount) { require(withdrawableTokens[_msgSender()] >= _amount, "can't withdraw more than balance"); _; } }
((qy-py)/(qx-px))^2
(sx, dx) = projectiveMul(lx, lz, lx, lz);
14,443,703
[ 1, 12443, 85, 93, 17, 2074, 13176, 12, 85, 92, 17, 4430, 3719, 66, 22, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 261, 30319, 16, 6633, 13, 273, 1984, 688, 27860, 12, 80, 92, 16, 328, 94, 16, 15855, 16, 328, 94, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x6F33c38298a1D50fdae35af410Bba2D6eF1CFead/sources/lib/revenue-distribution-token/contracts/interfaces/IERC4626.sol
@title A standard for tokenized Vaults with a single underlying ERC-20 token.
interface IERC4626 is IERC20 { event Deposit(address indexed caller_, address indexed owner_, uint256 assets_, uint256 shares_); event Withdraw(address indexed caller_, address indexed receiver_, address indexed owner_, uint256 assets_, uint256 shares_); function asset() external view returns (address asset_); function deposit(uint256 assets_, address receiver_) external returns (uint256 shares_); function mint(uint256 shares_, address receiver_) external returns (uint256 assets_); function redeem(uint256 shares_, address receiver_, address owner_) external returns (uint256 assets_); function withdraw(uint256 assets_, address receiver_, address owner_) external returns (uint256 shares_); function convertToAssets(uint256 shares_) external view returns (uint256 assets_); function convertToShares(uint256 assets_) external view returns (uint256 shares_); function maxDeposit(address receiver_) external view returns (uint256 assets_); function maxMint(address receiver_) external view returns (uint256 shares_); function maxRedeem(address owner_) external view returns (uint256 shares_); function maxWithdraw(address owner_) external view returns (uint256 assets_); function previewDeposit(uint256 assets_) external view returns (uint256 shares_); function previewMint(uint256 shares_) external view returns (uint256 assets_); function previewRedeem(uint256 shares_) external view returns (uint256 assets_); function previewWithdraw(uint256 assets_) external view returns (uint256 shares_); function totalAssets() external view returns (uint256 totalAssets_); pragma solidity 0.8.7; import { IERC20 } from "erc20/interfaces/IERC20.sol"; }
7,053,934
[ 1, 37, 4529, 364, 26073, 17329, 87, 598, 279, 2202, 6808, 4232, 39, 17, 3462, 1147, 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, 5831, 467, 654, 39, 8749, 5558, 353, 467, 654, 39, 3462, 288, 203, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 4894, 67, 16, 1758, 8808, 3410, 67, 16, 2254, 5034, 7176, 67, 16, 2254, 5034, 24123, 67, 1769, 203, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 4894, 67, 16, 1758, 8808, 5971, 67, 16, 1758, 8808, 3410, 67, 16, 2254, 5034, 7176, 67, 16, 2254, 5034, 24123, 67, 1769, 203, 203, 203, 565, 445, 3310, 1435, 3903, 1476, 1135, 261, 2867, 3310, 67, 1769, 203, 203, 203, 565, 445, 443, 1724, 12, 11890, 5034, 7176, 67, 16, 1758, 5971, 67, 13, 3903, 1135, 261, 11890, 5034, 24123, 67, 1769, 203, 203, 565, 445, 312, 474, 12, 11890, 5034, 24123, 67, 16, 1758, 5971, 67, 13, 3903, 1135, 261, 11890, 5034, 7176, 67, 1769, 203, 203, 565, 445, 283, 24903, 12, 11890, 5034, 24123, 67, 16, 1758, 5971, 67, 16, 1758, 3410, 67, 13, 3903, 1135, 261, 11890, 5034, 7176, 67, 1769, 203, 203, 565, 445, 598, 9446, 12, 11890, 5034, 7176, 67, 16, 1758, 5971, 67, 16, 1758, 3410, 67, 13, 3903, 1135, 261, 11890, 5034, 24123, 67, 1769, 203, 203, 203, 565, 445, 8137, 10726, 12, 11890, 5034, 24123, 67, 13, 3903, 1476, 1135, 261, 11890, 5034, 7176, 67, 1769, 203, 203, 565, 445, 8137, 24051, 12, 11890, 5034, 7176, 67, 13, 3903, 1476, 1135, 261, 11890, 5034, 24123, 67, 1769, 203, 203, 565, 445, 943, 758, 1724, 12, 2867, 5971, 67, 13, 3903, 1476, 1135, 261, 11890, 5034, 2 ]