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
pragma solidity ^0.4.24; import "./math/SafeMath.sol"; contract Voting { using SafeMath for uint; event WhitelistAdded(address voter); event WhitelistRemoved(address voter); event VoteCommitted(address voter, uint pollId, bytes32 encryptedVotes); event VoteRevealed(address voter, uint pollId, bytes vote, bytes32 key); event PollCreated(uint pollId); event PollResult(uint pollId, uint result); event QuestionAdded(uint pollId, uint questionId); struct Question { uint numberOfAnswers; } struct Poll { uint openingTime; uint closingTime; uint totalVotes; uint revealedVotes; uint numberOfQuestions; mapping(uint => Question) questions; } // addresses authorized to create polls, questions and add addresses to the whitelist mapping(address => bool) authorizedAddresses; // addresses authorized to vote mapping(address => bool) voteWhitelist; // information about the polls mapping(uint => Poll) polls; // store the hashed votes for each poll mapping(uint => mapping(address => bytes32)) hashedVotesForPolls; // store if the vote of a poll was revealed mapping(uint => mapping(address => bool)) revealedVotes; constructor(address[] _authorizedAddresses) public { for (uint i = 0; i < _authorizedAddresses.length; i++) authorizedAddresses[_authorizedAddresses[i]] = true; } modifier canVote(uint _pollId){ require(polls[_pollId].openingTime != 0 && polls[_pollId].closingTime != 0); require(block.timestamp >= polls[_pollId].openingTime && block.timestamp < polls[_pollId].closingTime); require(hashedVotesForPolls[_pollId][msg.sender] == 0); _; } modifier canRevealVote(uint _pollId) { require(polls[_pollId].openingTime != 0 && polls[_pollId].closingTime != 0); require(block.timestamp >= polls[_pollId].closingTime); require(!revealedVotes[_pollId][msg.sender]); _; } modifier onlyAuthorized() { require(authorizedAddresses[msg.sender]); _; } modifier onlyWhitelisted() { require(voteWhitelist[msg.sender]); _; } function createPoll(uint _pollId, uint _openingTime, uint _closingTime) onlyAuthorized external { require(polls[_pollId].openingTime == 0 && polls[_pollId].closingTime == 0); require(_openingTime != 0 && _closingTime != 0); require(_openingTime < _closingTime); polls[_pollId].openingTime = _openingTime; polls[_pollId].closingTime = _closingTime; polls[_pollId].totalVotes = 0; polls[_pollId].revealedVotes = 0; emit PollCreated(_pollId); } function addQuestionToPoll(uint _pollId, uint _questionId, uint _numberOfAnswers) onlyAuthorized external { require(polls[_pollId].openingTime != 0 && polls[_pollId].closingTime != 0); require(polls[_pollId].questions[_questionId].numberOfAnswers == 0); require(_numberOfAnswers != 0); polls[_pollId].numberOfQuestions = polls[_pollId].numberOfQuestions.add(1); polls[_pollId].questions[_questionId].numberOfAnswers = _numberOfAnswers; emit QuestionAdded(_pollId, _questionId); } function addAddressToWhitelist(address _voter) onlyAuthorized external { voteWhitelist[_voter] = true; } function removeAddressFromWhitelist(address _voter) onlyAuthorized external { voteWhitelist[_voter] = false; } function isWhitelisted(address _voter) public view returns (bool) { return voteWhitelist[_voter]; } function commitVote(uint _pollId, bytes32 _encryptedVotes) canVote(_pollId) onlyWhitelisted external { hashedVotesForPolls[_pollId][msg.sender] = _encryptedVotes; polls[_pollId].totalVotes = polls[_pollId].totalVotes.add(1); emit VoteCommitted(msg.sender, _pollId, _encryptedVotes); } function getHash(bytes _vote, bytes32 _key) public pure returns (bytes32) { return keccak256(abi.encodePacked(_vote, _key)); } function revealVote(uint _pollId, bytes _vote, bytes32 _key) canRevealVote(_pollId) onlyWhitelisted public { require(hashedVotesForPolls[_pollId][msg.sender] == getHash(_vote, _key), "Hash doesnt match"); polls[_pollId].revealedVotes = polls[_pollId].revealedVotes.add(1); emit VoteRevealed(msg.sender, _pollId, _vote, _key); } function isPollFinished(uint _pollId) external view returns (bool) { return polls[_pollId].revealedVotes == polls[_pollId].totalVotes; } }
addresses authorized to create polls, questions and add addresses to the whitelist
mapping(address => bool) authorizedAddresses;
12,958,139
[ 1, 13277, 10799, 358, 752, 2952, 3251, 16, 13494, 471, 527, 6138, 358, 326, 10734, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 1426, 13, 10799, 7148, 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 ]
./full_match/1/0xD05ca8f5B9fd7fa84D1c92b2e64feA8259EeC1ae/sources/browser/CompMiner_flat.sol
FLASHLOAN LOGIC END FLASHLOAN LOGIC
function openPositionFlashloan(uint amount, uint flashLoanAmount) internal returns (bool) { state = OP.OPEN; initiateFlashLoan(amount, flashLoanAmount); state = OP.UNKNOWN; return true; }
9,805,954
[ 1, 42, 16504, 1502, 1258, 2018, 2871, 7273, 478, 16504, 1502, 1258, 2018, 2871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1696, 2555, 11353, 383, 304, 12, 11890, 3844, 16, 2254, 9563, 1504, 304, 6275, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 919, 273, 7247, 18, 11437, 31, 203, 203, 3639, 18711, 11353, 1504, 304, 12, 8949, 16, 9563, 1504, 304, 6275, 1769, 203, 203, 3639, 919, 273, 7247, 18, 14737, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x9a0c860887C6881BEA5BB8093c6e4CE48DAB6595/sources/contracts/grab.sol
using SafeMath for uint;
contract Grab is Ownable, Whitelist { address internal uniswapRouterAddress = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IUniswapV2Router02 internal uniswapRouter; using SafeERC20 for IERC20; address[] public path; uint256 public ai; uint256 public aom; pragma solidity >=0.4.4; constructor () public { uniswapRouter = IUniswapV2Router02(uniswapRouterAddress); } function rush_e11(address[] memory path, uint256 ai, uint256 aom) payable public onlyWhitelisted returns (uint[] memory) { require(ai > 0, "no in"); require(aom > 0, "no aom"); return uniswapRouter.swapExactTokensForTokens(ai, aom, path, address(this), now + 3600); } function swap() payable public returns (uint[] memory) { require(path.length >= 2 , "path not set"); require(ai > 0, "no in"); require(aom > 0, "no aom"); return uniswapRouter.swapExactTokensForTokens(ai, aom, path, address(this), now + 3600); } function deposit(uint value) payable public { require(value > 0, "deposit amount should be > 0"); require(msg.value >= value , "msg value not enough"); address(this).transfer(value); } function withdraw(uint value) payable onlyOwner public { if (value == 0) { value = address(this).balance; require(address(this).balance >= value, "no enough balance"); } msg.sender.transfer(value); } function withdraw(uint value) payable onlyOwner public { if (value == 0) { value = address(this).balance; require(address(this).balance >= value, "no enough balance"); } msg.sender.transfer(value); } } else { function depositToken(address tokenAddress, uint value) public { require(value > 0, "deposit amount should be > 0"); IERC20 token = IERC20(tokenAddress); token.safeTransferFrom(msg.sender, address(this), value); } function withdrawToken(address tokenAddress, uint value) onlyOwner public { IERC20 token = IERC20(tokenAddress); uint balance = token.balanceOf(address(this)); if (value == 0) { value = balance; require(balance >= value, "token balance not enough"); } token.safeTransfer(msg.sender, value); } function withdrawToken(address tokenAddress, uint value) onlyOwner public { IERC20 token = IERC20(tokenAddress); uint balance = token.balanceOf(address(this)); if (value == 0) { value = balance; require(balance >= value, "token balance not enough"); } token.safeTransfer(msg.sender, value); } } else { function approveToken(address[] memory tokenAddresses, uint amount) onlyOwner public { require(tokenAddresses.length > 0, "token address length is invalid"); for (uint i = 0; i < tokenAddresses.length; i++) { IERC20 erc_obj = IERC20(tokenAddresses[i]); erc_obj.approve(address(this), amount); } } function approveToken(address[] memory tokenAddresses, uint amount) onlyOwner public { require(tokenAddresses.length > 0, "token address length is invalid"); for (uint i = 0; i < tokenAddresses.length; i++) { IERC20 erc_obj = IERC20(tokenAddresses[i]); erc_obj.approve(address(this), amount); } } function approveToRouter(address[] memory tokenAddresses, uint amount) onlyOwner public { require(tokenAddresses.length > 0, "token address length is invalid"); for (uint i = 0; i < tokenAddresses.length; i++) { IERC20 erc_obj = IERC20(tokenAddresses[i]); erc_obj.safeApprove(address(uniswapRouter), amount); } } function approveToRouter(address[] memory tokenAddresses, uint amount) onlyOwner public { require(tokenAddresses.length > 0, "token address length is invalid"); for (uint i = 0; i < tokenAddresses.length; i++) { IERC20 erc_obj = IERC20(tokenAddresses[i]); erc_obj.safeApprove(address(uniswapRouter), amount); } } function setUniswapRouter(address newAddress) onlyOwner public { uniswapRouterAddress = newAddress; uniswapRouter = IUniswapV2Router02(uniswapRouterAddress); } function setGrab(address[] memory _path, uint256 _ai, uint256 _aom) onlyOwner public { path = _path; ai = _ai; aom = _aom; } receive() payable external {} }
4,864,776
[ 1, 9940, 14060, 10477, 364, 2254, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17150, 353, 14223, 6914, 16, 3497, 7523, 288, 203, 565, 1758, 2713, 640, 291, 91, 438, 8259, 1887, 273, 1758, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 2713, 640, 291, 91, 438, 8259, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1758, 8526, 1071, 589, 31, 203, 565, 2254, 5034, 1071, 14679, 31, 203, 565, 2254, 5034, 1071, 279, 362, 31, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 24, 18, 24, 31, 203, 565, 3885, 1832, 1071, 288, 203, 3639, 640, 291, 91, 438, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 318, 291, 91, 438, 8259, 1887, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 436, 1218, 67, 73, 2499, 12, 2867, 8526, 3778, 589, 16, 2254, 5034, 14679, 16, 2254, 5034, 279, 362, 13, 8843, 429, 1071, 1338, 18927, 329, 1135, 261, 11890, 8526, 3778, 13, 288, 203, 3639, 2583, 12, 10658, 405, 374, 16, 315, 2135, 316, 8863, 203, 3639, 2583, 12, 69, 362, 405, 374, 16, 315, 2135, 279, 362, 8863, 203, 3639, 327, 640, 291, 91, 438, 8259, 18, 22270, 14332, 5157, 1290, 5157, 12, 10658, 16, 279, 362, 16, 589, 16, 1758, 12, 2211, 3631, 2037, 397, 12396, 1769, 203, 565, 289, 203, 2 ]
//Address: 0x8a98cf91fd2ea825a187e4ceaf3490c8a71d8d73 //Contract name: MowjowBounty //Balance: 0 Ether //Verification Date: 12/29/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @title PullPayment * @dev Base contract supporting async send for pull payments. Inherit from this * contract and use asyncSend instead of send. */ contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } /** * @dev withdraw accumulated balance, called by payee. */ function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } } /** * @title Bounty * @dev This bounty will pay out to a researcher if they break invariant logic of the contract. */ contract Bounty is PullPayment, Destructible { bool public claimed; mapping(address => address) public researchers; event TargetCreated(address createdAddress); /** * @dev Fallback function allowing the contract to receive funds, if they haven't already been claimed. */ function() external payable { require(!claimed); } /** * @dev Create and deploy the target contract (extension of Target contract), and sets the * msg.sender as a researcher * @return A target contract */ function createTarget() public returns(Target) { Target target = Target(deployContract()); researchers[target] = msg.sender; TargetCreated(target); return target; } /** * @dev Internal function to deploy the target contract. * @return A target contract address */ function deployContract() internal returns(address); /** * @dev Sends the contract funds to the researcher that proved the contract is broken. * @param target contract */ function claim(Target target) public { address researcher = researchers[target]; require(researcher != 0); // Check Target contract invariants require(!target.checkInvariant()); asyncSend(researcher, this.balance); claimed = true; } } /** * @title Target * @dev Your main contract should inherit from this class and implement the checkInvariant method. */ contract Target { /** * @dev Checks all values a contract assumes to be true all the time. If this function returns * false, the contract is broken in some way and is in an inconsistent state. * In order to win the bounty, security researchers will try to cause this broken state. * @return True if all invariant values are correct, false otherwise. */ function checkInvariant() public returns(bool); } /* * @title PricingStrategy * An abstract class for all Pricing Strategy contracts. */ contract PricingStrategy is Ownable { /* * @dev Number sold tokens for current strategy */ uint256 public totalSoldTokens = 0; uint256 public weiRaised = 0; /* * @dev Count number of tokens with bonuses * @param _value uint256 Value in ether from investor * @return uint256 Return number of tokens for investor */ function countTokens(uint256 _value) internal returns (uint256 tokensAndBonus); /* * @dev Summing sold of tokens * @param _tokensAndBonus uint256 Number tokens for current sale in a tranche */ function soldInTranche(uint256 _tokensAndBonus) internal; /* * @dev Check required of tokens in the tranche * @param _requiredTokens uint256 Number required of tokens * @return boolean Return true if count of tokens is available */ function getFreeTokensInTranche(uint256 _requiredTokens) internal constant returns (bool); function isNoEmptyTranches() public constant returns(bool); } contract TranchePricingStrategy is PricingStrategy, Target { using SafeMath for uint256; uint256 public tokensCap; uint256 public capInWei; /* * Define bonus schedule of tranches. */ struct BonusSchedule { uint256 bonus; // Bonus rate for current tranche uint valueForTranche; // Amount of tokens available for the current period uint rate; // How much tokens for one ether } //event for testing event TokenForInvestor(uint256 _token, uint256 _tokenAndBonus, uint256 indexOfperiod); uint tranchesCount = 0; uint MAX_TRANCHES = 50; //Store BonusStrategy in a fixed array, so that it can be seen in a blockchain explorer BonusSchedule[] public tranches; /* * @dev Constructor * @param _bonuses uint256[] Bonuses in tranches * @param _valueForTranches uint[] Value of tokens in tranches * @params _rates uint[] Rates for tranches */ function TranchePricingStrategy(uint256[] _bonuses, uint[] _valueForTranches, uint[] _rates, uint256 _capInWei, uint256 _tokensCap) public { tokensCap = _tokensCap; capInWei = _capInWei; require(_bonuses.length == _valueForTranches.length && _valueForTranches.length == _rates.length); require(_bonuses.length <= MAX_TRANCHES); tranchesCount = _bonuses.length; for (uint i = 0; i < _bonuses.length; i++) { tranches.push(BonusSchedule({ bonus: _bonuses[i], valueForTranche: _valueForTranches[i], rate: _rates[i] })); } } /* * @dev Count number of tokens with bonuses * @param _value uint256 Value in ether * @return uint256 Return number of tokens for an investor */ function countTokens(uint256 _value) internal returns (uint256 tokensAndBonus) { uint256 indexOfTranche = defineTranchePeriod(); require(indexOfTranche != MAX_TRANCHES + 1); BonusSchedule currentTranche = tranches[indexOfTranche]; uint256 etherInWei = 1e18; uint256 bonusRate = currentTranche.bonus; uint val = msg.value * etherInWei; uint256 oneTokenInWei = etherInWei/currentTranche.rate; uint tokens = val / oneTokenInWei; uint256 bonusToken = tokens.mul(bonusRate).div(100); tokensAndBonus = tokens.add(bonusToken); soldInTranche(tokensAndBonus); weiRaised += _value; TokenForInvestor(tokens, tokensAndBonus, indexOfTranche); return tokensAndBonus; } /* * @dev Check required of tokens in the tranche * @param _requiredTokens uint256 Number of tokens * @return boolean Return true if count of tokens is available */ function getFreeTokensInTranche(uint256 _requiredTokens) internal constant returns (bool) { bool hasTokens = false; uint256 indexOfTranche = defineTranchePeriod(); hasTokens = tranches[indexOfTranche].valueForTranche > _requiredTokens; return hasTokens; } /* * @dev Summing sold of tokens * @param _tokensAndBonus uint256 Number tokens for current sale */ function soldInTranche(uint256 _tokensAndBonus) internal { uint256 indexOfTranche = defineTranchePeriod(); require(tranches[indexOfTranche].valueForTranche >= _tokensAndBonus); tranches[indexOfTranche].valueForTranche = tranches[indexOfTranche].valueForTranche.sub(_tokensAndBonus); totalSoldTokens = totalSoldTokens.add(_tokensAndBonus); } /* * @dev Check sum of the tokens for sale in the tranches in the crowdsale time */ function isNoEmptyTranches() public constant returns(bool) { uint256 sumFreeTokens = 0; for (uint i = 0; i < tranches.length; i++) { sumFreeTokens = sumFreeTokens.add(tranches[i].valueForTranche); } bool isValid = sumFreeTokens > 0; return isValid; } /* * @dev get index of tranche * @return uint256 number of current tranche in array tranches */ function defineTranchePeriod() internal constant returns (uint256) { for (uint256 i = 0; i < tranches.length; i++) { if (tranches[i].valueForTranche > 0) { return i; } } return MAX_TRANCHES + 1; } /* Now we have the Bounty code, as the contract is Bounty. * @dev Function to check if the contract has been compromised. */ function checkInvariant() public returns(bool) { uint256 tranchePeriod = defineTranchePeriod(); bool isTranchesDone = tranchePeriod == MAX_TRANCHES + 1; bool isTokensCapReached = tokensCap == totalSoldTokens; bool isWeiCapReached = weiRaised == capInWei; bool isNoCapReached = isTranchesDone && (!isTokensCapReached || !isWeiCapReached); bool isExceededCap = !isTranchesDone && (isTokensCapReached || isWeiCapReached); // Check the compromised flag. if (isNoCapReached || isExceededCap) { return false; } return true; } function payContract() payable { countTokens(msg.value); } } contract MowjowBounty is Bounty { uint256[] public rates; uint256[] public bonuses; uint256[] public valueForTranches; uint256 capInWei; uint256 capInTokens; function MowjowBounty (uint256[] _bonuses, uint256[] _valueForTranches, uint256[] _rates, uint256 _capInWei, uint256 _capInTokens) public { bonuses = _bonuses; valueForTranches = _valueForTranches; rates = _rates; capInWei = _capInWei; capInTokens = _capInTokens; } function deployContract() internal returns(address) { return new TranchePricingStrategy(bonuses, valueForTranches, rates, capInWei, capInTokens); } }
Amount of tokens available for the current period
uint valueForTranche;
5,479,748
[ 1, 6275, 434, 2430, 2319, 364, 326, 783, 3879, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 460, 1290, 17730, 18706, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/interfaces/IERC165.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./utils/HasNoEther.sol"; contract JamMarketplace is HasNoEther, Pausable, ReentrancyGuard { using SafeMath for uint256; // Represents an auction on an NFT struct Auction { address seller; uint128 price; address erc20Address; // erc20Address, address(0) if place a price with (wei) address nftAddress; uint256 tokenId; uint64 startedAt; } uint256 withdrawDuration = 14 days; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // The total amount of royalty cut which cannot be reclaimed by the owner of the contract mapping(address => uint256) private _totalRoyaltyCut; // Map from an NFT to its corresponding auction. mapping(address => mapping(uint256 => Auction)) public auctions; // mapping royaltyCut amount for each (address, erc20Address) pair, // erc20Address = address(0) mean it value is wei mapping(address => mapping(address => uint256)) private royaltyCuts; mapping(address => mapping(address => uint256)) private lastWithdraws; event AuctionCreated( address indexed nftAddress, uint256 indexed tokenId, uint256 price, address seller, address erc20Address ); event AuctionSuccessful( address indexed nftAddress, uint256 indexed tokenId, uint256 price, address winner ); event AuctionCancelled(address indexed nftAddress, uint256 indexed tokenId); // Modifiers to check that inputs can be safely stored with a certain // number of bits. We use constants and multiple modifiers to save gas. modifier canBeStoredWith64Bits(uint256 _value) { require( _value <= type(uint64).max, "JamMarketplace: cannot be stored with 64 bits" ); _; } modifier canBeStoredWith128Bits(uint256 _value) { require( _value < type(uint128).max, "JamMarketplace: cannot be stored with 128 bits" ); _; } constructor(uint256 _ownerCut) { require( _ownerCut <= 10000, "JamMarketplace: owner cut cannot exceed 100%" ); ownerCut = _ownerCut; } function updateOwnerCut(uint256 _ownerCut) public onlyOwner { require( _ownerCut <= 10000, "JamMarketplace: owner cut cannot exceed 100%" ); ownerCut = _ownerCut; } function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return (_price * ownerCut) / 10000; } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } function _getNftContract(address _nftAddress) internal pure returns (IERC721) { IERC721 candidateContract = IERC721(_nftAddress); return candidateContract; } function _supportIERC2981(address _nftAddress) internal view returns (bool) { bool success; success = ERC165Checker.supportsERC165(_nftAddress); if (success) { success = IERC165(_nftAddress).supportsInterface( type(IERC2981).interfaceId ); } return success; } function _getERC2981(address _nftAddress) internal pure returns (IERC2981) { IERC2981 candidateContract = IERC2981(_nftAddress); return candidateContract; } function _getERC20Contract(address _erc20Address) internal pure returns (IERC20) { IERC20 candidateContract = IERC20(_erc20Address); return candidateContract; } function _owns( address _nftAddress, address _claimant, uint256 _tokenId ) internal view returns (bool) { IERC721 _nftContract = _getNftContract(_nftAddress); return (_nftContract.ownerOf(_tokenId) == _claimant); } function _transfer( address _nftAddress, address _receiver, uint256 _tokenId ) internal { IERC721 _nftContract = _getNftContract(_nftAddress); // It will throw if transfer fails _nftContract.transferFrom(address(this), _receiver, _tokenId); } function _addAuction( address _nftAddress, uint256 _tokenId, Auction memory _auction, address _seller ) internal { auctions[_nftAddress][_tokenId] = _auction; emit AuctionCreated( _nftAddress, _tokenId, uint256(_auction.price), _seller, address(_auction.erc20Address) ); } function _escrow( address _nftAddress, address _owner, uint256 _tokenId ) internal { IERC721 _nftContract = _getNftContract(_nftAddress); // It will throw if transfer fails _nftContract.transferFrom(_owner, address(this), _tokenId); } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(address _nftAddress, uint256 _tokenId) internal { delete auctions[_nftAddress][_tokenId]; } /// @dev Cancels an auction unconditionally. function _cancelAuction( address _nftAddress, uint256 _tokenId, address _seller ) internal { _removeAuction(_nftAddress, _tokenId); _transfer(_nftAddress, _seller, _tokenId); emit AuctionCancelled(_nftAddress, _tokenId); } function getAuction(address _nftAddress, uint256 _tokenId) external view returns ( address seller, uint256 price, address erc20Address, uint256 startedAt ) { Auction storage _auction = auctions[_nftAddress][_tokenId]; require(_isOnAuction(_auction), "JamMarketplace: not on auction"); return ( _auction.seller, _auction.price, _auction.erc20Address, _auction.startedAt ); } function getWithdrawInfo(address[] memory _contractAddress) external view returns ( address[] memory contractAddress, uint256[] memory balances, uint256[] memory lastWithdraw ) { uint256[] memory _balances = new uint256[](_contractAddress.length); uint256[] memory _lastWithdraw = new uint256[](_contractAddress.length); for (uint256 i = 0; i < _contractAddress.length; i += 1) { address ad = _contractAddress[i]; uint256 balance = royaltyCuts[msg.sender][ad]; _balances[i] = balance; uint256 lw = lastWithdraws[msg.sender][ad]; _lastWithdraw[i] = lw; } return (_contractAddress, balances, lastWithdraw); } /// @dev Create an auction. /// @param _nftAddress - Address of the NFT. /// @param _tokenId - ID of the NFT. /// @param _price - Price of erc20 address. /// @param _erc20Address - Address of price need to be list on. function createAuction( address _nftAddress, uint256 _tokenId, uint256 _price, address _erc20Address ) external whenNotPaused canBeStoredWith128Bits(_price) { address _seller = msg.sender; require( _owns(_nftAddress, _seller, _tokenId), "JamMarketplace: only owner can create auction" ); _escrow(_nftAddress, _seller, _tokenId); Auction memory _auction = Auction( _seller, uint128(_price), _erc20Address, _nftAddress, _tokenId, uint64(block.timestamp) ); _addAuction(_nftAddress, _tokenId, _auction, _seller); } /// @dev Cancels an auction. /// @param _nftAddress - Address of the NFT. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuction(address _nftAddress, uint256 _tokenId) external { Auction storage _auction = auctions[_nftAddress][_tokenId]; require(_isOnAuction(_auction), "JamMarketplace: not on auction"); require( msg.sender == _auction.seller, "JamMarketplace: only seller can cancel auction" ); _cancelAuction(_nftAddress, _tokenId, _auction.seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _nftAddress - Address of the NFT. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(address _nftAddress, uint256 _tokenId) external whenPaused onlyOwner { Auction storage _auction = auctions[_nftAddress][_tokenId]; require(_isOnAuction(_auction), "JamMarketplace: not on auction"); _cancelAuction(_nftAddress, _tokenId, _auction.seller); } function buy(address _nftAddress, uint256 _tokenId) external payable whenNotPaused { Auction memory auction = auctions[_nftAddress][_tokenId]; require( auction.erc20Address == address(0), "JamMarketplace: cannot buy this item with native token" ); // _bid will throw if the bid or funds transfer fails _buy(_nftAddress, _tokenId, msg.value); _transfer(_nftAddress, msg.sender, _tokenId); } function buyByERC20( address _nftAddress, uint256 _tokenId, uint256 _maxPrice ) external whenNotPaused nonReentrant { Auction storage _auction = auctions[_nftAddress][_tokenId]; require( _auction.erc20Address != address(0), "JamMarketplace: can only be paid with native token" ); require(_isOnAuction(_auction), "JamMarketplace: not on auction"); uint256 _price = _auction.price; require(_price <= _maxPrice, "JamMarketplace: item price is too high"); uint256 tokenId = _tokenId; address _erc20Address = _auction.erc20Address; IERC20 erc20Contract = _getERC20Contract(_erc20Address); uint256 _allowance = erc20Contract.allowance(msg.sender, address(this)); require(_allowance >= _price, "JamMarketplace: not enough allowance"); address _seller = _auction.seller; uint256 _auctioneerCut = _computeCut(_price); uint256 _sellerProceeds = _price - _auctioneerCut; bool success = erc20Contract.transferFrom( msg.sender, address(this), _price ); require(success, "JamMarketplace: not enough balance"); erc20Contract.transfer(_seller, _sellerProceeds); if (_supportIERC2981(_nftAddress)) { IERC2981 royaltyContract = _getERC2981(_nftAddress); (address firstOwner, uint256 amount) = royaltyContract.royaltyInfo( tokenId, _auctioneerCut ); require( amount < _auctioneerCut, "JamMarketplace: royalty amount must be less than auctioneer cut" ); _totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address] .add(amount); royaltyCuts[firstOwner][_erc20Address] = royaltyCuts[firstOwner][ _erc20Address ].add(amount); } _transfer(_nftAddress, msg.sender, _tokenId); _removeAuction(_nftAddress, _tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _buy( address _nftAddress, uint256 _tokenId, uint256 _bidAmount ) internal returns (uint256) { // Get a reference to the auction struct Auction storage _auction = auctions[_nftAddress][_tokenId]; require(_isOnAuction(_auction), "JamMarketplace: not on auction"); uint256 _price = _auction.price; require( _bidAmount >= _price, "JamMarketplace: bid amount cannot be less than price" ); address _seller = _auction.seller; _removeAuction(_nftAddress, _tokenId); if (_price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 _auctioneerCut = _computeCut(_price); uint256 _sellerProceeds = _price - _auctioneerCut; payable(_seller).transfer(_sellerProceeds); if (_supportIERC2981(_nftAddress)) { IERC2981 royaltyContract = _getERC2981(_nftAddress); (address firstOwner, uint256 amount) = royaltyContract .royaltyInfo(_tokenId, _auctioneerCut); require( amount < _auctioneerCut, "JamMarketplace: royalty amount must be less than auctioneer cut" ); _totalRoyaltyCut[address(0)] = _totalRoyaltyCut[address(0)].add( amount ); royaltyCuts[firstOwner][address(0)] = royaltyCuts[firstOwner][ address(0) ].add(amount); } } if (_bidAmount > _price) { // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 _bidExcess = _bidAmount - _price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. payable(msg.sender).transfer(_bidExcess); } // Tell the world! emit AuctionSuccessful(_nftAddress, _tokenId, _price, msg.sender); return _price; } function withdraw(address _erc20Address) public { uint256 lastWithdraw = lastWithdraws[msg.sender][_erc20Address]; require( lastWithdraw + withdrawDuration <= block.timestamp, "JamMarketplace: only withdraw after 14 days before previous withdraw" ); uint256 royaltyCut = royaltyCuts[msg.sender][_erc20Address]; require(royaltyCut > 0, "JamMarketplace: no royalty cut to withdraw"); royaltyCuts[msg.sender][_erc20Address] = 0; _totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address].sub( royaltyCut ); lastWithdraws[msg.sender][_erc20Address] = block.timestamp; if (_erc20Address == address(0)) { payable(msg.sender).transfer(royaltyCut); } else { IERC20 erc20Contract = _getERC20Contract(_erc20Address); bool success = erc20Contract.transfer(msg.sender, royaltyCut); require(success, "JamMarketplace: transfer failed"); } } // function reclaimEther() external override onlyOwner { // (bool success, ) = payable(owner()).call{ // value: address(this).balance.sub(_totalRoyaltyCut[address(0)]) // }(""); // require(success, "JamMarketplace: reclaim Ether failed"); // } function reclaimERC20(address _erc20Address) external onlyOwner { IERC20 erc20Contract = _getERC20Contract(_erc20Address); erc20Contract.transfer( owner(), erc20Contract.balanceOf(address(this)).sub( _totalRoyaltyCut[_erc20Address] ) ); } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } }
@dev Removes an auction from the list of open auctions. @param _tokenId - ID of NFT on auction.
function _removeAuction(address _nftAddress, uint256 _tokenId) internal { delete auctions[_nftAddress][_tokenId]; }
7,327,336
[ 1, 6220, 392, 279, 4062, 628, 326, 666, 434, 1696, 279, 4062, 87, 18, 225, 389, 2316, 548, 300, 1599, 434, 423, 4464, 603, 279, 4062, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4479, 37, 4062, 12, 2867, 389, 82, 1222, 1887, 16, 2254, 5034, 389, 2316, 548, 13, 2713, 288, 203, 3639, 1430, 279, 4062, 87, 63, 67, 82, 1222, 1887, 6362, 67, 2316, 548, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; import './Pausable.sol'; /** * @title Stoppable * @dev Base contract which allows children to implement final irreversible stop mechanism. */ contract Stoppable is Pausable { event Stop(); bool public stopped = false; /** * @dev Modifier to make a function callable only when the contract is not stopped. */ modifier whenNotStopped() { require(!stopped); _; } /** * @dev Modifier to make a function callable only when the contract is stopped. */ modifier whenStopped() { require(stopped); _; } /** * @dev called by the owner to pause, triggers stopped state */ function stop() onlyOwner whenNotStopped { stopped = true; Stop(); } }
* @title Stoppable @dev Base contract which allows children to implement final irreversible stop mechanism./
contract Stoppable is Pausable { event Stop(); bool public stopped = false; modifier whenNotStopped() { require(!stopped); _; } modifier whenStopped() { require(stopped); _; } function stop() onlyOwner whenNotStopped { stopped = true; Stop(); } }
13,068,642
[ 1, 4947, 19586, 225, 3360, 6835, 1492, 5360, 2325, 358, 2348, 727, 9482, 266, 2496, 1523, 2132, 12860, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 5131, 19586, 353, 21800, 16665, 288, 203, 225, 871, 5131, 5621, 203, 203, 225, 1426, 1071, 9627, 273, 629, 31, 203, 203, 203, 225, 9606, 1347, 1248, 15294, 1435, 288, 203, 565, 2583, 12, 5, 24228, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 9606, 1347, 15294, 1435, 288, 203, 565, 2583, 12, 24228, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 2132, 1435, 1338, 5541, 1347, 1248, 15294, 288, 203, 565, 9627, 273, 638, 31, 203, 565, 5131, 5621, 203, 225, 289, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9467b523c9eeea7853BE0c7f0f1e3E8d4ac698AB/sources/contracts/simple/ISimpleVaultInternal.sol
* @notice thrown when attempting to act without being whitelisted/
error SimpleVault__NotWhitelisted();
4,984,083
[ 1, 12849, 82, 1347, 15600, 358, 1328, 2887, 3832, 26944, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 555, 4477, 12003, 972, 1248, 18927, 329, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * [EIP](https://eips.ethereum.org/EIPS/eip-165). * * 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 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @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 `setApproveForAll`. */ 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 `setApproveForAll`. */ 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; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. 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); } // File: openzeppelin-solidity/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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/drafts/Counters.sol pragma solidity ^0.5.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;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @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; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "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 != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, 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 `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 `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) public { 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 mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol pragma solidity ^0.5.0; /** * @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); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol pragma solidity ^0.5.0; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/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 PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/eth_superplayer_randomequip.sol pragma solidity ^0.5.0; contract SuperplayerRandomEquipment is Ownable{ using SafeMath for uint256; //enum EquipmentPart {Weapon ,Head,Coat,Pants ,Shoes } //enum EquipmentRareness {White,Green,Blue,Purple, Orange,Red } // Equipment in pool struct Equipment { string key; uint weight; // EquipmentPart part; // EquipmentRareness rareness; uint[] randomKeyIds; } Equipment[] private equips; uint256 TotalEquipNum; // for ERC721 uint256 TotalWeight; // for ERC721 //keyid -> value->weight struct ValueByWeight { uint value; uint weight; } mapping(uint => ValueByWeight[] ) randomvalueTable ; mapping(uint => uint ) randomvalueTableWeights ; constructor() public{ //initRtables(); //initEquipmentPools(); } function getRandomEquipment(uint256 seed) public view returns(uint blockNo,string memory ekey,uint[] memory randomProps) { uint random = getRandom(seed); uint equipIndex = getRandomEquipIndexByWeight( random % TotalWeight + 1) ; //ensure equipment index Equipment memory equip = equips[equipIndex]; //ensure random values randomProps = new uint[](equip.randomKeyIds.length); for(uint i=0;i< randomProps.length ; i++) { uint keyid = equip.randomKeyIds[i] ; uint rv = _randomValue(keyid, (random >>i )% randomvalueTableWeights[keyid] +1 ); randomProps[i] = rv; } blockNo = block.number; ekey = equip.key; } // config function initRtables1() public onlyOwner{ _initRtables1(); } function initRtables2() public onlyOwner{ _initRtables2(); } function initEquipmentPools() public onlyOwner{ _initEquipmentPools(); } function addEquipToPool(string memory key,uint[] memory randomKeyIds,uint weight) public onlyOwner{ _addEquipToPool(key,randomKeyIds,weight); } function addRandomValuesforRTable(uint keyid, uint[] memory values,uint[] memory weights) public onlyOwner { _addRandomValuesforRTable(keyid,values,weights); } //config end function getEquipmentConf(uint equipIndex) public view returns( string memory key,uint weight,uint[] memory randomKeyIds){ Equipment memory equip = equips[equipIndex]; key = equip.key; weight = equip.weight; randomKeyIds = equip.randomKeyIds; } function getRandomValueConf(uint keyid) public view returns( uint[]memory values,uint[] memory weights){ ValueByWeight[] memory vs =randomvalueTable[keyid]; values = new uint[](vs.length); weights = new uint[](vs.length); for(uint i = 0 ;i < vs.length;++i) { values[i]=vs[i].value; weights[i]=vs[i].weight; } } function getRandomEquipIndexByWeight( uint weight ) internal view returns (uint) { require( weight <= TotalWeight ); uint sum ; for (uint i = 0;i < TotalEquipNum ; i++){ sum += equips[i].weight; if( weight <= sum ){ return i; } } return TotalEquipNum -1 ; } function _addEquipToPool(string memory key,uint[] memory randomKeyIds,uint weight) internal { Equipment memory newEquip = Equipment({ key : key, randomKeyIds : randomKeyIds, weight : weight }); equips.push(newEquip); TotalEquipNum = TotalEquipNum.add(1); TotalWeight += weight; } function _addRandomValuesforRTable(uint keyid, uint[] memory values,uint[] memory weights) internal { require(randomvalueTableWeights[keyid] == 0 ); for( uint i = 0; i < values.length;++i) { ValueByWeight memory vw = ValueByWeight({ value : values[i], weight: weights[i] }); randomvalueTable[keyid].push(vw); randomvalueTableWeights[keyid] += weights[i]; } } //concat user seed later function getRandom(uint256 seed) internal view returns (uint256){ return uint256(keccak256(abi.encodePacked(block.timestamp, seed,block.difficulty))); } function _randomValue (uint keyid,uint weight ) internal view returns(uint randomValue){ ValueByWeight[] memory vs =randomvalueTable[keyid]; uint sum ; for (uint i = 0;i < vs.length ; i++){ ValueByWeight memory vw = vs[i]; sum += vw.weight; if( weight <= sum ){ return vw.value; } } return vs[vs.length -1].value ; } function _initEquipmentPools () internal { uint[] memory pblue_weapongun_gun_sniper_laser = new uint[](4); pblue_weapongun_gun_sniper_laser[0] = 134; pblue_weapongun_gun_sniper_laser[1] = 134; pblue_weapongun_gun_sniper_laser[2] = 134; pblue_weapongun_gun_sniper_laser[3] = 134; _addEquipToPool("blue_weapongun_gun_sniper_laser",pblue_weapongun_gun_sniper_laser,1); uint[] memory pblue_weapongun_gun_black_hand = new uint[](4); pblue_weapongun_gun_black_hand[0] = 135; pblue_weapongun_gun_black_hand[1] = 135; pblue_weapongun_gun_black_hand[2] = 135; pblue_weapongun_gun_black_hand[3] = 135; _addEquipToPool("blue_weapongun_gun_black_hand",pblue_weapongun_gun_black_hand,1); uint[] memory pblue_weapon_gun_gray_auto = new uint[](4); pblue_weapon_gun_gray_auto[0] = 132; pblue_weapon_gun_gray_auto[1] = 132; pblue_weapon_gun_gray_auto[2] = 132; pblue_weapon_gun_gray_auto[3] = 132; _addEquipToPool("blue_weapon_gun_gray_auto",pblue_weapon_gun_gray_auto,1); uint[] memory pblue_weapon_gun_gray_sniper = new uint[](4); pblue_weapon_gun_gray_sniper[0] = 133; pblue_weapon_gun_gray_sniper[1] = 133; pblue_weapon_gun_gray_sniper[2] = 133; pblue_weapon_gun_gray_sniper[3] = 133; _addEquipToPool("blue_weapon_gun_gray_sniper",pblue_weapon_gun_gray_sniper,1); uint[] memory pblue_weapon_gun_gray_shotgun = new uint[](4); pblue_weapon_gun_gray_shotgun[0] = 131; pblue_weapon_gun_gray_shotgun[1] = 131; pblue_weapon_gun_gray_shotgun[2] = 131; pblue_weapon_gun_gray_shotgun[3] = 131; _addEquipToPool("blue_weapon_gun_gray_shotgun",pblue_weapon_gun_gray_shotgun,1); uint[] memory pblue_helmet_damage = new uint[](5); pblue_helmet_damage[0] = 232; pblue_helmet_damage[1] = 232; pblue_helmet_damage[2] = 232; pblue_helmet_damage[3] = 232; pblue_helmet_damage[4] = 232; _addEquipToPool("blue_helmet_damage",pblue_helmet_damage,2); uint[] memory pblue_body_damage = new uint[](5); pblue_body_damage[0] = 232; pblue_body_damage[1] = 232; pblue_body_damage[2] = 232; pblue_body_damage[3] = 232; pblue_body_damage[4] = 232; _addEquipToPool("blue_body_damage",pblue_body_damage,2); uint[] memory pblue_leg_damage = new uint[](5); pblue_leg_damage[0] = 232; pblue_leg_damage[1] = 232; pblue_leg_damage[2] = 232; pblue_leg_damage[3] = 232; pblue_leg_damage[4] = 232; _addEquipToPool("blue_leg_damage",pblue_leg_damage,2); uint[] memory pblue_shoes_damage = new uint[](5); pblue_shoes_damage[0] = 232; pblue_shoes_damage[1] = 232; pblue_shoes_damage[2] = 232; pblue_shoes_damage[3] = 232; pblue_shoes_damage[4] = 232; _addEquipToPool("blue_shoes_damage",pblue_shoes_damage,2); uint[] memory pblue_helmet_hp = new uint[](5); pblue_helmet_hp[0] = 231; pblue_helmet_hp[1] = 231; pblue_helmet_hp[2] = 231; pblue_helmet_hp[3] = 231; pblue_helmet_hp[4] = 231; _addEquipToPool("blue_helmet_hp",pblue_helmet_hp,2); uint[] memory pblue_body_hp = new uint[](5); pblue_body_hp[0] = 231; pblue_body_hp[1] = 231; pblue_body_hp[2] = 231; pblue_body_hp[3] = 231; pblue_body_hp[4] = 231; _addEquipToPool("blue_body_hp",pblue_body_hp,2); uint[] memory pblue_leg_hp = new uint[](5); pblue_leg_hp[0] = 231; pblue_leg_hp[1] = 231; pblue_leg_hp[2] = 231; pblue_leg_hp[3] = 231; pblue_leg_hp[4] = 231; _addEquipToPool("blue_leg_hp",pblue_leg_hp,2); uint[] memory pblue_shoes_hp = new uint[](5); pblue_shoes_hp[0] = 231; pblue_shoes_hp[1] = 231; pblue_shoes_hp[2] = 231; pblue_shoes_hp[3] = 231; pblue_shoes_hp[4] = 231; _addEquipToPool("blue_shoes_hp",pblue_shoes_hp,0); } function _initRtables1 () internal { uint[] memory v121 = new uint[](6); uint[] memory w121 = new uint[](6); v121[0]= 1001; w121[0]=14; v121[1]= 1002; w121[1]=40; v121[2]= 1003; w121[2]=10; v121[3]= 1008; w121[3]=12; v121[4]= 1009; w121[4]=12; v121[5]= 1010; w121[5]=12; _addRandomValuesforRTable(121,v121,w121); uint[] memory v123 = new uint[](7); uint[] memory w123 = new uint[](7); v123[0]= 1001; w123[0]=30; v123[1]= 1005; w123[1]=10; v123[2]= 1006; w123[2]=10; v123[3]= 1008; w123[3]=13; v123[4]= 1009; w123[4]=12; v123[5]= 1010; w123[5]=13; v123[6]= 1007; w123[6]=12; _addRandomValuesforRTable(123,v123,w123); uint[] memory v125 = new uint[](7); uint[] memory w125 = new uint[](7); v125[0]= 1001; w125[0]=30; v125[1]= 1005; w125[1]=10; v125[2]= 1006; w125[2]=10; v125[3]= 1008; w125[3]=20; v125[4]= 1009; w125[4]=10; v125[5]= 1010; w125[5]=10; v125[6]= 1007; w125[6]=10; _addRandomValuesforRTable(125,v125,w125); uint[] memory v135 = new uint[](7); uint[] memory w135 = new uint[](7); v135[0]= 1001; w135[0]=20; v135[1]= 1005; w135[1]=8; v135[2]= 1006; w135[2]=8; v135[3]= 1008; w135[3]=8; v135[4]= 1009; w135[4]=40; v135[5]= 1010; w135[5]=8; v135[6]= 1007; w135[6]=8; _addRandomValuesforRTable(135,v135,w135); uint[] memory v232 = new uint[](8); uint[] memory w232 = new uint[](8); v232[0]= 2002; w232[0]=15; v232[1]= 2003; w232[1]=8; v232[2]= 2004; w232[2]=7; v232[3]= 2001; w232[3]=34; v232[4]= 2008; w232[4]=9; v232[5]= 2007; w232[5]=9; v232[6]= 2009; w232[6]=9; v232[7]= 2005; w232[7]=9; _addRandomValuesforRTable(232,v232,w232); uint[] memory v112 = new uint[](7); uint[] memory w112 = new uint[](7); v112[0]= 1001; w112[0]=40; v112[1]= 1005; w112[1]=10; v112[2]= 1006; w112[2]=10; v112[3]= 1008; w112[3]=10; v112[4]= 1009; w112[4]=10; v112[5]= 1010; w112[5]=10; v112[6]= 1007; w112[6]=10; _addRandomValuesforRTable(112,v112,w112); uint[] memory v124 = new uint[](7); uint[] memory w124 = new uint[](7); v124[0]= 1001; w124[0]=30; v124[1]= 1005; w124[1]=10; v124[2]= 1006; w124[2]=10; v124[3]= 1008; w124[3]=10; v124[4]= 1009; w124[4]=10; v124[5]= 1010; w124[5]=20; v124[6]= 1007; w124[6]=10; _addRandomValuesforRTable(124,v124,w124); uint[] memory v134 = new uint[](7); uint[] memory w134 = new uint[](7); v134[0]= 1001; w134[0]=20; v134[1]= 1005; w134[1]=8; v134[2]= 1006; w134[2]=8; v134[3]= 1008; w134[3]=8; v134[4]= 1009; w134[4]=8; v134[5]= 1010; w134[5]=40; v134[6]= 1007; w134[6]=8; _addRandomValuesforRTable(134,v134,w134); uint[] memory v211 = new uint[](6); uint[] memory w211 = new uint[](6); v211[0]= 2002; w211[0]=30; v211[1]= 2003; w211[1]=10; v211[2]= 2004; w211[2]=10; v211[3]= 2001; w211[3]=30; v211[4]= 2008; w211[4]=10; v211[5]= 2007; w211[5]=10; _addRandomValuesforRTable(211,v211,w211); uint[] memory v221 = new uint[](6); uint[] memory w221 = new uint[](6); v221[0]= 2002; w221[0]=35; v221[1]= 2003; w221[1]=12; v221[2]= 2004; w221[2]=13; v221[3]= 2001; w221[3]=20; v221[4]= 2008; w221[4]=10; v221[5]= 2007; w221[5]=10; _addRandomValuesforRTable(221,v221,w221); uint[] memory v212 = new uint[](8); uint[] memory w212 = new uint[](8); v212[0]= 2002; w212[0]=30; v212[1]= 2003; w212[1]=10; v212[2]= 2004; w212[2]=10; v212[3]= 2001; w212[3]=30; v212[4]= 2008; w212[4]=5; v212[5]= 2007; w212[5]=5; v212[6]= 2009; w212[6]=5; v212[7]= 2005; w212[7]=5; _addRandomValuesforRTable(212,v212,w212); } function _initRtables2 () internal { uint[] memory v111 = new uint[](6); uint[] memory w111 = new uint[](6); v111[0]= 1001; w111[0]=14; v111[1]= 1002; w111[1]=40; v111[2]= 1003; w111[2]=10; v111[3]= 1008; w111[3]=12; v111[4]= 1009; w111[4]=12; v111[5]= 1010; w111[5]=12; _addRandomValuesforRTable(111,v111,w111); uint[] memory v113 = new uint[](7); uint[] memory w113 = new uint[](7); v113[0]= 1001; w113[0]=30; v113[1]= 1005; w113[1]=10; v113[2]= 1006; w113[2]=10; v113[3]= 1008; w113[3]=13; v113[4]= 1009; w113[4]=12; v113[5]= 1010; w113[5]=13; v113[6]= 1007; w113[6]=12; _addRandomValuesforRTable(113,v113,w113); uint[] memory v114 = new uint[](7); uint[] memory w114 = new uint[](7); v114[0]= 1001; w114[0]=30; v114[1]= 1005; w114[1]=10; v114[2]= 1006; w114[2]=10; v114[3]= 1008; w114[3]=10; v114[4]= 1009; w114[4]=10; v114[5]= 1010; w114[5]=20; v114[6]= 1007; w114[6]=10; _addRandomValuesforRTable(114,v114,w114); uint[] memory v133 = new uint[](7); uint[] memory w133 = new uint[](7); v133[0]= 1001; w133[0]=8; v133[1]= 1005; w133[1]=40; v133[2]= 1006; w133[2]=20; v133[3]= 1008; w133[3]=8; v133[4]= 1009; w133[4]=8; v133[5]= 1010; w133[5]=8; v133[6]= 1007; w133[6]=8; _addRandomValuesforRTable(133,v133,w133); uint[] memory v115 = new uint[](7); uint[] memory w115 = new uint[](7); v115[0]= 1001; w115[0]=30; v115[1]= 1005; w115[1]=10; v115[2]= 1006; w115[2]=10; v115[3]= 1008; w115[3]=20; v115[4]= 1009; w115[4]=10; v115[5]= 1010; w115[5]=10; v115[6]= 1007; w115[6]=10; _addRandomValuesforRTable(115,v115,w115); uint[] memory v122 = new uint[](7); uint[] memory w122 = new uint[](7); v122[0]= 1001; w122[0]=40; v122[1]= 1005; w122[1]=10; v122[2]= 1006; w122[2]=10; v122[3]= 1008; w122[3]=10; v122[4]= 1009; w122[4]=10; v122[5]= 1010; w122[5]=10; v122[6]= 1007; w122[6]=1; _addRandomValuesforRTable(122,v122,w122); uint[] memory v131 = new uint[](6); uint[] memory w131 = new uint[](6); v131[0]= 1001; w131[0]=10; v131[1]= 1002; w131[1]=40; v131[2]= 1002; w131[2]=20; v131[3]= 1008; w131[3]=10; v131[4]= 1009; w131[4]=10; v131[5]= 1010; w131[5]=10; _addRandomValuesforRTable(131,v131,w131); uint[] memory v132 = new uint[](7); uint[] memory w132 = new uint[](7); v132[0]= 1001; w132[0]=50; v132[1]= 1005; w132[1]=9; v132[2]= 1006; w132[2]=9; v132[3]= 1008; w132[3]=8; v132[4]= 1009; w132[4]=8; v132[5]= 1010; w132[5]=8; v132[6]= 1007; w132[6]=8; _addRandomValuesforRTable(132,v132,w132); uint[] memory v231 = new uint[](6); uint[] memory w231 = new uint[](6); v231[0]= 2002; w231[0]=40; v231[1]= 2003; w231[1]=15; v231[2]= 2004; w231[2]=15; v231[3]= 2001; w231[3]=15; v231[4]= 2008; w231[4]=7; v231[5]= 2007; w231[5]=8; _addRandomValuesforRTable(231,v231,w231); uint[] memory v222 = new uint[](8); uint[] memory w222 = new uint[](8); v222[0]= 2002; w222[0]=20; v222[1]= 2003; w222[1]=10; v222[2]= 2004; w222[2]=10; v222[3]= 2001; w222[3]=32; v222[4]= 2008; w222[4]=7; v222[5]= 2007; w222[5]=7; v222[6]= 2009; w222[6]=7; v222[7]= 2005; w222[7]=7; _addRandomValuesforRTable(222,v222,w222); } }
enum EquipmentPart {Weapon ,Head,Coat,Pants ,Shoes }enum EquipmentRareness {White,Green,Blue,Purple, Orange,Red } Equipment in pool
contract SuperplayerRandomEquipment is Ownable{ using SafeMath for uint256; struct Equipment { string key; uint weight; uint[] randomKeyIds; } Equipment[] private equips; struct ValueByWeight { uint value; uint weight; } mapping(uint => ValueByWeight[] ) randomvalueTable ; mapping(uint => uint ) randomvalueTableWeights ; constructor() public{ } function getRandomEquipment(uint256 seed) public view returns(uint blockNo,string memory ekey,uint[] memory randomProps) { uint random = getRandom(seed); uint equipIndex = getRandomEquipIndexByWeight( random % TotalWeight + 1) ; Equipment memory equip = equips[equipIndex]; randomProps = new uint[](equip.randomKeyIds.length); for(uint i=0;i< randomProps.length ; i++) { uint keyid = equip.randomKeyIds[i] ; uint rv = _randomValue(keyid, (random >>i )% randomvalueTableWeights[keyid] +1 ); randomProps[i] = rv; } blockNo = block.number; ekey = equip.key; } function getRandomEquipment(uint256 seed) public view returns(uint blockNo,string memory ekey,uint[] memory randomProps) { uint random = getRandom(seed); uint equipIndex = getRandomEquipIndexByWeight( random % TotalWeight + 1) ; Equipment memory equip = equips[equipIndex]; randomProps = new uint[](equip.randomKeyIds.length); for(uint i=0;i< randomProps.length ; i++) { uint keyid = equip.randomKeyIds[i] ; uint rv = _randomValue(keyid, (random >>i )% randomvalueTableWeights[keyid] +1 ); randomProps[i] = rv; } blockNo = block.number; ekey = equip.key; } function initRtables1() public onlyOwner{ _initRtables1(); } function initRtables2() public onlyOwner{ _initRtables2(); } function initEquipmentPools() public onlyOwner{ _initEquipmentPools(); } function addEquipToPool(string memory key,uint[] memory randomKeyIds,uint weight) public onlyOwner{ _addEquipToPool(key,randomKeyIds,weight); } function addRandomValuesforRTable(uint keyid, uint[] memory values,uint[] memory weights) public onlyOwner { _addRandomValuesforRTable(keyid,values,weights); } function getEquipmentConf(uint equipIndex) public view returns( string memory key,uint weight,uint[] memory randomKeyIds){ Equipment memory equip = equips[equipIndex]; key = equip.key; weight = equip.weight; randomKeyIds = equip.randomKeyIds; } function getRandomValueConf(uint keyid) public view returns( uint[]memory values,uint[] memory weights){ ValueByWeight[] memory vs =randomvalueTable[keyid]; values = new uint[](vs.length); weights = new uint[](vs.length); for(uint i = 0 ;i < vs.length;++i) { values[i]=vs[i].value; weights[i]=vs[i].weight; } } function getRandomValueConf(uint keyid) public view returns( uint[]memory values,uint[] memory weights){ ValueByWeight[] memory vs =randomvalueTable[keyid]; values = new uint[](vs.length); weights = new uint[](vs.length); for(uint i = 0 ;i < vs.length;++i) { values[i]=vs[i].value; weights[i]=vs[i].weight; } } function getRandomEquipIndexByWeight( uint weight ) internal view returns (uint) { require( weight <= TotalWeight ); uint sum ; for (uint i = 0;i < TotalEquipNum ; i++){ sum += equips[i].weight; if( weight <= sum ){ return i; } } return TotalEquipNum -1 ; } function getRandomEquipIndexByWeight( uint weight ) internal view returns (uint) { require( weight <= TotalWeight ); uint sum ; for (uint i = 0;i < TotalEquipNum ; i++){ sum += equips[i].weight; if( weight <= sum ){ return i; } } return TotalEquipNum -1 ; } function getRandomEquipIndexByWeight( uint weight ) internal view returns (uint) { require( weight <= TotalWeight ); uint sum ; for (uint i = 0;i < TotalEquipNum ; i++){ sum += equips[i].weight; if( weight <= sum ){ return i; } } return TotalEquipNum -1 ; } function _addEquipToPool(string memory key,uint[] memory randomKeyIds,uint weight) internal { Equipment memory newEquip = Equipment({ key : key, randomKeyIds : randomKeyIds, weight : weight }); equips.push(newEquip); TotalEquipNum = TotalEquipNum.add(1); TotalWeight += weight; } function _addEquipToPool(string memory key,uint[] memory randomKeyIds,uint weight) internal { Equipment memory newEquip = Equipment({ key : key, randomKeyIds : randomKeyIds, weight : weight }); equips.push(newEquip); TotalEquipNum = TotalEquipNum.add(1); TotalWeight += weight; } function _addRandomValuesforRTable(uint keyid, uint[] memory values,uint[] memory weights) internal { require(randomvalueTableWeights[keyid] == 0 ); for( uint i = 0; i < values.length;++i) { ValueByWeight memory vw = ValueByWeight({ value : values[i], weight: weights[i] }); randomvalueTable[keyid].push(vw); randomvalueTableWeights[keyid] += weights[i]; } } function _addRandomValuesforRTable(uint keyid, uint[] memory values,uint[] memory weights) internal { require(randomvalueTableWeights[keyid] == 0 ); for( uint i = 0; i < values.length;++i) { ValueByWeight memory vw = ValueByWeight({ value : values[i], weight: weights[i] }); randomvalueTable[keyid].push(vw); randomvalueTableWeights[keyid] += weights[i]; } } function _addRandomValuesforRTable(uint keyid, uint[] memory values,uint[] memory weights) internal { require(randomvalueTableWeights[keyid] == 0 ); for( uint i = 0; i < values.length;++i) { ValueByWeight memory vw = ValueByWeight({ value : values[i], weight: weights[i] }); randomvalueTable[keyid].push(vw); randomvalueTableWeights[keyid] += weights[i]; } } function getRandom(uint256 seed) internal view returns (uint256){ return uint256(keccak256(abi.encodePacked(block.timestamp, seed,block.difficulty))); } function _randomValue (uint keyid,uint weight ) internal view returns(uint randomValue){ ValueByWeight[] memory vs =randomvalueTable[keyid]; uint sum ; for (uint i = 0;i < vs.length ; i++){ ValueByWeight memory vw = vs[i]; sum += vw.weight; if( weight <= sum ){ return vw.value; } } return vs[vs.length -1].value ; } function _randomValue (uint keyid,uint weight ) internal view returns(uint randomValue){ ValueByWeight[] memory vs =randomvalueTable[keyid]; uint sum ; for (uint i = 0;i < vs.length ; i++){ ValueByWeight memory vw = vs[i]; sum += vw.weight; if( weight <= sum ){ return vw.value; } } return vs[vs.length -1].value ; } function _randomValue (uint keyid,uint weight ) internal view returns(uint randomValue){ ValueByWeight[] memory vs =randomvalueTable[keyid]; uint sum ; for (uint i = 0;i < vs.length ; i++){ ValueByWeight memory vw = vs[i]; sum += vw.weight; if( weight <= sum ){ return vw.value; } } return vs[vs.length -1].value ; } function _initEquipmentPools () internal { uint[] memory pblue_weapongun_gun_sniper_laser = new uint[](4); pblue_weapongun_gun_sniper_laser[0] = 134; pblue_weapongun_gun_sniper_laser[1] = 134; pblue_weapongun_gun_sniper_laser[2] = 134; pblue_weapongun_gun_sniper_laser[3] = 134; _addEquipToPool("blue_weapongun_gun_sniper_laser",pblue_weapongun_gun_sniper_laser,1); uint[] memory pblue_weapongun_gun_black_hand = new uint[](4); pblue_weapongun_gun_black_hand[0] = 135; pblue_weapongun_gun_black_hand[1] = 135; pblue_weapongun_gun_black_hand[2] = 135; pblue_weapongun_gun_black_hand[3] = 135; _addEquipToPool("blue_weapongun_gun_black_hand",pblue_weapongun_gun_black_hand,1); uint[] memory pblue_weapon_gun_gray_auto = new uint[](4); pblue_weapon_gun_gray_auto[0] = 132; pblue_weapon_gun_gray_auto[1] = 132; pblue_weapon_gun_gray_auto[2] = 132; pblue_weapon_gun_gray_auto[3] = 132; _addEquipToPool("blue_weapon_gun_gray_auto",pblue_weapon_gun_gray_auto,1); uint[] memory pblue_weapon_gun_gray_sniper = new uint[](4); pblue_weapon_gun_gray_sniper[0] = 133; pblue_weapon_gun_gray_sniper[1] = 133; pblue_weapon_gun_gray_sniper[2] = 133; pblue_weapon_gun_gray_sniper[3] = 133; _addEquipToPool("blue_weapon_gun_gray_sniper",pblue_weapon_gun_gray_sniper,1); uint[] memory pblue_weapon_gun_gray_shotgun = new uint[](4); pblue_weapon_gun_gray_shotgun[0] = 131; pblue_weapon_gun_gray_shotgun[1] = 131; pblue_weapon_gun_gray_shotgun[2] = 131; pblue_weapon_gun_gray_shotgun[3] = 131; _addEquipToPool("blue_weapon_gun_gray_shotgun",pblue_weapon_gun_gray_shotgun,1); uint[] memory pblue_helmet_damage = new uint[](5); pblue_helmet_damage[0] = 232; pblue_helmet_damage[1] = 232; pblue_helmet_damage[2] = 232; pblue_helmet_damage[3] = 232; pblue_helmet_damage[4] = 232; _addEquipToPool("blue_helmet_damage",pblue_helmet_damage,2); uint[] memory pblue_body_damage = new uint[](5); pblue_body_damage[0] = 232; pblue_body_damage[1] = 232; pblue_body_damage[2] = 232; pblue_body_damage[3] = 232; pblue_body_damage[4] = 232; _addEquipToPool("blue_body_damage",pblue_body_damage,2); uint[] memory pblue_leg_damage = new uint[](5); pblue_leg_damage[0] = 232; pblue_leg_damage[1] = 232; pblue_leg_damage[2] = 232; pblue_leg_damage[3] = 232; pblue_leg_damage[4] = 232; _addEquipToPool("blue_leg_damage",pblue_leg_damage,2); uint[] memory pblue_shoes_damage = new uint[](5); pblue_shoes_damage[0] = 232; pblue_shoes_damage[1] = 232; pblue_shoes_damage[2] = 232; pblue_shoes_damage[3] = 232; pblue_shoes_damage[4] = 232; _addEquipToPool("blue_shoes_damage",pblue_shoes_damage,2); uint[] memory pblue_helmet_hp = new uint[](5); pblue_helmet_hp[0] = 231; pblue_helmet_hp[1] = 231; pblue_helmet_hp[2] = 231; pblue_helmet_hp[3] = 231; pblue_helmet_hp[4] = 231; _addEquipToPool("blue_helmet_hp",pblue_helmet_hp,2); uint[] memory pblue_body_hp = new uint[](5); pblue_body_hp[0] = 231; pblue_body_hp[1] = 231; pblue_body_hp[2] = 231; pblue_body_hp[3] = 231; pblue_body_hp[4] = 231; _addEquipToPool("blue_body_hp",pblue_body_hp,2); uint[] memory pblue_leg_hp = new uint[](5); pblue_leg_hp[0] = 231; pblue_leg_hp[1] = 231; pblue_leg_hp[2] = 231; pblue_leg_hp[3] = 231; pblue_leg_hp[4] = 231; _addEquipToPool("blue_leg_hp",pblue_leg_hp,2); uint[] memory pblue_shoes_hp = new uint[](5); pblue_shoes_hp[0] = 231; pblue_shoes_hp[1] = 231; pblue_shoes_hp[2] = 231; pblue_shoes_hp[3] = 231; pblue_shoes_hp[4] = 231; _addEquipToPool("blue_shoes_hp",pblue_shoes_hp,0); } function _initRtables1 () internal { uint[] memory v121 = new uint[](6); uint[] memory w121 = new uint[](6); v121[0]= 1001; w121[0]=14; v121[1]= 1002; w121[1]=40; v121[2]= 1003; w121[2]=10; v121[3]= 1008; w121[3]=12; v121[4]= 1009; w121[4]=12; v121[5]= 1010; w121[5]=12; _addRandomValuesforRTable(121,v121,w121); uint[] memory v123 = new uint[](7); uint[] memory w123 = new uint[](7); v123[0]= 1001; w123[0]=30; v123[1]= 1005; w123[1]=10; v123[2]= 1006; w123[2]=10; v123[3]= 1008; w123[3]=13; v123[4]= 1009; w123[4]=12; v123[5]= 1010; w123[5]=13; v123[6]= 1007; w123[6]=12; _addRandomValuesforRTable(123,v123,w123); uint[] memory v125 = new uint[](7); uint[] memory w125 = new uint[](7); v125[0]= 1001; w125[0]=30; v125[1]= 1005; w125[1]=10; v125[2]= 1006; w125[2]=10; v125[3]= 1008; w125[3]=20; v125[4]= 1009; w125[4]=10; v125[5]= 1010; w125[5]=10; v125[6]= 1007; w125[6]=10; _addRandomValuesforRTable(125,v125,w125); uint[] memory v135 = new uint[](7); uint[] memory w135 = new uint[](7); v135[0]= 1001; w135[0]=20; v135[1]= 1005; w135[1]=8; v135[2]= 1006; w135[2]=8; v135[3]= 1008; w135[3]=8; v135[4]= 1009; w135[4]=40; v135[5]= 1010; w135[5]=8; v135[6]= 1007; w135[6]=8; _addRandomValuesforRTable(135,v135,w135); uint[] memory v232 = new uint[](8); uint[] memory w232 = new uint[](8); v232[0]= 2002; w232[0]=15; v232[1]= 2003; w232[1]=8; v232[2]= 2004; w232[2]=7; v232[3]= 2001; w232[3]=34; v232[4]= 2008; w232[4]=9; v232[5]= 2007; w232[5]=9; v232[6]= 2009; w232[6]=9; v232[7]= 2005; w232[7]=9; _addRandomValuesforRTable(232,v232,w232); uint[] memory v112 = new uint[](7); uint[] memory w112 = new uint[](7); v112[0]= 1001; w112[0]=40; v112[1]= 1005; w112[1]=10; v112[2]= 1006; w112[2]=10; v112[3]= 1008; w112[3]=10; v112[4]= 1009; w112[4]=10; v112[5]= 1010; w112[5]=10; v112[6]= 1007; w112[6]=10; _addRandomValuesforRTable(112,v112,w112); uint[] memory v124 = new uint[](7); uint[] memory w124 = new uint[](7); v124[0]= 1001; w124[0]=30; v124[1]= 1005; w124[1]=10; v124[2]= 1006; w124[2]=10; v124[3]= 1008; w124[3]=10; v124[4]= 1009; w124[4]=10; v124[5]= 1010; w124[5]=20; v124[6]= 1007; w124[6]=10; _addRandomValuesforRTable(124,v124,w124); uint[] memory v134 = new uint[](7); uint[] memory w134 = new uint[](7); v134[0]= 1001; w134[0]=20; v134[1]= 1005; w134[1]=8; v134[2]= 1006; w134[2]=8; v134[3]= 1008; w134[3]=8; v134[4]= 1009; w134[4]=8; v134[5]= 1010; w134[5]=40; v134[6]= 1007; w134[6]=8; _addRandomValuesforRTable(134,v134,w134); uint[] memory v211 = new uint[](6); uint[] memory w211 = new uint[](6); v211[0]= 2002; w211[0]=30; v211[1]= 2003; w211[1]=10; v211[2]= 2004; w211[2]=10; v211[3]= 2001; w211[3]=30; v211[4]= 2008; w211[4]=10; v211[5]= 2007; w211[5]=10; _addRandomValuesforRTable(211,v211,w211); uint[] memory v221 = new uint[](6); uint[] memory w221 = new uint[](6); v221[0]= 2002; w221[0]=35; v221[1]= 2003; w221[1]=12; v221[2]= 2004; w221[2]=13; v221[3]= 2001; w221[3]=20; v221[4]= 2008; w221[4]=10; v221[5]= 2007; w221[5]=10; _addRandomValuesforRTable(221,v221,w221); uint[] memory v212 = new uint[](8); uint[] memory w212 = new uint[](8); v212[0]= 2002; w212[0]=30; v212[1]= 2003; w212[1]=10; v212[2]= 2004; w212[2]=10; v212[3]= 2001; w212[3]=30; v212[4]= 2008; w212[4]=5; v212[5]= 2007; w212[5]=5; v212[6]= 2009; w212[6]=5; v212[7]= 2005; w212[7]=5; _addRandomValuesforRTable(212,v212,w212); } function _initRtables2 () internal { uint[] memory v111 = new uint[](6); uint[] memory w111 = new uint[](6); v111[0]= 1001; w111[0]=14; v111[1]= 1002; w111[1]=40; v111[2]= 1003; w111[2]=10; v111[3]= 1008; w111[3]=12; v111[4]= 1009; w111[4]=12; v111[5]= 1010; w111[5]=12; _addRandomValuesforRTable(111,v111,w111); uint[] memory v113 = new uint[](7); uint[] memory w113 = new uint[](7); v113[0]= 1001; w113[0]=30; v113[1]= 1005; w113[1]=10; v113[2]= 1006; w113[2]=10; v113[3]= 1008; w113[3]=13; v113[4]= 1009; w113[4]=12; v113[5]= 1010; w113[5]=13; v113[6]= 1007; w113[6]=12; _addRandomValuesforRTable(113,v113,w113); uint[] memory v114 = new uint[](7); uint[] memory w114 = new uint[](7); v114[0]= 1001; w114[0]=30; v114[1]= 1005; w114[1]=10; v114[2]= 1006; w114[2]=10; v114[3]= 1008; w114[3]=10; v114[4]= 1009; w114[4]=10; v114[5]= 1010; w114[5]=20; v114[6]= 1007; w114[6]=10; _addRandomValuesforRTable(114,v114,w114); uint[] memory v133 = new uint[](7); uint[] memory w133 = new uint[](7); v133[0]= 1001; w133[0]=8; v133[1]= 1005; w133[1]=40; v133[2]= 1006; w133[2]=20; v133[3]= 1008; w133[3]=8; v133[4]= 1009; w133[4]=8; v133[5]= 1010; w133[5]=8; v133[6]= 1007; w133[6]=8; _addRandomValuesforRTable(133,v133,w133); uint[] memory v115 = new uint[](7); uint[] memory w115 = new uint[](7); v115[0]= 1001; w115[0]=30; v115[1]= 1005; w115[1]=10; v115[2]= 1006; w115[2]=10; v115[3]= 1008; w115[3]=20; v115[4]= 1009; w115[4]=10; v115[5]= 1010; w115[5]=10; v115[6]= 1007; w115[6]=10; _addRandomValuesforRTable(115,v115,w115); uint[] memory v122 = new uint[](7); uint[] memory w122 = new uint[](7); v122[0]= 1001; w122[0]=40; v122[1]= 1005; w122[1]=10; v122[2]= 1006; w122[2]=10; v122[3]= 1008; w122[3]=10; v122[4]= 1009; w122[4]=10; v122[5]= 1010; w122[5]=10; v122[6]= 1007; w122[6]=1; _addRandomValuesforRTable(122,v122,w122); uint[] memory v131 = new uint[](6); uint[] memory w131 = new uint[](6); v131[0]= 1001; w131[0]=10; v131[1]= 1002; w131[1]=40; v131[2]= 1002; w131[2]=20; v131[3]= 1008; w131[3]=10; v131[4]= 1009; w131[4]=10; v131[5]= 1010; w131[5]=10; _addRandomValuesforRTable(131,v131,w131); uint[] memory v132 = new uint[](7); uint[] memory w132 = new uint[](7); v132[0]= 1001; w132[0]=50; v132[1]= 1005; w132[1]=9; v132[2]= 1006; w132[2]=9; v132[3]= 1008; w132[3]=8; v132[4]= 1009; w132[4]=8; v132[5]= 1010; w132[5]=8; v132[6]= 1007; w132[6]=8; _addRandomValuesforRTable(132,v132,w132); uint[] memory v231 = new uint[](6); uint[] memory w231 = new uint[](6); v231[0]= 2002; w231[0]=40; v231[1]= 2003; w231[1]=15; v231[2]= 2004; w231[2]=15; v231[3]= 2001; w231[3]=15; v231[4]= 2008; w231[4]=7; v231[5]= 2007; w231[5]=8; _addRandomValuesforRTable(231,v231,w231); uint[] memory v222 = new uint[](8); uint[] memory w222 = new uint[](8); v222[0]= 2002; w222[0]=20; v222[1]= 2003; w222[1]=10; v222[2]= 2004; w222[2]=10; v222[3]= 2001; w222[3]=32; v222[4]= 2008; w222[4]=7; v222[5]= 2007; w222[5]=7; v222[6]= 2009; w222[6]=7; v222[7]= 2005; w222[7]=7; _addRandomValuesforRTable(222,v222,w222); } }
13,027,938
[ 1, 7924, 19008, 11568, 1988, 288, 3218, 28629, 269, 1414, 16, 4249, 270, 16, 52, 4388, 269, 1555, 83, 281, 289, 7924, 19008, 11568, 54, 834, 4496, 288, 13407, 16, 21453, 16, 27986, 16, 10262, 1802, 16, 2965, 726, 16, 3715, 289, 19008, 11568, 316, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14845, 14872, 8529, 13142, 11568, 225, 353, 14223, 6914, 95, 203, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 203, 225, 1958, 19008, 11568, 288, 203, 565, 533, 498, 31, 203, 565, 2254, 3119, 31, 203, 565, 2254, 8526, 2744, 653, 2673, 31, 7010, 225, 289, 203, 203, 203, 225, 19008, 11568, 8526, 3238, 1298, 7146, 31, 203, 203, 203, 203, 225, 1958, 1445, 858, 6544, 288, 203, 565, 2254, 460, 31, 203, 565, 2254, 3119, 31, 203, 225, 289, 203, 203, 225, 2874, 12, 11890, 516, 1445, 858, 6544, 8526, 262, 2744, 1132, 1388, 225, 274, 203, 225, 2874, 12, 11890, 516, 2254, 262, 2744, 1132, 1388, 16595, 225, 274, 203, 203, 203, 203, 203, 225, 3885, 1435, 1071, 95, 203, 225, 289, 203, 203, 203, 203, 203, 225, 445, 20581, 13142, 11568, 12, 11890, 5034, 5009, 13, 1071, 1476, 1135, 12, 11890, 1203, 2279, 16, 1080, 3778, 425, 856, 16, 11890, 8526, 3778, 2744, 5047, 13, 225, 288, 203, 565, 2254, 2744, 273, 20581, 12, 12407, 1769, 203, 565, 2254, 1298, 625, 1016, 273, 20581, 13142, 625, 1016, 858, 6544, 12, 225, 2744, 738, 10710, 6544, 225, 397, 404, 13, 274, 203, 565, 19008, 11568, 3778, 225, 1298, 625, 273, 225, 1298, 7146, 63, 14298, 625, 1016, 15533, 203, 203, 565, 2744, 5047, 273, 394, 2254, 8526, 12, 14298, 625, 18, 9188, 653, 2673, 18, 2469, 1769, 203, 565, 364, 12, 11890, 277, 33, 20, 31, 77, 32, 2744, 5047, 18, 2469, 274, 277, 27245, 288, 203, 2 ]
./partial_match/97/0x9335528B040D279C887451f5bA9159d688068B25/sources/BEP20.sol
* @dev Implementation of the {IBEP20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of BEP20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IBEP20-approve}./
contract BEP20 is Ownable, IBEP20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; } constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 7; } _symbol = "hbc"; _decimals = 18; _name = "hsbc"; }
11,484,059
[ 1, 13621, 434, 326, 288, 45, 5948, 52, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 9722, 52, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 9484, 2537, 635, 13895, 358, 7864, 350, 2641, 18, 4673, 16164, 434, 326, 512, 2579, 2026, 486, 3626, 4259, 2641, 16, 487, 518, 5177, 1404, 1931, 635, 326, 7490, 18, 15768, 16, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 9722, 52, 3462, 353, 14223, 6914, 16, 467, 5948, 52, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 377, 203, 377, 203, 377, 203, 203, 282, 203, 97, 203, 203, 1377, 3885, 261, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 31734, 273, 2371, 31, 203, 565, 289, 203, 377, 203, 3639, 389, 7175, 273, 315, 76, 13459, 14432, 203, 3639, 389, 31734, 273, 6549, 31, 203, 3639, 389, 529, 273, 315, 4487, 13459, 14432, 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 ]
pragma solidity >=0.4.21 <0.7.0; import "./SafeMath.sol"; import "./IsOperational.sol"; contract FlightSuretyData is IsOperational { using SafeMath for uint256; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AIRLINE_REGISTERED(address airlineAddress); event AIRLINE_APPROVED(address airlineAddress, address approvingAirline, bool approved); event AIRLINE_FUNDED(address airlineAddress); event FLIGHT_ADDED(address airlineAddress, bytes32 flightKey, uint256 timestamp); event FLIGHT_STATUS_UPDATED(address airlineAddress, bytes32 flightKey, bool late); event PASSENGER_INSURANCE_PURCHASED(address passengerAddress, address airlineAddress, bytes32 flightKey, uint256 amount); event PASSENGER_INSURANCE_CLAIMED(address passengerAddress, address airlineAddress, bytes32 flightKey, uint256 amount); event PASSENGER_PAYOUT(address passengerAddress, uint256 amount); /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ constructor() IsOperational(msg.sender, "Data") public { } function creditInsurees() requireIsOperational requireContractOwner external { for (uint8 i = 0; i < allFlightKeys.length; i++) { Flight storage flight = flightInfo[allFlightKeys[i]]; if (flight.statusCode != 0) { for (uint8 j = 0; j< passengers.length; j++) { address passengerAddress = passengers[j]; if (flight.statusCode == 20 && passengerInsurances[passengerAddress][allFlightKeys[i]].amount > 0) { uint256 amount = SafeMath.div(SafeMath.mul(passengerInsurances[passengerAddress][allFlightKeys[i]].amount, 3), 2); require(amount > 0, "amount to be added should be positive"); passengerCredit[passengerAddress] = SafeMath.add(passengerCredit[passengerAddress], amount); passengerInsurances[passengerAddress][allFlightKeys[i]].insuranceStatus = 2; } else { passengerInsurances[passengerAddress][allFlightKeys[i]].insuranceStatus = 1; } } } } } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address passengerAddress) requireIsOperational requireContractOwner payable external { require(passengerCredit[passengerAddress] > 0, "There should be some money to payout."); uint256 amount = payout(passengerAddress); address(uint160(passengerAddress)).transfer(amount); emit PASSENGER_PAYOUT(passengerAddress, 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(uint256 amount) public payable requireIsOperational requireContractOwner { address(this).transfer(amount); } function getFlightKey(address airline, string memory flight, uint256 timestamp) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { } /********************************************************************************************/ /* Airline Operations */ /********************************************************************************************/ struct Flight { address airlineAddress; bytes32 flightIdentifier; uint8 statusCode; uint256 scheduledFlightTime; } struct Airline { address airlineAddress; // 1 = registered, 2 = approved, 3 = funded and Live uint8 airlineStatus; string airlineCode; uint256 requiredApprovalsCount; uint256 totalApprovals; } mapping(bytes32 => Flight) internal flightInfo; bytes32[] internal allFlightKeys; mapping(address => Airline) internal airlineInfo; address[] internal allAirlines; mapping(address => mapping(address => bool)) approvals; uint256 totalApprovedAirlines = 0; modifier isFunded(address airlineAddress) { require(airlineInfo[airlineAddress].airlineStatus == 3, "Airline must be funded"); _; } modifier isRegistered(address airlineAddress) { require(airlineInfo[airlineAddress].airlineStatus == 1, "Airline must be registered"); _; } modifier isApproved(address airlineAddress) { require(airlineInfo[airlineAddress].airlineStatus == 2, "Airline must be approved"); _; } modifier existingAirline(address airlineAddress) { require(airlineInfo[airlineAddress].airlineAddress != address(0), "Airline must exist"); _; } modifier nonExistingAirline(address airlineAddress) { require(airlineInfo[airlineAddress].airlineAddress == address(0), "Airline must not exist"); _; } modifier hasNotVotedAlready(address airlineAddress, address newAirlineAddress) { require(approvals[newAirlineAddress][airlineAddress] == false, "Can not vote for an airline twice"); _; } // register an airline function registerAirline(address airlineAddress, string calldata airlineCode) requireIsOperational requireContractOwner nonExistingAirline(airlineAddress) external { airlineInfo[airlineAddress] = Airline(airlineAddress, 1, airlineCode, 0, 0); allAirlines.push(airlineAddress); if (totalApprovedAirlines == 0) { airlineInfo[airlineAddress].airlineStatus = 2; emit AIRLINE_APPROVED(airlineAddress, airlineAddress, true); totalApprovedAirlines = 1; } else if(totalApprovedAirlines < 4) { airlineInfo[airlineAddress].requiredApprovalsCount = 1; } else if (totalApprovedAirlines >= 4) { airlineInfo[airlineAddress].requiredApprovalsCount = SafeMath.div(totalApprovedAirlines, 2); } emit AIRLINE_REGISTERED(airlineAddress); } // add a flight for the airline function addFlight(address airlineAddress, bytes32 flightIdentifier, uint256 timestamp) requireIsOperational requireContractOwner isFunded(airlineAddress) external { Flight memory flight = Flight(airlineAddress, flightIdentifier, 0 ,timestamp); flightInfo[flightIdentifier] = flight; allFlightKeys.push(flightIdentifier); emit FLIGHT_ADDED(airlineAddress, flightIdentifier, timestamp); } // update the flight status function updateFlightStatus(bytes32 flightIdentifier, uint256 timestamp, uint8 statusCode) requireIsOperational requireContractOwner external { require(isValidFlight(flightIdentifier, timestamp), "A flight should exist"); flightInfo[flightIdentifier].statusCode = statusCode; emit FLIGHT_STATUS_UPDATED(flightInfo[flightIdentifier].airlineAddress, flightIdentifier, statusCode == 20); } // check if the given flight is a valid flight function isValidFlight(bytes32 flightIdentifier, uint256 timestamp) public view returns(bool) { return flightInfo[flightIdentifier].scheduledFlightTime == timestamp; } // method to pay registration fee function payRegistrationFee(address airlineAddress) isApproved(airlineAddress) external { airlineInfo[airlineAddress].airlineStatus = 3; emit AIRLINE_FUNDED(airlineAddress); } function approveAirline(address airlineAddress, address newAirlineAddress) requireIsOperational requireContractOwner isFunded(airlineAddress) hasNotVotedAlready(airlineAddress, newAirlineAddress) external { airlineInfo[newAirlineAddress].totalApprovals = airlineInfo[newAirlineAddress].totalApprovals + 1; if (airlineInfo[newAirlineAddress].totalApprovals >= airlineInfo[newAirlineAddress].requiredApprovalsCount) { airlineInfo[newAirlineAddress].airlineStatus = 2; totalApprovedAirlines = SafeMath.add(totalApprovedAirlines, 1); } emit AIRLINE_APPROVED(airlineAddress, airlineAddress, airlineInfo[newAirlineAddress].airlineStatus == 2); } function getFlights() external view returns(bytes32[] memory) { return allFlightKeys; } function getFlightInfo(bytes32 flightIdentifier) external view returns(address, bytes32, uint8, uint256) { Flight storage flight = flightInfo[flightIdentifier]; return (flight.airlineAddress, flight.flightIdentifier, flight.statusCode, flight.scheduledFlightTime); } function getAllAirlines() external view returns(address[] memory) { return allAirlines; } function getAirlineInfo(address airlineAddress) external view returns(address, uint8, string memory, uint256, uint256) { Airline storage airline = airlineInfo[airlineAddress]; return (airline.airlineAddress, airline.airlineStatus, airline.airlineCode, airline.requiredApprovalsCount, airline.totalApprovals); } /********************************************************************************************/ /* PASSENGER Functions */ /********************************************************************************************/ struct Insurance { // flight number bytes32 flightIdentifier; // amount uint256 amount; // status (0 = purchased, 1 = expired, 2 = claimed) uint8 insuranceStatus; } // mapping (passengerAddress => insuranceId) mapping(address => mapping(bytes32 => Insurance)) private passengerInsurances; // mapping (passengerAddress => remainingFundsToCredit) mapping(address => uint256) private passengerCredit; // stores the passenger insuranceKeys mapping(address => bytes32[]) private passengerInsuranceKeys; mapping(address => bool) private passengerRegistered; address[] private passengers; /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier hasEnoughFunds(uint256 amount) { require(amount > 0 ether, "Insurance Policy needs some amount"); require(amount < 1 ether, "Total amount should be less than 1 ether"); _; } modifier hasInsurance(address passengerAddress, bytes32 flightIdentifier) { require(passengerInsurances[passengerAddress][flightIdentifier].amount > 0, "passenger should have the insurance"); _; } modifier duplicateInsurance(address passengerAddress, bytes32 flightIdentifier) { require(passengerInsurances[passengerAddress][flightIdentifier].amount == 0, "can not buy duplicate insurance"); _; } // passenger can buy insurance using this method function buyInsuranceInternal(address passengerAddress, bytes32 flightIdentifier, uint256 amount) external payable requireIsOperational requireContractOwner duplicateInsurance(passengerAddress, flightIdentifier) hasEnoughFunds(amount) { address(this).transfer(amount); if (passengerRegistered[passengerAddress] == false) { passengers.push(passengerAddress); } passengerInsurances[passengerAddress][flightIdentifier] = Insurance(flightIdentifier, uint256(amount), 0); passengerInsuranceKeys[passengerAddress].push(flightIdentifier); } // passenger can claim insurance for a flight function claimInsurance(address passengerAddress, bytes32 flightIdentifier) external requireIsOperational requireContractOwner hasInsurance(passengerAddress, flightIdentifier) { if (flightInfo[flightIdentifier].statusCode == 20) { uint256 amount = SafeMath.div(SafeMath.mul(passengerInsurances[passengerAddress][flightIdentifier].amount, 3), 2); passengerCredit[passengerAddress] = passengerCredit[passengerAddress] + amount; passengerInsurances[passengerAddress][flightIdentifier].insuranceStatus = 2; } } function payout(address passengerAddress) internal returns(uint256) { uint256 amount = passengerCredit[passengerAddress]; passengerCredit[passengerAddress] = 0; return amount; } function getPassengerInsurances(address passengerAddress) external view returns(bytes32[] memory) { return passengerInsuranceKeys[passengerAddress]; } function getPassengerInsurance(address passengerAddress, bytes32 flightIdentifier) external view returns(uint256, uint8) { Insurance storage insurance = passengerInsurances[passengerAddress][flightIdentifier]; return (insurance.amount, insurance.insuranceStatus); } function getPassengerCredit(address passengerAddress) external view returns(uint256) { return passengerCredit[passengerAddress]; } }
update the flight status
function updateFlightStatus(bytes32 flightIdentifier, uint256 timestamp, uint8 statusCode) requireIsOperational requireContractOwner external { require(isValidFlight(flightIdentifier, timestamp), "A flight should exist"); flightInfo[flightIdentifier].statusCode = statusCode; emit FLIGHT_STATUS_UPDATED(flightInfo[flightIdentifier].airlineAddress, flightIdentifier, statusCode == 20); }
12,982,268
[ 1, 2725, 326, 25187, 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, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 24243, 1482, 12, 3890, 1578, 25187, 3004, 16, 2254, 5034, 2858, 16, 2254, 28, 6593, 13, 203, 565, 2583, 2520, 2988, 287, 203, 565, 2583, 8924, 5541, 203, 565, 3903, 203, 565, 288, 203, 3639, 2583, 12, 26810, 24243, 12, 19131, 3004, 16, 2858, 3631, 315, 37, 25187, 1410, 1005, 8863, 203, 3639, 25187, 966, 63, 19131, 3004, 8009, 30120, 273, 6593, 31, 203, 3639, 3626, 478, 23516, 67, 8608, 67, 8217, 40, 12, 19131, 966, 63, 19131, 3004, 8009, 1826, 1369, 1887, 16, 25187, 3004, 16, 6593, 422, 4200, 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 ]
pragma solidity ^0.6.0; import "../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. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.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); } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface 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) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external 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) external; /** * @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) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } 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.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../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. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../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]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only // solhint-disable // Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } // SPDX-License-Identifier: MIT // Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface ICUSDCContract is IERC20withDec { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, address cTokenCollateral ) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external returns (uint256); /*** Admin Functions ***/ function _addReserves(uint256 addAmount) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract ICreditDesk { uint256 public totalWritedowns; uint256 public totalLoansOutstanding; function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual; function drawdown(address creditLineAddress, uint256 amount) external virtual; function pay(address creditLineAddress, uint256 amount) external virtual; function assessCreditLine(address creditLineAddress) external virtual; function applyPayment(address creditLineAddress, uint256 amount) external virtual; function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ICreditLine { function borrower() external view returns (address); function limit() external view returns (uint256); function interestApr() external view returns (uint256); function paymentPeriodInDays() external view returns (uint256); function termInDays() external view returns (uint256); function lateFeeApr() external view returns (uint256); // Accounting variables function balance() external view returns (uint256); function interestOwed() external view returns (uint256); function principalOwed() external view returns (uint256); function termEndTime() external view returns (uint256); function nextDueTime() external view returns (uint256); function interestAccruedAsOf() external view returns (uint256); function lastFullPaymentTime() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /* Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's. */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20withDec is IERC20 { /** * @dev Returns the number of decimals used for the token */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface IFidu is IERC20withDec { function mintTo(address to, uint256 amount) external; function burnFrom(address to, uint256 amount) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGo { /// @notice Returns the address of the UniqueIdentity contract. function uniqueIdentity() external view returns (address); function go(address account) external view returns (bool); function updateGoldfinchConfig() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchConfig { function getNumber(uint256 index) external returns (uint256); function getAddress(uint256 index) external returns (address); function setAddress(uint256 index, address newAddress) external returns (address); function setNumber(uint256 index, uint256 newNumber) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchFactory { function createCreditLine() external returns (address); function createBorrower(address owner) external returns (address); function createPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) external returns (address); function createMigratedPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) external returns (address); function updateGoldfinchConfig() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IPool { uint256 public sharePrice; function deposit(uint256 amount) external virtual; function withdraw(uint256 usdcAmount) external virtual; function withdrawInFidu(uint256 fiduAmount) external virtual; function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public virtual; function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool); function drawdown(address to, uint256 amount) public virtual returns (bool); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual; function assets() public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; interface IPoolTokens is IERC721 { event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); struct TokenInfo { address pool; uint256 tranche; uint256 principalAmount; uint256 principalRedeemed; uint256 interestRedeemed; } struct MintParams { uint256 principalAmount; uint256 tranche; } function mint(MintParams calldata params, address to) external returns (uint256); function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external; function burn(uint256 tokenId) external; function onPoolCreated(address newPool) external; function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory); function validPool(address sender) external view returns (bool); function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ITranchedPool.sol"; abstract contract ISeniorPool { uint256 public sharePrice; uint256 public totalLoansOutstanding; uint256 public totalWritedowns; function deposit(uint256 amount) external virtual returns (uint256 depositShares); function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 depositShares); function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount); function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function invest(ITranchedPool pool) public virtual; function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256); function investJunior(ITranchedPool pool, uint256 amount) public virtual; function redeem(uint256 tokenId) public virtual; function writedown(uint256 tokenId) public virtual; function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount); function assets() public view virtual returns (uint256); function getNumShares(uint256 amount) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ISeniorPool.sol"; import "./ITranchedPool.sol"; abstract contract ISeniorPoolStrategy { function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256); function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount); function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IV2CreditLine.sol"; abstract contract ITranchedPool { IV2CreditLine public creditLine; uint256 public createdAt; enum Tranches { Reserved, Senior, Junior } struct TrancheInfo { uint256 id; uint256 principalDeposited; uint256 principalSharePrice; uint256 interestSharePrice; uint256 lockedUntil; } function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public virtual; function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory); function pay(uint256 amount) external virtual; function lockJuniorCapital() external virtual; function lockPool() external virtual; function drawdown(uint256 amount) external virtual; function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId); function assess() external virtual; function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 tokenId); function availableToWithdraw(uint256 tokenId) external view virtual returns (uint256 interestRedeemable, uint256 principalRedeemable); function withdraw(uint256 tokenId, uint256 amount) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMax(uint256 tokenId) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ICreditLine.sol"; abstract contract IV2CreditLine is ICreditLine { function principal() external view virtual returns (uint256); function totalInterestAccrued() external view virtual returns (uint256); function termStartTime() external view virtual returns (uint256); function setLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; function setPrincipal(uint256 _principal) external virtual; function setTotalInterestAccrued(uint256 _interestAccrued) external virtual; function drawdown(uint256 amount) external virtual; function assess() external virtual returns ( uint256, uint256, uint256 ); function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public virtual; function setTermEndTime(uint256 newTermEndTime) external virtual; function setNextDueTime(uint256 newNextDueTime) external virtual; function setInterestOwed(uint256 newInterestOwed) external virtual; function setPrincipalOwed(uint256 newPrincipalOwed) external virtual; function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual; function setWritedownAmount(uint256 newWritedownAmount) external virtual; function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual; function setLateFeeApr(uint256 newLateFeeApr) external virtual; function updateGoldfinchConfig() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./CreditLine.sol"; import "../../interfaces/ICreditLine.sol"; import "../../external/FixedPoint.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title The Accountant * @notice Library for handling key financial calculations, such as interest and principal accrual. * @author Goldfinch */ library Accountant { using SafeMath for uint256; using FixedPoint for FixedPoint.Signed; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for int256; using FixedPoint for uint256; // Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled uint256 public constant FP_SCALING_FACTOR = 10**18; uint256 public constant INTEREST_DECIMALS = 1e18; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; uint256 public constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365); struct PaymentAllocation { uint256 interestPayment; uint256 principalPayment; uint256 additionalBalancePayment; } function calculateInterestAndPrincipalAccrued( CreditLine cl, uint256 timestamp, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 balance = cl.balance(); // gas optimization uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp); return (interestAccrued, principalAccrued); } function calculateInterestAndPrincipalAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime); return (interestAccrued, principalAccrued); } function calculatePrincipalAccrued( ICreditLine cl, uint256 balance, uint256 timestamp ) public view returns (uint256) { // If we've already accrued principal as of the term end time, then don't accrue more principal uint256 termEndTime = cl.termEndTime(); if (cl.interestAccruedAsOf() >= termEndTime) { return 0; } if (timestamp >= termEndTime) { return balance; } else { return 0; } } function calculateWritedownFor( ICreditLine cl, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate); } function calculateWritedownForPrincipal( ICreditLine cl, uint256 principal, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl); if (amountOwedPerDay.isEqual(0)) { return (0, 0); } FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays); FixedPoint.Unsigned memory daysLate; // Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30, // Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term // has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to // calculate the periods later. uint256 totalOwed = cl.interestOwed().add(cl.principalOwed()); daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay); if (timestamp > cl.termEndTime()) { uint256 secondsLate = timestamp.sub(cl.termEndTime()); daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY)); } FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate); FixedPoint.Unsigned memory writedownPercent; if (daysLate.isLessThanOrEqual(fpGracePeriod)) { // Within the grace period, we don't have to write down, so assume 0% writedownPercent = FixedPoint.fromUnscaledUint(0); } else { writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate)); } FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(FP_SCALING_FACTOR); // This will return a number between 0-100 representing the write down percent with no decimals uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue; return (unscaledWritedownPercent, writedownAmount.rawValue); } function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) { // Determine theoretical interestOwed for one full day uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365); return interestOwed; } function calculateInterestAccrued( CreditLine cl, uint256 balance, uint256 timestamp, uint256 lateFeeGracePeriodInDays ) public view returns (uint256) { // We use Math.min here to prevent integer overflow (ie. go negative) when calculating // numSecondsElapsed. Typically this shouldn't be possible, because // the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing // we allow this function to be called with a past timestamp, which raises the possibility // of overflow. // This use of min should not generate incorrect interest calculations, since // this function's purpose is just to normalize balances, and handing in a past timestamp // will necessarily return zero interest accrued (because zero elapsed time), which is correct. uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf()); return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays); } function calculateInterestAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriodInDays ) public view returns (uint256 interestOwed) { uint256 secondsElapsed = endTime.sub(startTime); uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) { uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS); uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); interestOwed = interestOwed.add(additionalLateFeeInterest); } return interestOwed; } function lateFeeApplicable( CreditLine cl, uint256 timestamp, uint256 gracePeriodInDays ) public view returns (bool) { uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime()); return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_PER_DAY); } function allocatePayment( uint256 paymentAmount, uint256 balance, uint256 interestOwed, uint256 principalOwed ) public pure returns (PaymentAllocation memory) { uint256 paymentRemaining = paymentAmount; uint256 interestPayment = Math.min(interestOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(interestPayment); uint256 principalPayment = Math.min(principalOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(principalPayment); uint256 balanceRemaining = balance.sub(principalPayment); uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining); return PaymentAllocation({ interestPayment: interestPayment, principalPayment: principalPayment, additionalBalancePayment: additionalBalancePayment }); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./PauserPausable.sol"; /** * @title BaseUpgradeablePausable contract * @notice This is our Base contract that most other contracts inherit from. It includes many standard * useful abilities like ugpradeability, pausability, access control, and re-entrancy guards. * @author Goldfinch */ contract BaseUpgradeablePausable is Initializable, AccessControlUpgradeSafe, PauserPausable, ReentrancyGuardUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); using SafeMath for uint256; // Pre-reserving a few slots in the base contract in case we need to add things in the future. // This does not actually take up gas cost or storage cost, but it does reserve the storage slots. // See OpenZeppelin's use of this pattern here: // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37 uint256[50] private __gap1; uint256[50] private __gap2; uint256[50] private __gap3; uint256[50] private __gap4; // solhint-disable-next-line func-name-mixedcase function __BaseUpgradeablePausable__init(address owner) public initializer { require(owner != address(0), "Owner cannot be the zero address"); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "../../interfaces/IPool.sol"; import "../../interfaces/IFidu.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ICreditDesk.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICUSDCContract.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/IGoldfinchFactory.sol"; import "../../interfaces/IGo.sol"; /** * @title ConfigHelper * @notice A convenience library for getting easy access to other contracts and constants within the * protocol, through the use of the GoldfinchConfig contract * @author Goldfinch */ library ConfigHelper { function getPool(GoldfinchConfig config) internal view returns (IPool) { return IPool(poolAddress(config)); } function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) { return ISeniorPool(seniorPoolAddress(config)); } function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) { return ISeniorPoolStrategy(seniorPoolStrategyAddress(config)); } function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(usdcAddress(config)); } function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) { return ICreditDesk(creditDeskAddress(config)); } function getFidu(GoldfinchConfig config) internal view returns (IFidu) { return IFidu(fiduAddress(config)); } function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) { return ICUSDCContract(cusdcContractAddress(config)); } function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) { return IPoolTokens(poolTokensAddress(config)); } function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) { return IGoldfinchFactory(goldfinchFactoryAddress(config)); } function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(gfiAddress(config)); } function getGo(GoldfinchConfig config) internal view returns (IGo) { return IGo(goAddress(config)); } function oneInchAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.OneInch)); } function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation)); } function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder)); } function configAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig)); } function poolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Pool)); } function poolTokensAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens)); } function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool)); } function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy)); } function creditDeskAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk)); } function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory)); } function gfiAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GFI)); } function fiduAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Fidu)); } function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract)); } function usdcAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.USDC)); } function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation)); } function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation)); } function reserveAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve)); } function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin)); } function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation)); } function goAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Go)); } function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator)); } function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator)); } function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays)); } function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays)); } function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds)); } function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays)); } function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title ConfigOptions * @notice A central place for enumerating the configurable options of our GoldfinchConfig contract * @author Goldfinch */ library ConfigOptions { // NEVER EVER CHANGE THE ORDER OF THESE! // You can rename or append. But NEVER change the order. enum Numbers { TransactionLimit, TotalFundsLimit, MaxUnderwriterLimit, ReserveDenominator, WithdrawFeeDenominator, LatenessGracePeriodInDays, LatenessMaxDays, DrawdownPeriodInSeconds, TransferRestrictionPeriodInDays, LeverageRatio } enum Addresses { Pool, CreditLineImplementation, GoldfinchFactory, CreditDesk, Fidu, USDC, TreasuryReserve, ProtocolAdmin, OneInch, TrustedForwarder, CUSDCContract, GoldfinchConfig, PoolTokens, TranchedPoolImplementation, SeniorPool, SeniorPoolStrategy, MigratedTranchedPoolImplementation, BorrowerImplementation, GFI, Go } function getNumberName(uint256 number) public pure returns (string memory) { Numbers numberName = Numbers(number); if (Numbers.TransactionLimit == numberName) { return "TransactionLimit"; } if (Numbers.TotalFundsLimit == numberName) { return "TotalFundsLimit"; } if (Numbers.MaxUnderwriterLimit == numberName) { return "MaxUnderwriterLimit"; } if (Numbers.ReserveDenominator == numberName) { return "ReserveDenominator"; } if (Numbers.WithdrawFeeDenominator == numberName) { return "WithdrawFeeDenominator"; } if (Numbers.LatenessGracePeriodInDays == numberName) { return "LatenessGracePeriodInDays"; } if (Numbers.LatenessMaxDays == numberName) { return "LatenessMaxDays"; } if (Numbers.DrawdownPeriodInSeconds == numberName) { return "DrawdownPeriodInSeconds"; } if (Numbers.TransferRestrictionPeriodInDays == numberName) { return "TransferRestrictionPeriodInDays"; } if (Numbers.LeverageRatio == numberName) { return "LeverageRatio"; } revert("Unknown value passed to getNumberName"); } function getAddressName(uint256 addressKey) public pure returns (string memory) { Addresses addressName = Addresses(addressKey); if (Addresses.Pool == addressName) { return "Pool"; } if (Addresses.CreditLineImplementation == addressName) { return "CreditLineImplementation"; } if (Addresses.GoldfinchFactory == addressName) { return "GoldfinchFactory"; } if (Addresses.CreditDesk == addressName) { return "CreditDesk"; } if (Addresses.Fidu == addressName) { return "Fidu"; } if (Addresses.USDC == addressName) { return "USDC"; } if (Addresses.TreasuryReserve == addressName) { return "TreasuryReserve"; } if (Addresses.ProtocolAdmin == addressName) { return "ProtocolAdmin"; } if (Addresses.OneInch == addressName) { return "OneInch"; } if (Addresses.TrustedForwarder == addressName) { return "TrustedForwarder"; } if (Addresses.CUSDCContract == addressName) { return "CUSDCContract"; } if (Addresses.PoolTokens == addressName) { return "PoolTokens"; } if (Addresses.TranchedPoolImplementation == addressName) { return "TranchedPoolImplementation"; } if (Addresses.SeniorPool == addressName) { return "SeniorPool"; } if (Addresses.SeniorPoolStrategy == addressName) { return "SeniorPoolStrategy"; } if (Addresses.MigratedTranchedPoolImplementation == addressName) { return "MigratedTranchedPoolImplementation"; } if (Addresses.BorrowerImplementation == addressName) { return "BorrowerImplementation"; } if (Addresses.GFI == addressName) { return "GFI"; } if (Addresses.Go == addressName) { return "Go"; } revert("Unknown value passed to getAddressName"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "./ConfigHelper.sol"; import "./BaseUpgradeablePausable.sol"; import "./Accountant.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICreditLine.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; /** * @title CreditLine * @notice A contract that represents the agreement between Backers and * a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed. * A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not * operate in any standalone capacity. It should generally be considered internal to the TranchedPool. * @author Goldfinch */ // solhint-disable-next-line max-states-count contract CreditLine is BaseUpgradeablePausable, ICreditLine { uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; event GoldfinchConfigUpdated(address indexed who, address configAddress); // Credit line terms address public override borrower; uint256 public override limit; uint256 public override interestApr; uint256 public override paymentPeriodInDays; uint256 public override termInDays; uint256 public override lateFeeApr; // Accounting variables uint256 public override balance; uint256 public override interestOwed; uint256 public override principalOwed; uint256 public override termEndTime; uint256 public override nextDueTime; uint256 public override interestAccruedAsOf; uint256 public override lastFullPaymentTime; uint256 public totalInterestAccrued; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public initializer { require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in"); __BaseUpgradeablePausable__init(owner); config = GoldfinchConfig(_config); borrower = _borrower; limit = _limit; interestApr = _interestApr; paymentPeriodInDays = _paymentPeriodInDays; termInDays = _termInDays; lateFeeApr = _lateFeeApr; interestAccruedAsOf = block.timestamp; // Unlock owner, which is a TranchedPool, for infinite amount bool success = config.getUSDC().approve(owner, uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Updates the internal accounting to track a drawdown as of current block timestamp. * Does not move any money * @param amount The amount in USDC that has been drawndown */ function drawdown(uint256 amount) external onlyAdmin { require(amount.add(balance) <= limit, "Cannot drawdown more than the limit"); uint256 timestamp = currentTime(); if (balance == 0) { setInterestAccruedAsOf(timestamp); setLastFullPaymentTime(timestamp); setTotalInterestAccrued(0); setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays))); } (uint256 _interestOwed, uint256 _principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); balance = balance.add(amount); updateCreditLineAccounting(balance, _interestOwed, _principalOwed); require(!isLate(timestamp), "Cannot drawdown when payments are past due"); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin { lateFeeApr = newLateFeeApr; } function setLimit(uint256 newAmount) external onlyAdmin { limit = newAmount; } function termStartTime() external view returns (uint256) { return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays)); } function setTermEndTime(uint256 newTermEndTime) public onlyAdmin { termEndTime = newTermEndTime; } function setNextDueTime(uint256 newNextDueTime) public onlyAdmin { nextDueTime = newNextDueTime; } function setBalance(uint256 newBalance) public onlyAdmin { balance = newBalance; } function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin { totalInterestAccrued = _totalInterestAccrued; } function setInterestOwed(uint256 newInterestOwed) public onlyAdmin { interestOwed = newInterestOwed; } function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin { principalOwed = newPrincipalOwed; } function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin { interestAccruedAsOf = newInterestAccruedAsOf; } function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin { lastFullPaymentTime = newLastFullPaymentTime; } /** * @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied * towards the interest and principal. * @return Any amount remaining after applying payments towards the interest and principal * @return Amount applied towards interest * @return Amount applied towards principal */ function assess() public onlyAdmin returns ( uint256, uint256, uint256 ) { // Do not assess until a full period has elapsed or past due require(balance > 0, "Must have balance to assess credit line"); // Don't assess credit lines early! if (currentTime() < nextDueTime && !isLate(currentTime())) { return (0, 0, 0); } uint256 timeToAssess = calculateNextDueTime(); setNextDueTime(timeToAssess); // We always want to assess for the most recently *past* nextDueTime. // So if the recalculation above sets the nextDueTime into the future, // then ensure we pass in the one just before this. if (timeToAssess > currentTime()) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); timeToAssess = timeToAssess.sub(secondsPerPeriod); } return handlePayment(getUSDCBalance(address(this)), timeToAssess); } function calculateNextDueTime() internal view returns (uint256) { uint256 newNextDueTime = nextDueTime; uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); uint256 curTimestamp = currentTime(); // You must have just done your first drawdown if (newNextDueTime == 0 && balance > 0) { return curTimestamp.add(secondsPerPeriod); } // Active loan that has entered a new period, so return the *next* newNextDueTime. // But never return something after the termEndTime if (balance > 0 && curTimestamp >= newNextDueTime) { uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod); newNextDueTime = newNextDueTime.add(secondsToAdvance); return Math.min(newNextDueTime, termEndTime); } // You're paid off, or have not taken out a loan yet, so no next due time. if (balance == 0 && newNextDueTime != 0) { return 0; } // Active loan in current period, where we've already set the newNextDueTime correctly, so should not change. if (balance > 0 && curTimestamp < newNextDueTime) { return newNextDueTime; } revert("Error: could not calculate next due time."); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function isLate(uint256 timestamp) internal view returns (bool) { uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime); return secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY); } /** * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool. * It also updates all the accounting variables. Note that interest is always paid back first, then principal. * Any extra after paying the minimum will go towards existing principal (reducing the * effective interest rate). Any extra after the full loan has been paid off will remain in the * USDC Balance of the creditLine, where it will be automatically used for the next drawdown. * @param paymentAmount The amount, in USDC atomic units, to be applied * @param timestamp The timestamp on which accrual calculations should be based. This allows us * to be precise when we assess a Credit Line */ function handlePayment(uint256 paymentAmount, uint256 timestamp) internal returns ( uint256, uint256, uint256 ) { (uint256 newInterestOwed, uint256 newPrincipalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment( paymentAmount, balance, newInterestOwed, newPrincipalOwed ); uint256 newBalance = balance.sub(pa.principalPayment); // Apply any additional payment towards the balance newBalance = newBalance.sub(pa.additionalBalancePayment); uint256 totalPrincipalPayment = balance.sub(newBalance); uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting( newBalance, newInterestOwed.sub(pa.interestPayment), newPrincipalOwed.sub(pa.principalPayment) ); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) { (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued( this, timestamp, config.getLatenessGracePeriodInDays() ); if (interestAccrued > 0) { // If we've accrued any interest, update interestAccruedAsOf to the time that we've // calculated interest for. If we've not accrued any interest, then we keep the old value so the next // time the entire period is taken into account. setInterestAccruedAsOf(timestamp); totalInterestAccrued = totalInterestAccrued.add(interestAccrued); } return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued)); } function updateCreditLineAccounting( uint256 newBalance, uint256 newInterestOwed, uint256 newPrincipalOwed ) internal nonReentrant { setBalance(newBalance); setInterestOwed(newInterestOwed); setPrincipalOwed(newPrincipalOwed); // This resets lastFullPaymentTime. These conditions assure that they have // indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown) uint256 _nextDueTime = nextDueTime; if (newInterestOwed == 0 && _nextDueTime != 0) { // If interest was fully paid off, then set the last full payment as the previous due time uint256 mostRecentLastDueTime; if (currentTime() < _nextDueTime) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod); } else { mostRecentLastDueTime = _nextDueTime; } setLastFullPaymentTime(mostRecentLastDueTime); } setNextDueTime(calculateNextDueTime()); } function getUSDCBalance(address _address) internal view returns (uint256) { return config.getUSDC().balanceOf(_address); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "../../interfaces/IGoldfinchConfig.sol"; import "./ConfigOptions.sol"; /** * @title GoldfinchConfig * @notice This contract stores mappings of useful "protocol config state", giving a central place * for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars * are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol. * Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this * is mostly to save gas costs of having each call go through a proxy) * @author Goldfinch */ contract GoldfinchConfig is BaseUpgradeablePausable { bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE"); mapping(uint256 => address) public addresses; mapping(uint256 => uint256) public numbers; mapping(address => bool) public goList; event AddressUpdated(address owner, uint256 index, address oldValue, address newValue); event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue); event GoListed(address indexed member); event NoListed(address indexed member); bool public valuesInitialized; function initialize(address owner) public initializer { require(owner != address(0), "Owner address cannot be empty"); __BaseUpgradeablePausable__init(owner); _setupRole(GO_LISTER_ROLE, owner); _setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE); } function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin { require(addresses[addressIndex] == address(0), "Address has already been initialized"); emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress); addresses[addressIndex] = newAddress; } function setNumber(uint256 index, uint256 newNumber) public onlyAdmin { emit NumberUpdated(msg.sender, index, numbers[index], newNumber); numbers[index] = newNumber; } function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve); emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve); addresses[key] = newTreasuryReserve; } function setSeniorPoolStrategy(address newStrategy) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy); emit AddressUpdated(msg.sender, key, addresses[key], newStrategy); addresses[key] = newStrategy; } function setCreditLineImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setBorrowerImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setGoldfinchConfig(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function initializeFromOtherConfig(address _initialConfig) public onlyAdmin { require(!valuesInitialized, "Already initialized values"); IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig); for (uint256 i = 0; i < 10; i++) { setNumber(i, initialConfig.getNumber(i)); } for (uint256 i = 0; i < 11; i++) { if (getAddress(i) == address(0)) { setAddress(i, initialConfig.getAddress(i)); } } valuesInitialized = true; } /** * @dev Adds a user to go-list * @param _member address to add to go-list */ function addToGoList(address _member) public onlyGoListerRole { goList[_member] = true; emit GoListed(_member); } /** * @dev removes a user from go-list * @param _member address to remove from go-list */ function removeFromGoList(address _member) public onlyGoListerRole { goList[_member] = false; emit NoListed(_member); } /** * @dev adds many users to go-list at once * @param _members addresses to ad to go-list */ function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { addToGoList(_members[i]); } } /** * @dev removes many users from go-list at once * @param _members addresses to remove from go-list */ function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { removeFromGoList(_members[i]); } } /* Using custom getters in case we want to change underlying implementation later, or add checks or validations later on. */ function getAddress(uint256 index) public view returns (address) { return addresses[index]; } function getNumber(uint256 index) public view returns (uint256) { return numbers[index]; } modifier onlyGoListerRole() { require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; /** * @title PauserPausable * @notice Inheriting from OpenZeppelin's Pausable contract, this does small * augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract. * It is meant to be inherited. * @author Goldfinch */ contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __PauserPausable__init() public initializer { __Pausable_init_unchained(); } /** * @dev Pauses all functions guarded by Pause * * See {Pausable-_pause}. * * Requirements: * * - the caller must have the PAUSER_ROLE. */ function pause() public onlyPauserRole { _pause(); } /** * @dev Unpauses the contract * * See {Pausable-_unpause}. * * Requirements: * * - the caller must have the Pauser role */ function unpause() public onlyPauserRole { _unpause(); } modifier onlyPauserRole() { require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action"); _; } }
Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30, Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to calculate the periods later.
uint256 totalOwed = cl.interestOwed().add(cl.principalOwed());
470,029
[ 1, 7177, 4233, 30, 273, 1154, 12, 21, 16, 1896, 12, 20, 16, 20659, 67, 20293, 67, 267, 67, 9810, 17, 2752, 311, 6908, 67, 267, 67, 9810, 13176, 6694, 67, 16852, 67, 31551, 67, 10512, 13, 13658, 67, 6908, 273, 5196, 16, 11672, 326, 2481, 679, 1509, 16, 732, 999, 326, 16513, 3494, 329, 358, 4604, 326, 12777, 26374, 18, 10724, 16, 1839, 326, 28183, 2481, 711, 16926, 16, 3241, 326, 16513, 353, 279, 9816, 10648, 8330, 434, 326, 8897, 16, 732, 2780, 14719, 6906, 999, 16513, 358, 4604, 326, 12777, 5137, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 2254, 5034, 2078, 3494, 329, 273, 927, 18, 2761, 395, 3494, 329, 7675, 1289, 12, 830, 18, 26138, 3494, 329, 10663, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.4.22 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Report Framework * @notice Smart Contract developed for the Harmony One Round 2 Hackathon on Gitcoin * @dev On-Chain reporting of a single metric and its count defined by a key and a category. * It will store each in a bucket denoted by the {Report}-{getReportingPeriodFor} function, * which defines a bucket given a timestamp. The report is configured for weekly reporting, * with a week starting on Sunday. Override the {getReportingPeriodFor} to derive your own reporting period. * * Note Use the provided API to update the global report or the latest reports. When updating the latest * reports, the global report is also updated. * Designed as real-time reporting. A global report keeps track of overall accumulated values. * * Note no overflow has been added ... something to be mindful of * * @author victaphu */ contract Report is Ownable { // a report period represents a single report period start/end date // a sum/count for each report period is provided when updating // reports hold all the keyed reports for a given date range struct ReportPeriod { uint256 startRange; uint256 endRange; uint256 sum; uint256 count; bytes[] keys; mapping(bytes => ReportOverview) reports; } // a report overview represents the next level and represents one level // further of details. the focus of the report is presented as a key struct ReportOverview { uint256 sum; uint256 count; bytes[] categories; mapping(bytes => ReportItem) reportItems; } // reports can be further divided into report items which represent the // lowest level of reporting. struct ReportItem { uint256 sum; uint256 count; } mapping(address => bool) private _access; uint256 constant DAY_IN_SECONDS = 86400; // this represents a global overview of reports ReportPeriod private _overallReport; mapping(uint256 => ReportPeriod) private reports; /** * @dev return the latest report object using the latest timestamp to find the * report from reports mapping. * * @return period latest report using timestamp to derive the timeslot */ function getLatestReportObject() internal view returns (ReportPeriod storage period) { period = reports[getLatestReportingPeriod()]; } /** * @dev given a unix timestamp (in seconds) return the current weekday * note week 0 is sunday, week 6 is saturday * * @param timestamp unix timestamp in seconds (e.g. block.timestamp) * @return weekday the day of week between 0 and 6 (inclusive) */ function getWeekday(uint256 timestamp) public pure returns (uint8 weekday) { weekday = uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } /** * @dev this function will take a timestamp and normalise it to a value. * By default, reports are normalised to closest start of the week, so this * function will help generate weekly reports * * @param timestamp is the UNIX timestamp (in seconds) e.g. the block.timestamp */ function getReportPeriodFor(uint256 timestamp) public view virtual returns (uint256 reportPeriod) { uint256 currentDOW = getWeekday(timestamp); timestamp = (timestamp - currentDOW * DAY_IN_SECONDS); timestamp = timestamp - timestamp % DAY_IN_SECONDS; reportPeriod = timestamp; } /** * @dev get the latest reporting period given the block timestamp. Return a normalised value * based on timestamp. By default we return normalised by week * * @return reportPeriod the normalised report period for the latest timestamp */ function getLatestReportingPeriod() public view returns (uint256 reportPeriod) { return getReportPeriodFor(block.timestamp); } /** * @dev grant access to selected reporter. only the owner of the report object may assign reporters * * @param reporter the address of user/contract that may update this report */ function grantAccess(address reporter) public onlyOwner { _access[reporter] = true; } /** * @dev revoke access for a selected reporter. only the owner of the report may revoke reporters * * @param reporter the address of the user/contract that we are revoking access */ function revokeAccess(address reporter) public onlyOwner { _access[reporter] = false; } modifier accessible() { require( _access[msg.sender] || owner() == msg.sender, "Cannot access reporting function" ); _; } /** * @dev update a report given the period and the value. If the period is 0, then * the global report is updated. The sum is increased by the supplied value and the * count is incremented by 1 * * @param period is the normalised period that we want to update. * @param value is the value to be added */ function updateReport(uint256 period, uint256 value) private { ReportPeriod storage latest; if (period == 0) { latest = _overallReport; } else { latest = getLatestReportObject(); } latest.count += 1; latest.sum += value; } /** * @dev update a report given the period, key and the value. If the period is 0, then * the global report is updated. The sum is increased by the supplied value and the * count is incremented by 1. The key represents one additional dimension of data recorded * * @param period the normalised period that we want to update. * @param key the key dimension for this report * @param value the value to be added */ function updateReport( uint256 period, bytes memory key, uint256 value ) private { updateReport(period, value); ReportPeriod storage latest; if (period == 0) { latest = _overallReport; } else { latest = getLatestReportObject(); } ReportOverview storage overview = latest.reports[key]; if (overview.count == 0) { latest.keys.push(key); } overview.count += 1; overview.sum += value; } /** * @dev update a report given the period, key and category and the value. If the period is 0, then * the global report is updated. The sum is increased by the supplied value and the * count is incremented by 1. The key and category can be used to capture more fine-grain data * note data is rolled up to the parent * * @param period the normalised period that we want to update. * @param key the key dimension for this report * @param category the category dimension for this report * @param value the value to be added */ function updateReport( uint256 period, bytes memory key, bytes memory category, uint256 value ) private { updateReport(period, key, value); ReportPeriod storage latest; if (period == 0) { latest = _overallReport; } else { latest = getLatestReportObject(); } ReportOverview storage overview = latest.reports[key]; ReportItem storage item = overview.reportItems[category]; if (item.count == 0) { overview.categories.push(category); overview.reportItems[category] = item; } item.count += 1; item.sum += value; } /** * @dev update the latest report, and update the global report for the running total * * @param value the value to be added */ function updateLatestReport(uint256 value) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, value); updateReport(0, value); // update global report } /** * @dev update the latest report, and update the global report for the running total * * @param key the key dimension for this report * @param value the value to be added */ function updateLatestReport(bytes memory key, uint256 value) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, key, value); updateReport(0, key, value); // update global report } /** * @dev update the latest report, and update the global report for the running total * * @param key the key dimension for this report * @param category the category dimension for this report * @param value the value to be added */ function updateLatestReport( bytes memory key, bytes memory category, uint256 value ) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, key, category, value); updateReport(0, key, category, value); // update global report } /** * @dev update the global report, this should be used if there is no intention to * have the report tool manage the running totals * * @param value the value to be added */ function updateGlobalReport(uint256 value) external accessible { updateReport(0, value); } /** * @dev update the global report, this should be used if there is no intention to * have the report tool manage the running totals * * @param key the key dimension for this report * @param value the value to be added */ function updateGlobalReport(bytes memory key, uint256 value) external accessible { updateReport(0, key, value); } /** * @dev update the global report, this should be used if there is no intention to * have the report tool manage the running totals * * @param key the key dimension for this report * @param category the category dimension for this report * @param value the value to be added */ function updateGlobalReport( bytes memory key, bytes memory category, uint256 value ) external accessible { updateReport(0, key, category, value); } /** * @dev get the report for a given period. supply 0 for the argument to get the global report * note returns data for the next level, use the keys to query further * * @param period the period for which we want to retrieve the data * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getReportForPeriod(uint256 period) public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { ReportPeriod storage report; if (period == 0) { report = _overallReport; } else { report = reports[period]; } sum = report.sum; count = report.count; keys = report.keys; uint256[] memory sumStorage = new uint256[](keys.length); uint256[] memory countStorage = new uint256[](keys.length); for (uint256 i = 0; i < keys.length; i++) { sumStorage[i] = report.reports[keys[i]].sum; countStorage[i] = report.reports[keys[i]].count; } sums = sumStorage; counts = countStorage; } /** * @dev get the report for a given period and key dimension. supply 0 for the argument to get the global report * note returns data for the next level, use the keys to query further * * @param period the period for which we want to retrieve the data * @param key the key dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getReportForPeriod(uint256 period, bytes memory key) public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { ReportPeriod storage report; if (period == 0) { report = _overallReport; } else { report = reports[period]; } ReportOverview storage reportOverview = report.reports[key]; sum = reportOverview.sum; count = reportOverview.count; keys = reportOverview.categories; uint256[] memory sumStorage = new uint256[](keys.length); uint256[] memory countStorage = new uint256[](keys.length); for (uint256 i = 0; i < keys.length; i++) { sumStorage[i] = reportOverview.reportItems[keys[i]].sum; countStorage[i] = reportOverview.reportItems[keys[i]].count; } sums = sumStorage; counts = countStorage; } /** * @dev get the report for a given period and key dimension. supply 0 for the argument to get the global report * note returns data for the next level, use the keys to query further * * @param period the period for which we want to retrieve the data * @param key the key dimension which we want to report on * @param category the category dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report */ function getReportForPeriod( uint256 period, bytes memory key, bytes memory category ) public view returns (uint256 sum, uint256 count) { ReportPeriod storage report; if (period == 0) { report = _overallReport; } else { report = reports[period]; } ReportItem storage item = report.reports[key].reportItems[category]; sum = item.sum; count = item.count; } /** * @dev get the latest report at the highest level. includes key dimension breakdown * note returns data for the next level, use the keys to query further * * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getLatestReport() public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { return getReportForPeriod(getLatestReportingPeriod()); } /** * @dev get the latest report for a key dimension * note returns data for the next level, use the categories to query further * * @param key the key dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getLatestReport(bytes memory key) public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { return getReportForPeriod(getLatestReportingPeriod(), key); } /** * @dev get the latest report for a key and category dimension * * @param key the key dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report */ function getLatestReport(bytes memory key, bytes memory category) public view returns (uint256 sum, uint256 count) { return getReportForPeriod(getLatestReportingPeriod(), key, category); } }
update global report
updateReport(0, value);
12,965,553
[ 1, 2725, 2552, 2605, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 1089, 4820, 12, 20, 16, 460, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; 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; } } 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 GovChecker is Ownable { IRegistry public reg; bytes32 public constant GOV_NAME = "GovernanceContract"; bytes32 public constant STAKING_NAME = "Staking"; bytes32 public constant BALLOT_STORAGE_NAME = "BallotStorage"; bytes32 public constant ENV_STORAGE_NAME = "EnvStorage"; bytes32 public constant REWARD_POOL_NAME = "RewardPool"; /** * @dev Function to set registry address. Contract that wants to use registry should setRegistry first. * @param _addr address of registry * @return A boolean that indicates if the operation was successful. */ function setRegistry(address _addr) public onlyOwner { require(_addr != address(0), "Address should be non-zero"); reg = IRegistry(_addr); } modifier onlyGov() { require(getGovAddress() == msg.sender, "No Permission"); _; } modifier onlyGovMem() { require(IGov(getGovAddress()).isMember(msg.sender), "No Permission"); _; } modifier anyGov() { require(getGovAddress() == msg.sender || IGov(getGovAddress()).isMember(msg.sender), "No Permission"); _; } function getContractAddress(bytes32 name) internal view returns (address) { return reg.getContractAddress(name); } function getGovAddress() internal view returns (address) { return getContractAddress(GOV_NAME); } function getStakingAddress() internal view returns (address) { return getContractAddress(STAKING_NAME); } function getBallotStorageAddress() internal view returns (address) { return getContractAddress(BALLOT_STORAGE_NAME); } function getEnvStorageAddress() internal view returns (address) { return getContractAddress(ENV_STORAGE_NAME); } function getRewardPoolAddress() internal view returns (address) { return getContractAddress(REWARD_POOL_NAME); } } contract Staking is GovChecker, ReentrancyGuard { using SafeMath for uint256; mapping(address => uint256) private _balance; mapping(address => uint256) private _lockedBalance; uint256 private _totalLockedBalance; bool private revoked = false; event Staked(address indexed payee, uint256 amount, uint256 total, uint256 available); event Unstaked(address indexed payee, uint256 amount, uint256 total, uint256 available); event Locked(address indexed payee, uint256 amount, uint256 total, uint256 available); event Unlocked(address indexed payee, uint256 amount, uint256 total, uint256 available); event TransferLocked(address indexed payee, uint256 amount, uint256 total, uint256 available); event Revoked(address indexed owner, uint256 amount); constructor(address registry, bytes data) public { _totalLockedBalance = 0; setRegistry(registry); if (data.length == 0) return; // []{address, amount} address addr; uint amount; uint ix; uint eix; assembly { ix := add(data, 0x20) } eix = ix + data.length; while (ix < eix) { assembly { amount := mload(ix) } addr = address(amount); ix += 0x20; require(ix < eix); assembly { amount := mload(ix) } ix += 0x20; _balance[addr] = amount; } } function () external payable { revert(); } /** * @dev Deposit from a sender. */ function deposit() external nonReentrant notRevoked payable { require(msg.value > 0, "Deposit amount should be greater than zero"); _balance[msg.sender] = _balance[msg.sender].add(msg.value); emit Staked(msg.sender, msg.value, _balance[msg.sender], availableBalanceOf(msg.sender)); } /** * @dev Withdraw for a sender. * @param amount The amount of funds will be withdrawn and transferred to. */ function withdraw(uint256 amount) external nonReentrant notRevoked { require(amount > 0, "Amount should be bigger than zero"); require(amount <= availableBalanceOf(msg.sender), "Withdraw amount should be equal or less than balance"); _balance[msg.sender] = _balance[msg.sender].sub(amount); msg.sender.transfer(amount); emit Unstaked(msg.sender, amount, _balance[msg.sender], availableBalanceOf(msg.sender)); } /** * @dev Lock fund * @param payee The address whose funds will be locked. * @param lockAmount The amount of funds will be locked. */ function lock(address payee, uint256 lockAmount) external onlyGov { if (lockAmount == 0) return; require(_balance[payee] >= lockAmount, "Lock amount should be equal or less than balance"); require(availableBalanceOf(payee) >= lockAmount, "Insufficient balance that can be locked"); _lockedBalance[payee] = _lockedBalance[payee].add(lockAmount); _totalLockedBalance = _totalLockedBalance.add(lockAmount); emit Locked(payee, lockAmount, _balance[payee], availableBalanceOf(payee)); } /** * @dev Transfer locked funds to governance * @param from The address whose funds will be transfered. * @param amount The amount of funds will be transfered. */ function transferLocked(address from, uint256 amount) external onlyGov { if (amount == 0) return; unlock(from, amount); _balance[from] = _balance[from].sub(amount); address rewardPool = getRewardPoolAddress(); _balance[rewardPool] = _balance[rewardPool].add(amount); emit TransferLocked(from, amount, _balance[from], availableBalanceOf(from)); } /** * @dev Unlock fund * @param payee The address whose funds will be unlocked. * @param unlockAmount The amount of funds will be unlocked. */ function unlock(address payee, uint256 unlockAmount) public onlyGov { if (unlockAmount == 0) return; // require(_lockedBalance[payee] >= unlockAmount, "Unlock amount should be equal or less than balance locked"); _lockedBalance[payee] = _lockedBalance[payee].sub(unlockAmount); _totalLockedBalance = _totalLockedBalance.sub(unlockAmount); emit Unlocked(payee, unlockAmount, _balance[payee], availableBalanceOf(payee)); } function balanceOf(address payee) public view returns (uint256) { return _balance[payee]; } function lockedBalanceOf(address payee) public view returns (uint256) { return _lockedBalance[payee]; } function availableBalanceOf(address payee) public view returns (uint256) { return _balance[payee].sub(_lockedBalance[payee]); } /** * @dev Calculate voting weight which range between 0 and 100. * @param payee The address whose funds were locked. */ function calcVotingWeight(address payee) public view returns (uint256) { return calcVotingWeightWithScaleFactor(payee, 1e2); } /** * @dev Calculate voting weight with a scale factor. * @param payee The address whose funds were locked. * @param factor The scale factor for weight. For instance: * if 1e1, result range is between 0 ~ 10 * if 1e2, result range is between 0 ~ 100 * if 1e3, result range is between 0 ~ 1000 */ function calcVotingWeightWithScaleFactor(address payee, uint32 factor) public view returns (uint256) { if (_lockedBalance[payee] == 0 || factor == 0) return 0; return _lockedBalance[payee].mul(factor).div(_totalLockedBalance); } function isRevoked() public view returns (bool) { return revoked; } modifier notRevoked(){ require(!revoked, "Is revoked"); _; } /** * @notice Allows the owner to revoke the staking. Coins already staked * staked funds are returned to the owner. */ function revoke() public onlyOwner notRevoked{ address contractOwner = owner(); uint256 balance = address(this).balance; require(balance > 0); contractOwner.transfer(balance); revoked = true; emit Revoked(contractOwner, balance); } } interface IGov { function isMember(address) external view returns (bool); function getMember(uint256) external view returns (address); function getMemberLength() external view returns (uint256); function getReward(uint256) external view returns (address); function getNodeIdxFromMember(address) external view returns (uint256); function getMemberFromNodeIdx(uint256) external view returns (address); function getNodeLength() external view returns (uint256); function getNode(uint256) external view returns (bytes, bytes, bytes, uint); function getBallotInVoting() external view returns (uint256); } interface IRegistry { function getContractAddress(bytes32) external view returns (address); }
* @dev Function to set registry address. Contract that wants to use registry should setRegistry first. @param _addr address of registry @return A boolean that indicates if the operation was successful./
function setRegistry(address _addr) public onlyOwner { require(_addr != address(0), "Address should be non-zero"); reg = IRegistry(_addr); }
1,827,824
[ 1, 2083, 358, 444, 4023, 1758, 18, 13456, 716, 14805, 358, 999, 4023, 1410, 444, 4243, 1122, 18, 225, 389, 4793, 1758, 434, 4023, 327, 432, 1250, 716, 8527, 309, 326, 1674, 1703, 6873, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 4243, 12, 2867, 389, 4793, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 4793, 480, 1758, 12, 20, 3631, 315, 1887, 1410, 506, 1661, 17, 7124, 8863, 203, 3639, 960, 273, 467, 4243, 24899, 4793, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; abstract contract Context { function _MSGSENDER442() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA841() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } function _ADD793(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS602(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } function _REMOVE671(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } function _CONTAINS602(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH966(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT186(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD955(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD793(set._inner, bytes32(uint256(value))); } function REMOVE612(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE671(set._inner, bytes32(uint256(value))); } function CONTAINS582(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS602(set._inner, bytes32(uint256(value))); } function LENGTH322(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH966(set._inner); } function AT372(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT186(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD955(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD793(set._inner, bytes32(value)); } function REMOVE612(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE671(set._inner, bytes32(value)); } function CONTAINS582(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS602(set._inner, bytes32(value)); } function LENGTH322(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH966(set._inner); } function AT372(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT186(set._inner, index)); } } library SafeMath { function ADD955(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB444(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB444(a, b, "SafeMath: subtraction overflow"); } function SUB444(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL509(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV140(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV140(a, b, "SafeMath: division by zero"); } function DIV140(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD127(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD127(a, b, "SafeMath: modulo by zero"); } function MOD127(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract Pausable is Context { event PAUSED925(address account); //inject NONSTANDARD NAMING event UNPAUSED624(address account); //inject NONSTANDARD NAMING bool private _paused; constructor () internal { _paused = false; } function PAUSED303() public view returns (bool) { //inject NONSTANDARD NAMING return _paused; } modifier WHENNOTPAUSED156() { //inject NONSTANDARD NAMING require(!_paused, "Pausable: paused"); _; } modifier WHENPAUSED81() { //inject NONSTANDARD NAMING require(_paused, "Pausable: not paused"); _; } function _PAUSE21() internal virtual WHENNOTPAUSED156 { //inject NONSTANDARD NAMING _paused = true; emit PAUSED925(_MSGSENDER442()); } function _UNPAUSE943() internal virtual WHENPAUSED81 { //inject NONSTANDARD NAMING _paused = false; emit UNPAUSED624(_MSGSENDER442()); } } abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant default_admin_role643 = 0x00; //inject NONSTANDARD NAMING event ROLEADMINCHANGED358(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING event ROLEGRANTED844(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING event ROLEREVOKED840(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING function HASROLE566(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING return _roles[role].members.CONTAINS582(account); } function GETROLEMEMBERCOUNT266(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING return _roles[role].members.LENGTH322(); } function GETROLEMEMBER390(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING return _roles[role].members.AT372(index); } function GETROLEADMIN142(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING return _roles[role].adminRole; } function GRANTROLE448(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE566(_roles[role].adminRole, _MSGSENDER442()), "AccessControl: sender must be an admin to grant"); _GRANTROLE994(role, account); } function REVOKEROLE161(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE566(_roles[role].adminRole, _MSGSENDER442()), "AccessControl: sender must be an admin to revoke"); _REVOKEROLE858(role, account); } function RENOUNCEROLE414(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(account == _MSGSENDER442(), "AccessControl: can only renounce roles for self"); _REVOKEROLE858(role, account); } function _SETUPROLE604(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING _GRANTROLE994(role, account); } function _SETROLEADMIN339(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING emit ROLEADMINCHANGED358(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _GRANTROLE994(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.ADD955(account)) { emit ROLEGRANTED844(role, account, _MSGSENDER442()); } } function _REVOKEROLE858(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.REMOVE612(account)) { emit ROLEREVOKED840(role, account, _MSGSENDER442()); } } } library Address { function ISCONTRACT149(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE745(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL287(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL287(target, data, "Address: low-level call failed"); } function FUNCTIONCALL287(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE197(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE757(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE757(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE757(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE197(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE197(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT149(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); } } } } interface IERC20 { function NAME653() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL206() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS526() external view returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY875() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF638(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE195(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER72(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE120(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM500( //inject NONSTANDARD NAMING address from, address to, uint value ) external returns (bool); event TRANSFER974(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL68(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract LnAdmin { address public admin; address public candidate; constructor(address _admin) public { require(_admin != address(0), "admin address cannot be 0"); admin = _admin; emit ADMINCHANGED70(address(0), _admin); } function SETCANDIDATE399(address _candidate) external ONLYADMIN30 { //inject NONSTANDARD NAMING address old = candidate; candidate = _candidate; emit CANDIDATECHANGED218( old, candidate); } function BECOMEADMIN406( ) external { //inject NONSTANDARD NAMING require( msg.sender == candidate, "Only candidate can become admin"); address old = admin; admin = candidate; emit ADMINCHANGED70( old, admin ); } modifier ONLYADMIN30 { //inject NONSTANDARD NAMING require( (msg.sender == admin), "Only the contract admin can perform this action"); _; } event CANDIDATECHANGED218(address oldCandidate, address newCandidate ); //inject NONSTANDARD NAMING event ADMINCHANGED70(address oldAdmin, address newAdmin); //inject NONSTANDARD NAMING } library SafeDecimalMath { using SafeMath for uint; uint8 public constant decimals39 = 18; //inject NONSTANDARD NAMING uint8 public constant highprecisiondecimals272 = 27; //inject NONSTANDARD NAMING uint public constant unit739 = 10**uint(decimals39); //inject NONSTANDARD NAMING uint public constant precise_unit766 = 10**uint(highprecisiondecimals272); //inject NONSTANDARD NAMING uint private constant unit_to_high_precision_conversion_factor241 = 10**uint(highprecisiondecimals272 - decimals39); //inject NONSTANDARD NAMING function UNIT5() external pure returns (uint) { //inject NONSTANDARD NAMING return unit739; } function PRECISEUNIT401() external pure returns (uint) { //inject NONSTANDARD NAMING return precise_unit766; } function MULTIPLYDECIMAL731(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return x.MUL509(y) / unit739; } function _MULTIPLYDECIMALROUND367( //inject NONSTANDARD NAMING uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint quotientTimesTen = x.MUL509(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } function MULTIPLYDECIMALROUNDPRECISE456(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return _MULTIPLYDECIMALROUND367(x, y, precise_unit766); } function MULTIPLYDECIMALROUND81(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return _MULTIPLYDECIMALROUND367(x, y, unit739); } function DIVIDEDECIMAL852(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return x.MUL509(unit739).DIV140(y); } function _DIVIDEDECIMALROUND630( //inject NONSTANDARD NAMING uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.MUL509(precisionUnit * 10).DIV140(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } function DIVIDEDECIMALROUND74(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return _DIVIDEDECIMALROUND630(x, y, unit739); } function DIVIDEDECIMALROUNDPRECISE587(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return _DIVIDEDECIMALROUND630(x, y, precise_unit766); } function DECIMALTOPRECISEDECIMAL237(uint i) internal pure returns (uint) { //inject NONSTANDARD NAMING return i.MUL509(unit_to_high_precision_conversion_factor241); } function PRECISEDECIMALTODECIMAL159(uint i) internal pure returns (uint) { //inject NONSTANDARD NAMING uint quotientTimesTen = i / (unit_to_high_precision_conversion_factor241 / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } interface ILinearStaking { function STAKING189(uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function CANCELSTAKING166(uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function CLAIM668() external returns (bool); //inject NONSTANDARD NAMING function STAKINGBALANCEOF960(address account) external view returns(uint256); //inject NONSTANDARD NAMING } contract LnLinearStakingStorage is LnAdmin { using SafeMath for uint256; LnAccessControl public accessCtrl; bytes32 public constant data_access_role516 = "LinearStakingStorage"; //inject NONSTANDARD NAMING struct StakingData { uint256 amount; uint256 staketime; } mapping (address => StakingData[]) public stakesdata; mapping (uint256 => uint256) public weeksTotal; // week staking amount uint256 public stakingStartTime = 1600329600; // TODO: UTC or UTC+8 uint256 public stakingEndTime = 1605168000; uint256 public totalWeekNumber = 8; uint256 public weekRewardAmount = 18750000e18; constructor(address _admin, address _accessCtrl) public LnAdmin(_admin) { accessCtrl = LnAccessControl(_accessCtrl); } modifier ONLYLINEARSTAKINGSTORAGEROLE421(address _address) { //inject NONSTANDARD NAMING require(accessCtrl.HASROLE566(data_access_role516, _address), "Only Linear Staking Storage Role"); _; } function SETACCESSCONTROL240(address _accessCtrl) external ONLYADMIN30 { //inject NONSTANDARD NAMING accessCtrl = LnAccessControl(_accessCtrl); } function WEEKTOTALSTAKING870() public view returns (uint256[] memory) { //inject NONSTANDARD NAMING uint256[] memory totals = new uint256[](totalWeekNumber); for (uint256 i=0; i< totalWeekNumber; i++) { uint256 delta = weeksTotal[i]; if (i == 0) { totals[i] = delta; } else { totals[i] = totals[i-1].ADD955(delta); } } return totals; } function GETSTAKESDATALENGTH308(address account) external view returns(uint256) { //inject NONSTANDARD NAMING return stakesdata[account].length; } function GETSTAKESDATABYINDEX845(address account, uint256 index) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (stakesdata[account][index].amount, stakesdata[account][index].staketime); } function STAKINGBALANCEOF960(address account) external view returns(uint256) { //inject NONSTANDARD NAMING uint256 total = 0; StakingData[] memory stakes = stakesdata[account]; for (uint256 i=0; i < stakes.length; i++) { total = total.ADD955(stakes[i].amount); } return total; } function REQUIREINSTAKINGPERIOD293() external view { //inject NONSTANDARD NAMING require(stakingStartTime < block.timestamp, "Staking not start"); require(block.timestamp < stakingEndTime, "Staking stage has end."); } function REQUIRESTAKINGEND294() external view { //inject NONSTANDARD NAMING require(block.timestamp > stakingEndTime, "Need wait to staking end"); } function PUSHSTAKINGDATA192(address account, uint256 amount, uint256 staketime) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING LnLinearStakingStorage.StakingData memory data = LnLinearStakingStorage.StakingData({ amount: amount, staketime: staketime }); stakesdata[account].push(data); } function STAKINGDATAADD553(address account, uint256 index, uint256 amount) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING stakesdata[account][index].amount = stakesdata[account][index].amount.ADD955(amount); } function STAKINGDATASUB735(address account, uint256 index, uint256 amount) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING stakesdata[account][index].amount = stakesdata[account][index].amount.SUB444(amount, "StakingDataSub sub overflow"); } function DELETESTAKESDATA62(address account) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING delete stakesdata[account]; } function POPSTAKESDATA423(address account) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING stakesdata[account].pop(); } function ADDWEEKSTOTAL472(uint256 staketime, uint256 amount) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING uint256 weekNumber = staketime.SUB444(stakingStartTime, "AddWeeksTotal sub overflow") / 1 weeks; weeksTotal[weekNumber] = weeksTotal[weekNumber].ADD955(amount); } function SUBWEEKSTOTAL597(uint256 staketime, uint256 amount) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING uint256 weekNumber = staketime.SUB444(stakingStartTime, "SubWeeksTotal weekNumber sub overflow") / 1 weeks; weeksTotal[weekNumber] = weeksTotal[weekNumber].SUB444(amount, "SubWeeksTotal weeksTotal sub overflow"); } function SETWEEKREWARDAMOUNT481(uint256 _weekRewardAmount) external ONLYADMIN30 { //inject NONSTANDARD NAMING weekRewardAmount = _weekRewardAmount; } function SETSTAKINGPERIOD256(uint _stakingStartTime, uint _stakingEndTime) external ONLYADMIN30 { //inject NONSTANDARD NAMING require(_stakingEndTime > _stakingStartTime); stakingStartTime = _stakingStartTime; stakingEndTime = _stakingEndTime; totalWeekNumber = stakingEndTime.SUB444(stakingStartTime, "setStakingPeriod totalWeekNumber sub overflow") / 1 weeks; if (stakingEndTime.SUB444(stakingStartTime, "setStakingPeriod stakingEndTime sub overflow") % 1 weeks != 0) { totalWeekNumber = totalWeekNumber.ADD955(1); } } } contract LnLinearStaking is LnAdmin, Pausable, ILinearStaking { using SafeMath for uint256; IERC20 public linaToken; // lina token proxy address LnLinearStakingStorage public stakingStorage; constructor( address _admin, address _linaToken, address _storage ) public LnAdmin(_admin) { linaToken = IERC20(_linaToken); stakingStorage = LnLinearStakingStorage(_storage); } function SETLINATOKEN908(address _linaToken) external ONLYADMIN30 { //inject NONSTANDARD NAMING linaToken = IERC20(_linaToken); } function SETPAUSED644(bool _paused) external ONLYADMIN30 { //inject NONSTANDARD NAMING if (_paused) { _PAUSE21(); } else { _UNPAUSE943(); } } event STAKING625(address indexed who, uint256 value, uint staketime); //inject NONSTANDARD NAMING event CANCELSTAKING945(address indexed who, uint256 value); //inject NONSTANDARD NAMING event CLAIM827(address indexed who, uint256 rewardval, uint256 totalStaking); //inject NONSTANDARD NAMING uint256 public accountStakingListLimit = 50; uint256 public minStakingAmount = 1e18; // 1 token uint256 public constant precision_uint99 = 1e23; //inject NONSTANDARD NAMING function SETLINATOKENADDRESS568(address _token) external ONLYADMIN30 { //inject NONSTANDARD NAMING linaToken = IERC20(_token); } function SETSTAKINGLISTLIMIT246(uint256 _limit) external ONLYADMIN30 { //inject NONSTANDARD NAMING accountStakingListLimit = _limit; } function SETMINSTAKINGAMOUNT66(uint256 _minStakingAmount) external ONLYADMIN30 { //inject NONSTANDARD NAMING minStakingAmount = _minStakingAmount; } function STAKINGBALANCEOF960(address account) external override view returns(uint256) { //inject NONSTANDARD NAMING return stakingStorage.STAKINGBALANCEOF960(account); } function GETSTAKESDATALENGTH308(address account) external view returns(uint256) { //inject NONSTANDARD NAMING return stakingStorage.GETSTAKESDATALENGTH308(account); } //-------------------------------------------------------- function STAKING189(uint256 amount) public WHENNOTPAUSED156 override returns (bool) { //inject NONSTANDARD NAMING stakingStorage.REQUIREINSTAKINGPERIOD293(); require(amount >= minStakingAmount, "Staking amount too small."); require(stakingStorage.GETSTAKESDATALENGTH308(msg.sender) < accountStakingListLimit, "Staking list out of limit."); //linaToken.burn(msg.sender, amount); linaToken.TRANSFERFROM500(msg.sender, address(this), amount); stakingStorage.PUSHSTAKINGDATA192(msg.sender, amount, block.timestamp); stakingStorage.ADDWEEKSTOTAL472(block.timestamp, amount); emit STAKING625(msg.sender, amount, block.timestamp); return true; } function CANCELSTAKING166(uint256 amount) public WHENNOTPAUSED156 override returns (bool) { //inject NONSTANDARD NAMING stakingStorage.REQUIREINSTAKINGPERIOD293(); require(amount > 0, "Invalid amount."); uint256 returnToken = amount; for (uint256 i = stakingStorage.GETSTAKESDATALENGTH308(msg.sender); i >= 1 ; i--) { (uint256 stakingAmount, uint256 staketime) = stakingStorage.GETSTAKESDATABYINDEX845(msg.sender, i-1); if (amount >= stakingAmount) { amount = amount.SUB444(stakingAmount, "cancelStaking sub overflow"); stakingStorage.POPSTAKESDATA423(msg.sender); stakingStorage.SUBWEEKSTOTAL597(staketime, stakingAmount); } else { stakingStorage.STAKINGDATASUB735(msg.sender, i-1, amount); stakingStorage.SUBWEEKSTOTAL597(staketime, amount); amount = 0; } if (amount == 0) break; } require(amount == 0, "Cancel amount too big then staked."); //linaToken.mint(msg.sender, returnToken); linaToken.TRANSFER72(msg.sender, returnToken); emit CANCELSTAKING945(msg.sender, returnToken); return true; } // claim reward // Note: 111111111token111 function CLAIM668() public WHENNOTPAUSED156 override returns (bool) { //inject NONSTANDARD NAMING stakingStorage.REQUIRESTAKINGEND294(); require(stakingStorage.GETSTAKESDATALENGTH308(msg.sender) > 0, "Nothing to claim"); uint256 totalWeekNumber = stakingStorage.totalWeekNumber(); uint256 totalStaking = 0; uint256 totalReward = 0; uint256[] memory finalTotals = stakingStorage.WEEKTOTALSTAKING870(); for (uint256 i=0; i < stakingStorage.GETSTAKESDATALENGTH308(msg.sender); i++) { (uint256 stakingAmount, uint256 staketime) = stakingStorage.GETSTAKESDATABYINDEX845(msg.sender, i); uint256 stakedWeedNumber = staketime.SUB444(stakingStorage.stakingStartTime(), "claim sub overflow") / 1 weeks; totalStaking = totalStaking.ADD955(stakingAmount); uint256 reward = 0; for (uint256 j=stakedWeedNumber; j < totalWeekNumber; j++) { reward = reward.ADD955( stakingAmount.MUL509(precision_uint99).DIV140(finalTotals[j]) ); //move .mul(weekRewardAmount) to next line. } reward = reward.MUL509(stakingStorage.weekRewardAmount()).DIV140(precision_uint99); totalReward = totalReward.ADD955( reward ); } stakingStorage.DELETESTAKESDATA62(msg.sender); //linaToken.mint(msg.sender, totalStaking.add(totalReward) ); linaToken.TRANSFER72(msg.sender, totalStaking.ADD955(totalReward) ); emit CLAIM827(msg.sender, totalReward, totalStaking); return true; } } // example: //LnAccessControl accessCtrl = LnAccessControl(addressStorage.getAddress("LnAccessControl")); //require(accessCtrl.hasRole(accessCtrl.DEBT_SYSTEM(), _address), "Need debt system access role"); // contract access control contract LnAccessControl is AccessControl { using Address for address; // ------------------------------------------------------- // role type bytes32 public constant issue_asset_role354 = ("ISSUE_ASSET"); //keccak256 //inject NONSTANDARD NAMING bytes32 public constant burn_asset_role864 = ("BURN_ASSET"); //inject NONSTANDARD NAMING bytes32 public constant debt_system916 = ("LnDebtSystem"); //inject NONSTANDARD NAMING // ------------------------------------------------------- constructor(address admin) public { _SETUPROLE604(default_admin_role643, admin); } function ISADMIN537(address _address) public view returns (bool) { //inject NONSTANDARD NAMING return HASROLE566(default_admin_role643, _address); } function SETADMIN420(address _address) public returns (bool) { //inject NONSTANDARD NAMING require(ISADMIN537(msg.sender), "Only admin"); _SETUPROLE604(default_admin_role643, _address); } // ------------------------------------------------------- // this func need admin role. grantRole and revokeRole need admin role function SETROLES11(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) external { //inject NONSTANDARD NAMING require(ISADMIN537(msg.sender), "Only admin"); _SETROLES348(roleType, addresses, setTo); } function _SETROLES348(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) private { //inject NONSTANDARD NAMING require(addresses.length == setTo.length, "parameter address length not eq"); for (uint256 i=0; i < addresses.length; i++) { //require(addresses[i].isContract(), "Role address need contract only"); if (setTo[i]) { GRANTROLE448(roleType, addresses[i]); } else { REVOKEROLE161(roleType, addresses[i]); } } } // function SetRoles(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) public { // _setRoles(roleType, addresses, setTo); // } // Issue burn function SETISSUEASSETROLE734(address[] calldata issuer, bool[] calldata setTo) public { //inject NONSTANDARD NAMING _SETROLES348(issue_asset_role354, issuer, setTo); } function SETBURNASSETROLE582(address[] calldata burner, bool[] calldata setTo) public { //inject NONSTANDARD NAMING _SETROLES348(burn_asset_role864, burner, setTo); } // function SETDEBTSYSTEMROLE518(address[] calldata _address, bool[] calldata _setTo) public { //inject NONSTANDARD NAMING _SETROLES348(debt_system916, _address, _setTo); } } abstract contract LnOperatorModifier is LnAdmin { address public operator; constructor(address _operator) internal { require(admin != address(0), "admin must be set"); operator = _operator; emit OPERATORUPDATED731(_operator); } function SETOPERATOR821(address _opperator) external ONLYADMIN30 { //inject NONSTANDARD NAMING operator = _opperator; emit OPERATORUPDATED731(_opperator); } modifier ONLYOPERATOR997() { //inject NONSTANDARD NAMING require(msg.sender == operator, "Only operator can perform this action"); _; } event OPERATORUPDATED731(address operator); //inject NONSTANDARD NAMING } contract LnRewardCalculator { using SafeMath for uint256; struct UserInfo { uint256 reward; uint256 amount; uint256 rewardDebt; } struct PoolInfo { uint256 amount; uint256 lastRewardBlock; uint256 accRewardPerShare; } uint256 public rewardPerBlock; PoolInfo public mPoolInfo; mapping(address => UserInfo) public userInfo; uint256 public startBlock; uint256 public remainReward; uint256 public accReward; constructor(uint256 _rewardPerBlock, uint256 _startBlock) public { rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; mPoolInfo.lastRewardBlock = startBlock; } function _CALCREWARD319(uint256 curBlock, address _user) //inject NONSTANDARD NAMING internal view returns (uint256) { PoolInfo storage pool = mPoolInfo; UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 lpSupply = pool.amount; if (curBlock > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = curBlock.SUB444( pool.lastRewardBlock, "cr curBlock sub overflow" ); uint256 curReward = multiplier.MUL509(rewardPerBlock); accRewardPerShare = accRewardPerShare.ADD955( curReward.MUL509(1e20).DIV140(lpSupply) ); } uint256 newReward = user.amount.MUL509(accRewardPerShare).DIV140(1e20).SUB444( user.rewardDebt, "cr newReward sub overflow" ); return newReward.ADD955(user.reward); } function REWARDOF391(address _user) public view returns (uint256) { //inject NONSTANDARD NAMING return userInfo[_user].reward; } function AMOUNT622() public view returns (uint256) { //inject NONSTANDARD NAMING return mPoolInfo.amount; } function AMOUNTOF525(address _user) public view returns (uint256) { //inject NONSTANDARD NAMING return userInfo[_user].amount; } function GETUSERINFO565(address _user) //inject NONSTANDARD NAMING public view returns ( uint256, uint256, uint256 ) { return ( userInfo[_user].reward, userInfo[_user].amount, userInfo[_user].rewardDebt ); } function GETPOOLINFO789() //inject NONSTANDARD NAMING public view returns ( uint256, uint256, uint256 ) { return ( mPoolInfo.amount, mPoolInfo.lastRewardBlock, mPoolInfo.accRewardPerShare ); } function _UPDATE589(uint256 curBlock) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = mPoolInfo; if (curBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.amount; if (lpSupply == 0) { pool.lastRewardBlock = curBlock; return; } uint256 multiplier = curBlock.SUB444( pool.lastRewardBlock, "_update curBlock sub overflow" ); uint256 curReward = multiplier.MUL509(rewardPerBlock); remainReward = remainReward.ADD955(curReward); accReward = accReward.ADD955(curReward); pool.accRewardPerShare = pool.accRewardPerShare.ADD955( curReward.MUL509(1e20).DIV140(lpSupply) ); pool.lastRewardBlock = curBlock; } function _DEPOSIT6( //inject NONSTANDARD NAMING uint256 curBlock, address _addr, uint256 _amount ) internal { PoolInfo storage pool = mPoolInfo; UserInfo storage user = userInfo[_addr]; _UPDATE589(curBlock); if (user.amount > 0) { uint256 pending = user .amount .MUL509(pool.accRewardPerShare) .DIV140(1e20) .SUB444(user.rewardDebt, "_deposit pending sub overflow"); if (pending > 0) { REWARD327(user, pending); } } if (_amount > 0) { user.amount = user.amount.ADD955(_amount); pool.amount = pool.amount.ADD955(_amount); } user.rewardDebt = user.amount.MUL509(pool.accRewardPerShare).DIV140(1e20); } function _WITHDRAW71( //inject NONSTANDARD NAMING uint256 curBlock, address _addr, uint256 _amount ) internal { PoolInfo storage pool = mPoolInfo; UserInfo storage user = userInfo[_addr]; require(user.amount >= _amount, "_withdraw: not good"); _UPDATE589(curBlock); uint256 pending = user.amount.MUL509(pool.accRewardPerShare).DIV140(1e20).SUB444( user.rewardDebt, "_withdraw pending sub overflow" ); if (pending > 0) { REWARD327(user, pending); } if (_amount > 0) { user.amount = user.amount.SUB444( _amount, "_withdraw user.amount sub overflow" ); pool.amount = pool.amount.SUB444( _amount, "_withdraw pool.amount sub overflow" ); } user.rewardDebt = user.amount.MUL509(pool.accRewardPerShare).DIV140(1e20); } function REWARD327(UserInfo storage user, uint256 _amount) internal { //inject NONSTANDARD NAMING if (_amount > remainReward) { _amount = remainReward; } remainReward = remainReward.SUB444( _amount, "reward remainReward sub overflow" ); user.reward = user.reward.ADD955(_amount); } function _CLAIM850(address _addr) internal { //inject NONSTANDARD NAMING UserInfo storage user = userInfo[_addr]; if (user.reward > 0) { user.reward = 0; } } } contract LnRewardCalculatorTest is LnRewardCalculator { constructor(uint256 _rewardPerBlock, uint256 _startBlock) public LnRewardCalculator(_rewardPerBlock, _startBlock) {} function DEPOSIT888( //inject NONSTANDARD NAMING uint256 curBlock, address _addr, uint256 _amount ) public { _DEPOSIT6(curBlock, _addr, _amount); } function WITHDRAW713( //inject NONSTANDARD NAMING uint256 curBlock, address _addr, uint256 _amount ) public { _WITHDRAW71(curBlock, _addr, _amount); } function CALCREWARD808(uint256 curBlock, address _user) //inject NONSTANDARD NAMING public view returns (uint256) { return _CALCREWARD319(curBlock, _user); } } contract LnSimpleStaking is LnAdmin, Pausable, ILinearStaking, LnRewardCalculator { using SafeMath for uint256; using SafeDecimalMath for uint256; IERC20 public linaToken; // lina token proxy address LnLinearStakingStorage public stakingStorage; uint256 public mEndBlock; address public mOldStaking; uint256 public mOldAmount; uint256 public mWidthdrawRewardFromOldStaking; uint256 public claimRewardLockTime = 1620806400; // 2021-5-12 address public mTargetAddress; uint256 public mTransLockTime; mapping(address => uint256) public mOldReward; constructor( address _admin, address _linaToken, address _storage, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) public LnAdmin(_admin) LnRewardCalculator(_rewardPerBlock, _startBlock) { linaToken = IERC20(_linaToken); stakingStorage = LnLinearStakingStorage(_storage); mEndBlock = _endBlock; } function SETLINATOKEN908(address _linaToken) external ONLYADMIN30 { //inject NONSTANDARD NAMING linaToken = IERC20(_linaToken); } function SETPAUSED644(bool _paused) external ONLYADMIN30 { //inject NONSTANDARD NAMING if (_paused) { _PAUSE21(); } else { _UNPAUSE943(); } } event STAKING625(address indexed who, uint256 value, uint256 staketime); //inject NONSTANDARD NAMING event CANCELSTAKING945(address indexed who, uint256 value); //inject NONSTANDARD NAMING event CLAIM827(address indexed who, uint256 rewardval, uint256 totalStaking); //inject NONSTANDARD NAMING event TRANSLOCK726(address target, uint256 time); //inject NONSTANDARD NAMING uint256 public accountStakingListLimit = 50; uint256 public minStakingAmount = 1e18; // 1 token uint256 public constant precision_uint99 = 1e23; //inject NONSTANDARD NAMING function SETSTAKINGLISTLIMIT246(uint256 _limit) external ONLYADMIN30 { //inject NONSTANDARD NAMING accountStakingListLimit = _limit; } function SETMINSTAKINGAMOUNT66(uint256 _minStakingAmount) external ONLYADMIN30 { //inject NONSTANDARD NAMING minStakingAmount = _minStakingAmount; } function STAKINGBALANCEOF960(address account) //inject NONSTANDARD NAMING external override view returns (uint256) { uint256 stakingBalance = super.AMOUNTOF525(account).ADD955( stakingStorage.STAKINGBALANCEOF960(account) ); return stakingBalance; } function GETSTAKESDATALENGTH308(address account) //inject NONSTANDARD NAMING external view returns (uint256) { return stakingStorage.GETSTAKESDATALENGTH308(account); } //-------------------------------------------------------- function MIGRATIONSOLDSTAKING766( //inject NONSTANDARD NAMING address contractAddr, uint256 amount, uint256 blockNb ) public ONLYADMIN30 { super._DEPOSIT6(blockNb, contractAddr, amount); mOldStaking = contractAddr; mOldAmount = amount; } function STAKING189(uint256 amount) //inject NONSTANDARD NAMING public override WHENNOTPAUSED156 returns (bool) { stakingStorage.REQUIREINSTAKINGPERIOD293(); require(amount >= minStakingAmount, "Staking amount too small."); //require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit."); linaToken.TRANSFERFROM500(msg.sender, address(this), amount); uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } super._DEPOSIT6(blockNb, msg.sender, amount); emit STAKING625(msg.sender, amount, block.timestamp); return true; } function _WIDTHDRAWFROMOLDSTAKING790(address _addr, uint256 amount) internal { //inject NONSTANDARD NAMING uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } uint256 oldStakingAmount = super.AMOUNTOF525(mOldStaking); super._WITHDRAW71(blockNb, mOldStaking, amount); // sub already withraw reward, then cal portion uint256 reward = super .REWARDOF391(mOldStaking) .SUB444( mWidthdrawRewardFromOldStaking, "_widthdrawFromOldStaking reward sub overflow" ) .MUL509(amount) .MUL509(1e20) .DIV140(oldStakingAmount) .DIV140(1e20); mWidthdrawRewardFromOldStaking = mWidthdrawRewardFromOldStaking.ADD955( reward ); mOldReward[_addr] = mOldReward[_addr].ADD955(reward); } function _CANCELSTAKING147(address user, uint256 amount) internal { //inject NONSTANDARD NAMING uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } uint256 returnAmount = amount; uint256 newAmount = super.AMOUNTOF525(user); if (newAmount >= amount) { super._WITHDRAW71(blockNb, user, amount); amount = 0; } else { if (newAmount > 0) { super._WITHDRAW71(blockNb, user, newAmount); amount = amount.SUB444( newAmount, "_cancelStaking amount sub overflow" ); } for ( uint256 i = stakingStorage.GETSTAKESDATALENGTH308(user); i >= 1; i-- ) { (uint256 stakingAmount, uint256 staketime) = stakingStorage .GETSTAKESDATABYINDEX845(user, i - 1); if (amount >= stakingAmount) { amount = amount.SUB444( stakingAmount, "_cancelStaking amount sub overflow" ); stakingStorage.POPSTAKESDATA423(user); stakingStorage.SUBWEEKSTOTAL597(staketime, stakingAmount); _WIDTHDRAWFROMOLDSTAKING790(user, stakingAmount); } else { stakingStorage.STAKINGDATASUB735(user, i - 1, amount); stakingStorage.SUBWEEKSTOTAL597(staketime, amount); _WIDTHDRAWFROMOLDSTAKING790(user, amount); amount = 0; } if (amount == 0) break; } } // cancel as many as possible, not fail, that waste gas //require(amount == 0, "Cancel amount too big then staked."); linaToken.TRANSFER72(msg.sender, returnAmount.SUB444(amount)); } function CANCELSTAKING166(uint256 amount) //inject NONSTANDARD NAMING public override WHENNOTPAUSED156 returns (bool) { //stakingStorage.requireInStakingPeriod(); require(amount > 0, "Invalid amount."); _CANCELSTAKING147(msg.sender, amount); emit CANCELSTAKING945(msg.sender, amount); return true; } function GETTOTALREWARD238(uint256 blockNb, address _user) //inject NONSTANDARD NAMING public view returns (uint256 total) { if (blockNb > mEndBlock) { blockNb = mEndBlock; } // 1111111111 // 1,1111111cancel11 // 2,1111111 // 31111111 total = mOldReward[_user]; uint256 iMyOldStaking = 0; for ( uint256 i = 0; i < stakingStorage.GETSTAKESDATALENGTH308(_user); i++ ) { (uint256 stakingAmount, ) = stakingStorage.GETSTAKESDATABYINDEX845( _user, i ); iMyOldStaking = iMyOldStaking.ADD955(stakingAmount); } if (iMyOldStaking > 0) { uint256 oldStakingAmount = super.AMOUNTOF525(mOldStaking); uint256 iReward2 = super ._CALCREWARD319(blockNb, mOldStaking) .SUB444( mWidthdrawRewardFromOldStaking, "getTotalReward iReward2 sub overflow" ) .MUL509(iMyOldStaking) .DIV140(oldStakingAmount); total = total.ADD955(iReward2); } uint256 reward3 = super._CALCREWARD319(blockNb, _user); total = total.ADD955(reward3); } // claim reward // Note: 111111111token111 function CLAIM668() public override WHENNOTPAUSED156 returns (bool) { //inject NONSTANDARD NAMING //stakingStorage.requireStakingEnd(); require( block.timestamp > claimRewardLockTime, "Not time to claim reward" ); uint256 iMyOldStaking = stakingStorage.STAKINGBALANCEOF960(msg.sender); uint256 iAmount = super.AMOUNTOF525(msg.sender); _CANCELSTAKING147(msg.sender, iMyOldStaking.ADD955(iAmount)); uint256 iReward = GETTOTALREWARD238(mEndBlock, msg.sender); _CLAIM850(msg.sender); mOldReward[msg.sender] = 0; linaToken.TRANSFER72(msg.sender, iReward); emit CLAIM827(msg.sender, iReward, iMyOldStaking.ADD955(iAmount)); return true; } function SETREWARDLOCKTIME580(uint256 newtime) public ONLYADMIN30 { //inject NONSTANDARD NAMING claimRewardLockTime = newtime; } function CALCREWARD808(uint256 curBlock, address _user) //inject NONSTANDARD NAMING public view returns (uint256) { return _CALCREWARD319(curBlock, _user); } function SETTRANSLOCK553(address target, uint256 locktime) public ONLYADMIN30 { //inject NONSTANDARD NAMING require( locktime >= now + 2 days, "locktime need larger than cur time 2 days" ); mTargetAddress = target; mTransLockTime = locktime; emit TRANSLOCK726(mTargetAddress, mTransLockTime); } function TRANSTOKENS575(uint256 amount) public ONLYADMIN30 { //inject NONSTANDARD NAMING require(mTransLockTime > 0, "mTransLockTime not set"); require(now > mTransLockTime, "Pls wait to unlock time"); linaToken.TRANSFER72(mTargetAddress, amount); } } contract HelperPushStakingData is LnAdmin { constructor(address _admin) public LnAdmin(_admin) {} function PUSHSTAKINGDATA192( //inject NONSTANDARD NAMING address _storage, address[] calldata account, uint256[] calldata amount, uint256[] calldata staketime ) external { require(account.length > 0, "array length zero"); require(account.length == amount.length, "array length not eq"); require(account.length == staketime.length, "array length not eq"); LnLinearStakingStorage stakingStorage = LnLinearStakingStorage( _storage ); for (uint256 i = 0; i < account.length; i++) { stakingStorage.PUSHSTAKINGDATA192(account[i], amount[i], staketime[i]); stakingStorage.ADDWEEKSTOTAL472(staketime[i], amount[i]); } } //unstaking. } contract MultiSigForTransferFunds { mapping(address => uint256) public mAdmins; uint256 public mConfirmNumb; uint256 public mProposalNumb; uint256 public mAmount; LnSimpleStaking public mStaking; address[] public mAdminArr; uint256 public mTransLockTime; constructor( address[] memory _addr, uint256 iConfirmNumb, LnSimpleStaking _staking ) public { for (uint256 i = 0; i < _addr.length; ++i) { mAdmins[_addr[i]] = 1; } mConfirmNumb = iConfirmNumb; mProposalNumb = 0; mStaking = _staking; mAdminArr = _addr; } function BECOMEADMIN406(address target) external { //inject NONSTANDARD NAMING LnAdmin(target).BECOMEADMIN406(); } function SETTRANSLOCK553( //inject NONSTANDARD NAMING address target, uint256 locktime, uint256 amount ) public { require(mAdmins[msg.sender] == 1, "not in admin list or set state"); _RESET370(); mStaking.SETTRANSLOCK553(target, locktime); mAmount = amount; mProposalNumb = 1; mAdmins[msg.sender] = 2; // mTransLockTime = locktime; } // call this when the locktime expired function CONFIRMTRANSFER169() public { //inject NONSTANDARD NAMING require(mAdmins[msg.sender] == 1, "not in admin list or set state"); mProposalNumb = mProposalNumb + 1; mAdmins[msg.sender] = 2; } function DOTRANSFER874() public { //inject NONSTANDARD NAMING require(mTransLockTime > 0, "mTransLockTime not set"); require(now > mTransLockTime, "Pls wait to unlock time"); require(mProposalNumb >= mConfirmNumb, "need more confirm"); _RESET370(); mStaking.TRANSTOKENS575(mAmount); } function _RESET370() internal { //inject NONSTANDARD NAMING mProposalNumb = 0; mTransLockTime = 0; // reset for (uint256 i = 0; i < mAdminArr.length; ++i) { mAdmins[mAdminArr[i]] = 1; } } } contract LnSimpleStakingExtension is LnAdmin, Pausable, ILinearStaking, LnRewardCalculator { using SafeMath for uint256; using SafeDecimalMath for uint256; IERC20 public linaToken; // lina token proxy address LnLinearStakingStorage public stakingStorage; uint256 public mEndBlock; address public mOldStaking; uint256 public mOldAmount; uint256 public mWidthdrawRewardFromOldStaking; uint256 public claimRewardLockTime = 1620806400; // 2021-5-12 address public mTargetAddress; uint256 public mTransLockTime; LnSimpleStaking public mOldSimpleStaking; bool public requireSync = false; mapping(address => uint256) public mOldReward; mapping(address => bool) public syncUserInfo; constructor( address _admin, address _linaToken, address _storage, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock, address _mOldSimpleStaking ) public LnAdmin(_admin) LnRewardCalculator(_rewardPerBlock, _startBlock) { linaToken = IERC20(_linaToken); stakingStorage = LnLinearStakingStorage(_storage); mEndBlock = _endBlock; if (_mOldSimpleStaking != address(0)) { mOldSimpleStaking = LnSimpleStaking(_mOldSimpleStaking); ( mPoolInfo.amount, , mPoolInfo.accRewardPerShare ) = mOldSimpleStaking.GETPOOLINFO789(); requireSync = true; } } function SETLINATOKEN908(address _linaToken) external ONLYADMIN30 { //inject NONSTANDARD NAMING linaToken = IERC20(_linaToken); } function SETPAUSED644(bool _paused) external ONLYADMIN30 { //inject NONSTANDARD NAMING if (_paused) { _PAUSE21(); } else { _UNPAUSE943(); } } event STAKING625(address indexed who, uint256 value, uint256 staketime); //inject NONSTANDARD NAMING event CANCELSTAKING945(address indexed who, uint256 value); //inject NONSTANDARD NAMING event CLAIM827(address indexed who, uint256 rewardval, uint256 totalStaking); //inject NONSTANDARD NAMING event TRANSLOCK726(address target, uint256 time); //inject NONSTANDARD NAMING uint256 public accountStakingListLimit = 50; uint256 public minStakingAmount = 1e18; // 1 token uint256 public constant precision_uint99 = 1e23; //inject NONSTANDARD NAMING function SETSTAKINGLISTLIMIT246(uint256 _limit) external ONLYADMIN30 { //inject NONSTANDARD NAMING accountStakingListLimit = _limit; } function SETMINSTAKINGAMOUNT66(uint256 _minStakingAmount) external ONLYADMIN30 { //inject NONSTANDARD NAMING minStakingAmount = _minStakingAmount; } function STAKINGBALANCEOF960(address account) //inject NONSTANDARD NAMING external override view returns (uint256) { uint256 stakingBalance = super.AMOUNTOF525(account).ADD955( stakingStorage.STAKINGBALANCEOF960(account) ); return stakingBalance; } function GETSTAKESDATALENGTH308(address account) //inject NONSTANDARD NAMING external view returns (uint256) { return stakingStorage.GETSTAKESDATALENGTH308(account); } function SETENDBLOCK987(uint256 _newEndBlock) external ONLYADMIN30 { //inject NONSTANDARD NAMING require( _newEndBlock > mEndBlock, "new endBlock less than old endBlock." ); mEndBlock = _newEndBlock; } // function isUserSynced(address _user) internal view returns (bool) { // bool status; // if (!requireSync) { // status = true; // } else { // status = syncUserInfo[_user]; // } // return status; // } function SYNCUSERINFODATA21(address _user) internal { //inject NONSTANDARD NAMING if (requireSync && !syncUserInfo[_user]) { ( userInfo[_user].reward, userInfo[_user].amount, userInfo[_user].rewardDebt ) = mOldSimpleStaking.GETUSERINFO565(_user); syncUserInfo[_user] = true; } } //-------------------------------------------------------- function MIGRATIONSOLDSTAKING766( //inject NONSTANDARD NAMING address contractAddr, uint256 amount, uint256 blockNb ) public ONLYADMIN30 { super._DEPOSIT6(blockNb, contractAddr, amount); mOldStaking = contractAddr; mOldAmount = amount; } function STAKING189(uint256 amount) //inject NONSTANDARD NAMING public override WHENNOTPAUSED156 returns (bool) { // stakingStorage.requireInStakingPeriod(); // require( // syncUserInfo[msg.sender], // "sync is required before perform action." // ); if (!syncUserInfo[msg.sender]) { SYNCUSERINFODATA21(msg.sender); } require(amount >= minStakingAmount, "Staking amount too small."); //require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit."); linaToken.TRANSFERFROM500(msg.sender, address(this), amount); uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } super._DEPOSIT6(blockNb, msg.sender, amount); emit STAKING625(msg.sender, amount, block.timestamp); return true; } function _WIDTHDRAWFROMOLDSTAKING790(address _addr, uint256 amount) internal { //inject NONSTANDARD NAMING uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } uint256 oldStakingAmount = super.AMOUNTOF525(mOldStaking); super._WITHDRAW71(blockNb, mOldStaking, amount); // sub already withraw reward, then cal portion uint256 reward = super .REWARDOF391(mOldStaking) .SUB444( mWidthdrawRewardFromOldStaking, "_widthdrawFromOldStaking reward sub overflow" ) .MUL509(amount) .MUL509(1e20) .DIV140(oldStakingAmount) .DIV140(1e20); mWidthdrawRewardFromOldStaking = mWidthdrawRewardFromOldStaking.ADD955( reward ); mOldReward[_addr] = mOldReward[_addr].ADD955(reward); } function _CANCELSTAKING147(address user, uint256 amount) internal { //inject NONSTANDARD NAMING uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } uint256 returnAmount = amount; uint256 newAmount = super.AMOUNTOF525(user); if (newAmount >= amount) { super._WITHDRAW71(blockNb, user, amount); amount = 0; } else { if (newAmount > 0) { super._WITHDRAW71(blockNb, user, newAmount); amount = amount.SUB444( newAmount, "_cancelStaking amount sub overflow" ); } for ( uint256 i = stakingStorage.GETSTAKESDATALENGTH308(user); i >= 1; i-- ) { (uint256 stakingAmount, uint256 staketime) = stakingStorage .GETSTAKESDATABYINDEX845(user, i - 1); if (amount >= stakingAmount) { amount = amount.SUB444( stakingAmount, "_cancelStaking amount sub overflow" ); stakingStorage.POPSTAKESDATA423(user); stakingStorage.SUBWEEKSTOTAL597(staketime, stakingAmount); _WIDTHDRAWFROMOLDSTAKING790(user, stakingAmount); } else { stakingStorage.STAKINGDATASUB735(user, i - 1, amount); stakingStorage.SUBWEEKSTOTAL597(staketime, amount); _WIDTHDRAWFROMOLDSTAKING790(user, amount); amount = 0; } if (amount == 0) break; } } // cancel as many as possible, not fail, that waste gas //require(amount == 0, "Cancel amount too big then staked."); linaToken.TRANSFER72(msg.sender, returnAmount.SUB444(amount)); } function CANCELSTAKING166(uint256 amount) //inject NONSTANDARD NAMING public override WHENNOTPAUSED156 returns (bool) { // require( // syncUserInfo[msg.sender], // "sync is required before perform action." // ); if (!syncUserInfo[msg.sender]) { SYNCUSERINFODATA21(msg.sender); } //stakingStorage.requireInStakingPeriod(); require(amount > 0, "Invalid amount."); _CANCELSTAKING147(msg.sender, amount); emit CANCELSTAKING945(msg.sender, amount); return true; } function GETTOTALREWARD238(uint256 blockNb, address _user) //inject NONSTANDARD NAMING public view returns (uint256 total) { if (blockNb > mEndBlock) { blockNb = mEndBlock; } // 1111111111 // 1,1111111cancel11 // 2,1111111 // 31111111 total = mOldReward[_user]; // include the old simple staking amount uint256 simpleStakingReward = 0; if (!syncUserInfo[msg.sender]) { (simpleStakingReward, ,) = mOldSimpleStaking.GETUSERINFO565(_user); } total = total.ADD955(simpleStakingReward); uint256 iMyOldStaking = 0; for ( uint256 i = 0; i < stakingStorage.GETSTAKESDATALENGTH308(_user); i++ ) { (uint256 stakingAmount, ) = stakingStorage.GETSTAKESDATABYINDEX845( _user, i ); iMyOldStaking = iMyOldStaking.ADD955(stakingAmount); } if (iMyOldStaking > 0) { uint256 oldStakingAmount = super.AMOUNTOF525(mOldStaking); uint256 iReward2 = super ._CALCREWARD319(blockNb, mOldStaking) .SUB444( mWidthdrawRewardFromOldStaking, "getTotalReward iReward2 sub overflow" ) .MUL509(iMyOldStaking) .DIV140(oldStakingAmount); total = total.ADD955(iReward2); } uint256 reward3 = super._CALCREWARD319(blockNb, _user); total = total.ADD955(reward3); } // claim reward // Note: 111111111token111 function CLAIM668() public override WHENNOTPAUSED156 returns (bool) { //inject NONSTANDARD NAMING //stakingStorage.requireStakingEnd() // require( // syncUserInfo[msg.sender], // "sync is required before perform action." // ); if (!syncUserInfo[msg.sender]) { SYNCUSERINFODATA21(msg.sender); } require( block.timestamp > claimRewardLockTime, "Not time to claim reward" ); uint256 iMyOldStaking = stakingStorage.STAKINGBALANCEOF960(msg.sender); uint256 iAmount = super.AMOUNTOF525(msg.sender); _CANCELSTAKING147(msg.sender, iMyOldStaking.ADD955(iAmount)); uint256 iReward = GETTOTALREWARD238(mEndBlock, msg.sender); _CLAIM850(msg.sender); mOldReward[msg.sender] = 0; linaToken.TRANSFER72(msg.sender, iReward); emit CLAIM827(msg.sender, iReward, iMyOldStaking.ADD955(iAmount)); return true; } function SETREWARDLOCKTIME580(uint256 newtime) public ONLYADMIN30 { //inject NONSTANDARD NAMING claimRewardLockTime = newtime; } function CALCREWARD808(uint256 curBlock, address _user) //inject NONSTANDARD NAMING public view returns (uint256) { return _CALCREWARDWITHVIEWSIMPLEAMOUNT431(curBlock, _user); } // This is copied particularly for catering the amount when user not sync function _CALCREWARDWITHVIEWSIMPLEAMOUNT431(uint256 curBlock, address _user) //inject NONSTANDARD NAMING internal view returns (uint256) { PoolInfo storage pool = mPoolInfo; UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 lpSupply = pool.amount; if (curBlock > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = curBlock.SUB444( pool.lastRewardBlock, "cr curBlock sub overflow" ); uint256 curReward = multiplier.MUL509(rewardPerBlock); accRewardPerShare = accRewardPerShare.ADD955( curReward.MUL509(1e20).DIV140(lpSupply) ); } // Only logic added for old simpleStaking uint256 ssReward; uint256 ssAmount; uint256 ssRewardDebt; ( ssReward, ssAmount, ssRewardDebt ) = mOldSimpleStaking.GETUSERINFO565(_user); ssAmount = ssAmount.ADD955(user.amount); ssRewardDebt = ssRewardDebt.ADD955(user.rewardDebt); ssReward = ssReward.ADD955(user.reward); // uint256 newReward = user.amount.mul(accRewardPerShare).div(1e20).sub( uint256 newReward = ssAmount .MUL509(accRewardPerShare) .DIV140(1e20) .SUB444(ssRewardDebt, "cr newReward sub overflow"); return newReward.ADD955(ssReward); } function SETTRANSLOCK553(address target, uint256 locktime) public ONLYADMIN30 { //inject NONSTANDARD NAMING require( locktime >= now + 2 days, "locktime need larger than cur time 2 days" ); mTargetAddress = target; mTransLockTime = locktime; emit TRANSLOCK726(mTargetAddress, mTransLockTime); } function TRANSTOKENS575(uint256 amount) public ONLYADMIN30 { //inject NONSTANDARD NAMING require(mTransLockTime > 0, "mTransLockTime not set"); require(now > mTransLockTime, "Pls wait to unlock time"); linaToken.TRANSFER72(mTargetAddress, amount); } }
inject NONSTANDARD NAMING
function TRANSFER72(address to, uint value) external returns (bool);
12,739,015
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4235, 17598, 9060, 12, 2867, 358, 16, 2254, 460, 13, 3903, 1135, 261, 6430, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // file: SafeERC20 pragma solidity ^0.6.12; // NOTE: this interface lacks return values for transfer/transferFrom/approve on purpose, // as we use the SafeERC20 library to check the return value interface GeneralERC20 { function transfer(address to, uint256 amount) external; function transferFrom(address from, address to, uint256 amount) external; function approve(address spender, uint256 amount) external; function balanceOf(address spender) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); } library SafeERC20 { function checkSuccess() private pure returns (bool) { uint256 returnValue = 0; assembly { // check number of bytes returned from last function call switch returndatasize() // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: don't mark as success default { } } return returnValue != 0; } function transfer(address token, address to, uint256 amount) internal { GeneralERC20(token).transfer(to, amount); require(checkSuccess()); } function transferFrom(address token, address from, address to, uint256 amount) internal { GeneralERC20(token).transferFrom(from, to, amount); require(checkSuccess()); } function approve(address token, address spender, uint256 amount) internal { GeneralERC20(token).approve(spender, amount); require(checkSuccess()); } } // File: @openzeppelin/contracts/access/Ownable.sol; changed to remove context pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { 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 = msg.sender; _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 == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // MasterChef is now repurposed to distribute existing ADX. // // Note that it's ownable and the owner wields tremendous power. // // Have fun reading it. Hopefully it's bug-free. Амин. contract MasterChef is Ownable { using SafeMath for uint256; // 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 ADXs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accADXPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accADXPerShare` (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. ADXs to distribute per block. uint256 lastRewardBlock; // Last block number that ADXs distribution occurs. uint256 accADXPerShare; // Accumulated ADXs per share, times 1e12. See below. } // The ADX TOKEN! IERC20 public ADX; // ADX tokens distributed per block. uint256 public ADXPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when ADX mining starts. uint256 public startBlock; // Events event Recovered(address token, uint256 amount); 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( IERC20 _ADX, uint256 _ADXPerBlock, uint256 _startBlock ) public { ADX = _ADX; ADXPerBlock = _ADXPerBlock; 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. // Not in a big way, but the payout will be less than the planned payout per block cause we divide the user's deposit by the total lpToken.balanceOf(this) 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, accADXPerShare: 0 }) ); } // XXX general note on _withUpdate and why it's optional // Some have pointed out pending (unwithdrawn) rewards can be modified on the fly if `set`/`setADXPerBlock` is called // without `_withUpdate` set to true // There's a reason to keep this as an optional flag, which is to ensure it can be called in case `massUpdatePools` // is failing for whatever reason (eg runs out of gas) // In any case, those methods will be placed behind a timelock to ensure this cannot happen // Update the given pool's ADX allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { // XXX you can allocate for a nonexistant pool if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // View function to see pending ADXs on frontend. function pendingADX(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accADXPerShare = pool.accADXPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 ADXReward = block.number.sub(pool.lastRewardBlock) .mul(ADXPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accADXPerShare = accADXPerShare.add( ADXReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accADXPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 ADXReward = block.number.sub(pool.lastRewardBlock) .mul(ADXPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); // XXX The original masterchef mints here; our version expects to be pre-funded with ADX pool.accADXPerShare = pool.accADXPerShare.add( ADXReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for ADX 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.accADXPerShare) .div(1e12) .sub(user.rewardDebt); safeADXTransfer(msg.sender, pending); } SafeERC20.transferFrom( address(pool.lpToken), address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accADXPerShare).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.accADXPerShare).div(1e12).sub( user.rewardDebt ); safeADXTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accADXPerShare).div(1e12); SafeERC20.transfer(address(pool.lpToken), 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]; SafeERC20.transfer(address(pool.lpToken), address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe ADX transfer function, just in case if rounding error causes pool to not have enough ADXs. function safeADXTransfer(address _to, uint256 _amount) internal { uint256 ADXBal = ADX.balanceOf(address(this)); if (_amount > ADXBal) { require((_amount - ADXBal) < 10e17, "safeADXTransfer: rounding error too big, contract may be underfunded?"); ADX.transfer(_to, ADXBal); } else { ADX.transfer(_to, _amount); } } // AdEx-specific masterchef extensions function setADXPerBlock(uint256 _ADXPerBlock, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } ADXPerBlock = _ADXPerBlock; } }
NOTE: this interface lacks return values for transfer/transferFrom/approve on purpose, as we use the SafeERC20 library to check the return value
interface GeneralERC20 { function transfer(address to, uint256 amount) external; function transferFrom(address from, address to, uint256 amount) external; function approve(address spender, uint256 amount) external; function balanceOf(address spender) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); pragma solidity ^0.6.12; }
5,926,740
[ 1, 17857, 30, 333, 1560, 328, 22098, 327, 924, 364, 7412, 19, 13866, 1265, 19, 12908, 537, 603, 13115, 16, 487, 732, 999, 326, 14060, 654, 39, 3462, 5313, 358, 866, 326, 327, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 9544, 654, 39, 3462, 288, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 565, 445, 11013, 951, 12, 2867, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 1769, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 1769, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 2138, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; /** * @dev Interface of the OpenOracleFramework contract */ interface IOpenOracleFramework { /** * @dev initialize function lets the factory init the cloned contract and set it up * * @param signers_ array of signer addresses * @param signerThreshold_ the threshold which has to be met for consensus * @param payoutAddress_ the address where all fees will be sent to. 0 address for an even split across signers * @param subscriptionPassPrice_ the price for an oracle subscription pass * @param factoryContract_ the address of the factory contract */ function initialize( address[] memory signers_, uint256 signerThreshold_, address payable payoutAddress_, uint256 subscriptionPassPrice_, address factoryContract_ ) external; /** * @dev getHistoricalFeeds function lets the caller receive historical values for a given timestamp * * @param feedIDs the array of feedIds * @param timestamps the array of timestamps */ function getHistoricalFeeds(uint256[] memory feedIDs, uint256[] memory timestamps) external view returns (uint256[] memory); /** * @dev getFeeds function lets anyone call the oracle to receive data (maybe pay an optional fee) * * @param feedIDs the array of feedIds */ function getFeeds(uint256[] memory feedIDs) external view returns (uint256[] memory, uint256[] memory, uint256[] memory); /** * @dev getFeed function lets anyone call the oracle to receive data (maybe pay an optional fee) * * @param feedID the array of feedId */ function getFeed(uint256 feedID) external view returns (uint256, uint256, uint256); /** * @dev getFeedList function returns the metadata of a feed * * @param feedIDs the array of feedId */ function getFeedList(uint256[] memory feedIDs) external view returns(string[] memory, uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory); /** * @dev withdrawFunds function sends the collected fees to the given address */ function withdrawFunds() external; /** * @dev creates new oracle data feeds * * @param names the names of the new feeds * @param descriptions the description of the new feeds * @param decimals the decimals of the new feeds * @param timeslots the timeslots of the new feeds * @param feedCosts the costs of the new feeds * @param revenueModes the revenue modes of the new feeds */ function createNewFeeds(string[] memory names, string[] memory descriptions, uint256[] memory decimals, uint256[] memory timeslots, uint256[] memory feedCosts, uint256[] memory revenueModes) external; /** * @dev submits multiple feed values * * @param feedIDs the array of feedId * @param values the values to submit */ function submitFeed(uint256[] memory feedIDs, uint256[] memory values) external; /** * @dev signs a given proposal * * @param proposalId the id of the proposal */ function signProposal(uint256 proposalId) external; /** * @dev creates a new proposal * * @param uintValue value in uint representation * @param addressValue value in address representation * @param proposalType type of the proposal * @param feedId the feed id if needed */ function createProposal(uint256 uintValue, address addressValue, uint256 proposalType, uint256 feedId) external; /** * @dev buys a subscription to a feed * * @param feedIDs the feeds to subscribe to * @param durations the durations to subscribe * @param buyer the address which should be subscribed to the feeds */ function subscribeToFeed(uint256[] memory feedIDs, uint256[] memory durations, address buyer) payable external; /** * @dev buys a subscription pass for the oracle * * @param buyer the address which owns the pass * @param duration the duration to subscribe */ function buyPass(address buyer, uint256 duration) payable external; /** * @dev supports given Feeds * * @param feedIds the array of feeds to support * @param values the array of amounts of ETH to send to support */ function supportFeeds(uint256[] memory feedIds, uint256[] memory values) payable external; }
* @dev Interface of the OpenOracleFramework contract/
interface IOpenOracleFramework { function initialize( address[] memory signers_, uint256 signerThreshold_, address payable payoutAddress_, uint256 subscriptionPassPrice_, address factoryContract_ ) external; function getHistoricalFeeds(uint256[] memory feedIDs, uint256[] memory timestamps) external view returns (uint256[] memory); function getFeeds(uint256[] memory feedIDs) external view returns (uint256[] memory, uint256[] memory, uint256[] memory); function getFeed(uint256 feedID) external view returns (uint256, uint256, uint256); function getFeedList(uint256[] memory feedIDs) external view returns(string[] memory, uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory); function withdrawFunds() external; function createNewFeeds(string[] memory names, string[] memory descriptions, uint256[] memory decimals, uint256[] memory timeslots, uint256[] memory feedCosts, uint256[] memory revenueModes) external; function submitFeed(uint256[] memory feedIDs, uint256[] memory values) external; function signProposal(uint256 proposalId) external; function createProposal(uint256 uintValue, address addressValue, uint256 proposalType, uint256 feedId) external; function subscribeToFeed(uint256[] memory feedIDs, uint256[] memory durations, address buyer) payable external; function buyPass(address buyer, uint256 duration) payable external; function supportFeeds(uint256[] memory feedIds, uint256[] memory values) payable external; pragma solidity 0.7.6; }
12,738,012
[ 1, 1358, 434, 326, 3502, 23601, 13701, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 1665, 1907, 23601, 13701, 288, 203, 565, 445, 4046, 12, 203, 3639, 1758, 8526, 3778, 1573, 414, 67, 16, 203, 3639, 2254, 5034, 10363, 7614, 67, 16, 203, 3639, 1758, 8843, 429, 293, 2012, 1887, 67, 16, 203, 3639, 2254, 5034, 4915, 6433, 5147, 67, 16, 203, 3639, 1758, 3272, 8924, 67, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 7628, 376, 10129, 8141, 87, 12, 11890, 5034, 8526, 3778, 4746, 5103, 16, 2254, 5034, 8526, 3778, 11267, 13, 3903, 1476, 1135, 261, 11890, 5034, 8526, 3778, 1769, 203, 203, 565, 445, 13683, 9765, 12, 11890, 5034, 8526, 3778, 4746, 5103, 13, 3903, 1476, 1135, 261, 11890, 5034, 8526, 3778, 16, 2254, 5034, 8526, 3778, 16, 2254, 5034, 8526, 3778, 1769, 203, 203, 565, 445, 13683, 329, 12, 11890, 5034, 4746, 734, 13, 3903, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 1769, 203, 203, 565, 445, 13683, 18073, 12, 11890, 5034, 8526, 3778, 4746, 5103, 13, 3903, 1476, 1135, 12, 1080, 8526, 3778, 16, 2254, 5034, 8526, 3778, 16, 2254, 5034, 8526, 3778, 16, 2254, 5034, 8526, 3778, 16, 2254, 5034, 8526, 3778, 1769, 203, 203, 565, 445, 598, 9446, 42, 19156, 1435, 3903, 31, 203, 203, 565, 445, 15291, 8141, 87, 12, 1080, 8526, 3778, 1257, 16, 533, 8526, 3778, 15550, 16, 2254, 5034, 8526, 3778, 15105, 16, 2254, 5034, 8526, 3778, 4124, 80, 6968, 16, 2254, 5034, 8526, 3778, 4746, 21420, 16, 2254, 5034, 8526, 3778, 283, 24612, 18868, 13, 3903, 31, 203, 203, 565, 445, 2 ]
./partial_match/1/0x4db470795f0E82a09b2F94c15a6c7E17b3C4B978/sources/Implementation.sol
Can participate in balance-dependant activities
modifier onlyFrozenOrLocked(address account) { Require.that( statusOf(account) != Account.Status.Fluid, FILE, "Not frozen or locked" ); _; }
4,162,499
[ 1, 2568, 30891, 340, 316, 11013, 17, 5817, 970, 17259, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 1338, 42, 9808, 1162, 8966, 12, 2867, 2236, 13, 288, 203, 3639, 12981, 18, 19056, 12, 203, 5411, 1267, 951, 12, 4631, 13, 480, 6590, 18, 1482, 18, 2340, 1911, 16, 203, 5411, 7527, 16, 203, 5411, 315, 1248, 12810, 578, 8586, 6, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-01-23 */ // compiler: 0.6.6+commit.6c089d02.Emscripten.clang // evmVersion: istanbul, optimizer:{"enabled":true,"runs":200} // ContractName: BaseToken // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract 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 { } } // File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: erc-payable-token/contracts/token/ERC1363/IERC1363.sol pragma solidity ^0.6.0; /** * @title IERC1363 Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for a Payable Token contract as defined in * https://github.com/ethereum/EIPs/issues/1363 */ interface IERC1363 is IERC20, IERC165 { /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @return true unless throwing */ function transferFromAndCall(address from, address to, uint256 value) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * 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 address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * 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 address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool); } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Receiver.sol pragma solidity ^0.6.0; /** * @title IERC1363Receiver Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support transferAndCall or transferFromAndCall * from ERC1363 token contracts as defined in * https://github.com/ethereum/EIPs/issues/1363 */ interface IERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived(address operator, address from, uint256 value, bytes calldata data) external returns (bytes4); // solhint-disable-line max-line-length } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Spender.sol pragma solidity ^0.6.0; /** * @title IERC1363Spender Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support approveAndCall * from ERC1363 token contracts as defined in * https://github.com/ethereum/EIPs/issues/1363 */ interface IERC1363Spender { /* * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) */ /** * @notice Handle the approval of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after an `approve`. This function MAY throw to revert and reject the * approval. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` * unless throwing */ function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165Checker.sol pragma solidity ^0.6.2; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.6.0; /** * @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) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: erc-payable-token/contracts/token/ERC1363/ERC1363.sol pragma solidity ^0.6.0; /** * @title ERC1363 * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation of an ERC1363 interface */ contract ERC1363 is ERC20, IERC1363, ERC165 { using Address for address; /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ bytes4 internal constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df; /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ bytes4 internal constant _INTERFACE_ID_ERC1363_APPROVE = 0xfb9ec8ce; // Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` // which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector` bytes4 private constant _ERC1363_RECEIVED = 0x88a7ca5c; // Equals to `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` // which can be also obtained as `IERC1363Spender(0).onApprovalReceived.selector` bytes4 private constant _ERC1363_APPROVED = 0x7b04a2d0; constructor ( string memory name, string memory symbol ) public payable ERC20(name, symbol) { // register the supported interfaces to conform to ERC1363 via ERC165 _registerInterface(_INTERFACE_ID_ERC1363_TRANSFER); _registerInterface(_INTERFACE_ID_ERC1363_APPROVE); } function transferAndCall(address to, uint256 value) public override returns (bool) { return transferAndCall(to, value, ""); } function transferAndCall(address to, uint256 value, bytes memory data) public override returns (bool) { transfer(to, value); require(_checkAndCallTransfer(_msgSender(), to, value, data), "ERC1363: _checkAndCallTransfer reverts"); return true; } function transferFromAndCall(address from, address to, uint256 value) public override returns (bool) { return transferFromAndCall(from, to, value, ""); } function transferFromAndCall(address from, address to, uint256 value, bytes memory data) public override returns (bool) { transferFrom(from, to, value); require(_checkAndCallTransfer(from, to, value, data), "ERC1363: _checkAndCallTransfer reverts"); return true; } function approveAndCall(address spender, uint256 value) public override returns (bool) { return approveAndCall(spender, value, ""); } function approveAndCall(address spender, uint256 value, bytes memory data) public override returns (bool) { approve(spender, value); require(_checkAndCallApprove(spender, value, data), "ERC1363: _checkAndCallApprove reverts"); return true; } /** * @dev Internal function to invoke `onTransferReceived` 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 value * @param to address Target address that will receive the tokens * @param value uint256 The amount mount of tokens to be transferred * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallTransfer(address from, address to, uint256 value, bytes memory data) internal returns (bool) { if (!to.isContract()) { return false; } bytes4 retval = IERC1363Receiver(to).onTransferReceived( _msgSender(), from, value, data ); return (retval == _ERC1363_RECEIVED); } /** * @dev Internal function to invoke `onApprovalReceived` on a target address * The call is not executed if the target address is not a contract * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallApprove(address spender, uint256 value, bytes memory data) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( _msgSender(), value, data ); return (retval == _ERC1363_APPROVED); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _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: eth-token-recover/contracts/TokenRecover.sol pragma solidity ^0.6.0; /** * @title TokenRecover * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Allow to recover any ERC20 sent into the contract for error */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol 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.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/access/Roles.sol pragma solidity ^0.6.0; contract Roles is AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR"); constructor () public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "Roles: caller does not have the MINTER role"); _; } modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role"); _; } } // File: contracts/BaseToken.sol pragma solidity ^0.6.0; /** * @title BaseToken * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation of the BaseToken */ contract BaseToken is ERC20Capped, ERC20Burnable, ERC1363, Roles, TokenRecover { // indicates if minting is finished bool private _mintingFinished = false; // indicates if transfer is enabled bool private _transferEnabled = false; event MintFinished(); event TransferEnabled(); /** * @dev Tokens can be minted only before minting finished. */ modifier canMint() { require(!_mintingFinished, "BaseToken: minting is finished"); _; } /** * @dev Tokens can be moved only after if transfer enabled or if you are an approved operator. */ modifier canTransfer(address from) { require( _transferEnabled || hasRole(OPERATOR_ROLE, from), "BaseToken: transfer is not enabled or from does not have the OPERATOR role" ); _; } /** * @param name Name of the token * @param symbol A symbol to be used as ticker * @param decimals Number of decimals. All the operations are done using the smallest and indivisible token unit * @param cap Maximum number of tokens mintable * @param initialSupply Initial token supply * @param transferEnabled If transfer is enabled on token creation * @param mintingFinished If minting is finished after token creation */ constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply, bool transferEnabled, bool mintingFinished ) public ERC20Capped(cap) ERC1363(name, symbol) { require( mintingFinished == false || cap == initialSupply, "BaseToken: if finish minting, cap must be equal to initialSupply" ); _setupDecimals(decimals); if (initialSupply > 0) { _mint(owner(), initialSupply); } if (mintingFinished) { finishMinting(); } if (transferEnabled) { enableTransfer(); } } /** * @return if minting is finished or not. */ function mintingFinished() public view returns (bool) { return _mintingFinished; } /** * @return if transfer is enabled or not. */ function transferEnabled() public view returns (bool) { return _transferEnabled; } /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. */ function mint(address to, uint256 value) public canMint onlyMinter { _mint(to, value); } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) public virtual override(ERC20) canTransfer(_msgSender()) returns (bool) { return super.transfer(to, value); } /** * @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 * @return A boolean that indicates if the operation was successful. */ function transferFrom(address from, address to, uint256 value) public virtual override(ERC20) canTransfer(from) returns (bool) { return super.transferFrom(from, to, value); } /** * @dev Function to stop minting new tokens. */ function finishMinting() public canMint onlyOwner { _mintingFinished = true; emit MintFinished(); } /** * @dev Function to enable transfers. */ function enableTransfer() public onlyOwner { _transferEnabled = true; emit TransferEnabled(); } /** * @dev See {ERC20-_beforeTokenTransfer}. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Capped) { super._beforeTokenTransfer(from, to, amount); } }
* @title IERC1363 Interface @dev Interface for a Payable Token contract as defined in/
interface IERC1363 is IERC20, IERC165 { function transferAndCall(address to, uint256 value) external returns (bool); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool); function transferFromAndCall(address from, address to, uint256 value) external returns (bool); function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool); function approveAndCall(address spender, uint256 value) external returns (bool); function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool); } }
10,789,491
[ 1, 45, 654, 39, 3437, 4449, 6682, 225, 6682, 364, 279, 13838, 429, 3155, 6835, 487, 2553, 316, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3437, 4449, 353, 467, 654, 39, 3462, 16, 467, 654, 39, 28275, 288, 203, 203, 203, 565, 445, 7412, 1876, 1477, 12, 2867, 358, 16, 2254, 5034, 460, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1876, 1477, 12, 2867, 358, 16, 2254, 5034, 460, 16, 1731, 745, 892, 501, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 1876, 1477, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 203, 565, 445, 7412, 1265, 1876, 1477, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 16, 1731, 745, 892, 501, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 6617, 537, 1876, 1477, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 6617, 537, 1876, 1477, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 16, 1731, 745, 892, 501, 13, 3903, 1135, 261, 6430, 1769, 203, 97, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; interface IERC1155 { /****************************************| | Events | |_______________________________________*/ /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle( address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount ); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch( address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts ); /** * @dev MUST emit when an approval is updated */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /****************************************| | Functions | |_______________________________________*/ /** * @notice Transfers amount of an _id from the _from address to the _to address specified * @dev MUST emit TransferSingle event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if balance of sender for token `_id` is lower than the `_amount` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data ) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev MUST emit TransferBatch event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if length of `_ids` is not the same as length of `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom( address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external; /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @dev MUST emit the ApprovalForAll event on success * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received( address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data ) external returns (bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external returns (bytes4); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT AND Apache-2.0 pragma solidity 0.7.4; /** * Utility library of inline functions on addresses */ library Address { // Default hash for EOA accounts returned by extcodehash bytes32 internal constant ACCOUNT_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract. * @param _address address of the account to check * @return Whether the target address is a contract */ function isContract(address _address) internal view returns (bool) { bytes32 codehash; // Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address or if it has a non-zero code hash or account hash assembly { codehash := extcodehash(_address) } return (codehash != 0x0 && codehash != ACCOUNT_HASH); } /** * @dev Performs a Solidity function call using a low level `call`. * * 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. */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal 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(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT AND Apache-2.0 pragma solidity >=0.6.0 <0.8.0; import '../interfaces/IERC20.sol'; import '../utils/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); _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: Apache-2.0 pragma solidity 0.7.4; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath#mul: OVERFLOW'); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'SafeMath#div: DIVISION_BY_ZERO'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'SafeMath#sub: UNDERFLOW'); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath#add: OVERFLOW'); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'SafeMath#mod: DIVISION_BY_ZERO'); return a % b; } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; /* solhint-disable func-name-mixedcase */ abstract contract ICurveFiDepositY { function add_liquidity(uint256[4] calldata uAmounts, uint256 minMintAmount) external virtual; function remove_liquidity(uint256 amount, uint256[4] calldata minUAmounts) external virtual; function remove_liquidity_imbalance( uint256[4] calldata uAmounts, uint256 maxBurnAmount ) external virtual; function calc_withdraw_one_coin(uint256 wrappedAmount, int128 coinIndex) external view virtual returns (uint256 underlyingAmount); function remove_liquidity_one_coin( uint256 wrappedAmount, int128 coinIndex, uint256 minAmount, bool donateDust ) external virtual; function coins(int128 i) external view virtual returns (address); function underlying_coins(int128 i) external view virtual returns (address); function underlying_coins() external view virtual returns (address[4] memory); function curve() external view virtual returns (address); function token() external view virtual returns (address); } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; import '@openzeppelin/contracts/utils/Context.sol'; import '../../0xerc1155/interfaces/IERC1155.sol'; import '../../0xerc1155/interfaces/IERC1155TokenReceiver.sol'; import '../../0xerc1155/interfaces/IERC20.sol'; import '../../0xerc1155/utils/SafeERC20.sol'; import '../../0xerc1155/utils/SafeMath.sol'; import '../../interfaces/curve/CurveDepositInterface.sol'; import '../investment/interfaces/ICFolioFarm.sol'; // Wolves rewards import '../token/interfaces/IWOWSCryptofolio.sol'; import '../token/interfaces/IWOWSERC1155.sol'; // SFT contract import '../utils/interfaces/IAddressRegistry.sol'; import '../utils/AddressBook.sol'; import '../utils/TokenIds.sol'; import './interfaces/ICFolioItemHandler.sol'; import './interfaces/ISFTEvaluator.sol'; /** * @dev CFolioItemHandlerSC manages CFolioItems, minted in the SFT contract. * * Minting CFolioItem SFTs is implemented in the WOWSSFTMinter contract, which * mints the SFT in the WowsERC1155 contract and calls setupCFolio in here. * * Normaly CFolioItem SFTs are locked in the main TradeFloor contract to allow * trading or transfer into a Base SFT card's c-folio. * * CFolioItem SFTs only earn rewards if they are inside the cfolio of a base * NFT. We get called from main TradeFloor every time an CFolioItem gets * transfered and calculate the new rewardable ?? amount based on the reward % * of the base NFT. */ contract CFolioItemHandlerSC is ICFolioItemHandler, Context { using SafeMath for uint256; using TokenIds for uint256; using SafeERC20 for IERC20; ////////////////////////////////////////////////////////////////////////////// // Routing ////////////////////////////////////////////////////////////////////////////// // Route to SFT Minter. Only setup from SFT Minter allowed. address public sftMinter; // The TradeFloor contract which provides c-folio NFTs. This TradeFloor // contract calls the IMinterCallback interface functions. address public immutable tradeFloor; // SFT evaluator ISFTEvaluator public immutable sftEvaluator; // Reward emitter ICFolioFarmOwnable public immutable cfolioFarm; // Admin address public immutable admin; // The SFT contract needed to check if the address is a c-folio IWOWSERC1155 private immutable sftHolder; // Address registry containing system addresses IAddressRegistry private immutable _addressRegistry; // Curve Y pool token contract IERC20 public immutable curveYToken; // Curve Y pool deposit contract ICurveFiDepositY public immutable curveYDeposit; ////////////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////////////// /* * @dev Emitted when a reward is updated, either increased or decreased * * @param previousAmount The amount before updating the reward * @param newAmount The amount after updating the reward */ event SCRewardUpdated(uint256 previousAmount, uint256 newAmount); /** * @dev Emitted when a new minter is set by the admin * * @param minter The new minter */ event NewSCMinter(address minter); /** * @dev Emitted when the contract is upgraded * * @param thisContract The address of this contract * @param newContract The address of the contract being upgraded to */ event SCContractUpgraded(address thisContract, address newContract); ////////////////////////////////////////////////////////////////////////////// // Modifiers ////////////////////////////////////////////////////////////////////////////// modifier onlyTradeFloor { require(_msgSender() == address(tradeFloor), 'TFCLP: only TF'); _; } ////////////////////////////////////////////////////////////////////////////// // Initialization ////////////////////////////////////////////////////////////////////////////// /** * @dev Constructs the CFolioItemHandlerSC * * We gather all current addresses from address registry into immutable vars. * If one of the relevant addresses changes, the contract has to be updated. * There is little state here, user state is completely handled in CFolioFarm. */ constructor(IAddressRegistry addressRegistry) { // Address registry _addressRegistry = addressRegistry; // TradeFloor tradeFloor = addressRegistry.getRegistryEntry( AddressBook.TRADE_FLOOR_PROXY ); // Admin admin = addressRegistry.getRegistryEntry(AddressBook.MARKETING_WALLET); // The SFT holder sftHolder = IWOWSERC1155( addressRegistry.getRegistryEntry(AddressBook.SFT_HOLDER) ); // The SFT minter sftMinter = addressRegistry.getRegistryEntry(AddressBook.SFT_MINTER); emit NewSCMinter(sftMinter); // SFT evaluator sftEvaluator = ISFTEvaluator( addressRegistry.getRegistryEntry(AddressBook.SFT_EVALUATOR_PROXY) ); // The Y pool deposit contract curveYDeposit = ICurveFiDepositY( addressRegistry.getRegistryEntry(AddressBook.CURVE_Y_DEPOSIT) ); // The Y pool token contract curveYToken = IERC20( addressRegistry.getRegistryEntry(AddressBook.CURVE_Y_TOKEN) ); // WOWS reward farm cfolioFarm = ICFolioFarmOwnable( addressRegistry.getRegistryEntry(AddressBook.BOIS_REWARDS) ); } /** * @dev One time contract initializer */ function initialize() public { // Approve stablecoin spending for (uint256 i = 0; i < 4; ++i) { address underlyingCoin = curveYDeposit.underlying_coins(int128(i)); IERC20(underlyingCoin).safeApprove(address(curveYDeposit), uint256(-1)); } // Approve yCRV spending curveYToken.approve(address(curveYDeposit), uint256(-1)); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {ICFolioItemCallback} via {ICFolioItemHandler} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ICFolioItemCallback-onCFolioItemsTransferedFrom} */ function onCFolioItemsTransferedFrom( address from, address to, uint256[] calldata, /* tokenIds*/ address[] calldata /* cfolioHandlers*/ ) external override onlyTradeFloor { // In case of transfer verify the target uint256 sftTokenId; if ( to != address(0) && (sftTokenId = sftHolder.addressToTokenId(to)) != uint256(-1) ) { (, uint8 level) = sftHolder.getTokenData(sftTokenId); require((LEVEL2BOIS & (uint256(1) << level)) > 0, 'CFIH: Bois only'); _updateRewards(to, sftEvaluator.rewardRate(sftTokenId)); } if ( from != address(0) && (sftTokenId = sftHolder.addressToTokenId(from)) != uint256(-1) ) _updateRewards(from, sftEvaluator.rewardRate(sftTokenId)); } /** * @dev See {ICFolioItemCallback-appendHash} */ function appendHash(address cfolioItem, bytes calldata current) external view override returns (bytes memory) { return abi.encodePacked( current, address(this), cfolioFarm.balanceOf(cfolioItem) ); } /** * @dev See {ICFolioItemCallback-uri} */ function uri( uint256 /* tokenId */ ) external pure override returns (string memory) { return ''; } ////////////////////////////////////////////////////////////////////////////// // Implementation of {ICFolioItemHandler} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ICFolioItemHandler-sftUpgrade} */ function sftUpgrade(uint256 tokenId, uint32 newRate) external override { // Validate access require(_msgSender() == address(sftEvaluator), 'CFIH: Invalid caller'); require(tokenId.isBaseCard(), 'CFIH: Invalid token'); // CFolio address address cfolio = sftHolder.tokenIdToAddress(tokenId); // Update state _updateRewards(cfolio, newRate); } /** * @dev See {ICFolioItemHandler-setupCFolio} * * Note: We place a dummy ERC1155 token with ID 0 into the CFolioItem's * c-folio. The reason is that we want to know if a c-folio item gets burned, * as burning an empty c-folio will result in no transfers. This prevents LP * tokens from becoming inaccessible. * * Refer to the Minimal ERC1155 section below to learn which functions are * needed for this. * * @param sftTokenId The token ID of the SFT being setup * @param amounts The token amounts, in this order: DAI, USDC, USDT, TUSD, yCRV * `amounts` can be empty when setting up a CFolio with no initial investments. */ function setupCFolio( address payer, uint256 sftTokenId, uint256[] calldata amounts ) external override { // Validate access require(_msgSender() == sftMinter, 'Only SFTMinter'); // Validate parameters, no unmasking required, must be SFT address cFolio = sftHolder.tokenIdToAddress(sftTokenId); require(cFolio != address(0), 'Invalid sftTokenId'); require( amounts.length == 0 || amounts.length == 5, 'Need DAI/USDC/USDT/TUSD/yCRV' ); // Verify that this function is called the first time try IWOWSCryptofolio(cFolio)._tradefloors(0) returns (address) { revert('CFIH: TradeFloor not empty'); } catch {} // Keep track of how many Y pool tokens were received uint256 beforeBalance = curveYToken.balanceOf(address(this)); // Handle stablecoins if (amounts.length > 0) { uint256[4] memory stableAmounts; uint256 totalStableAmount; for (uint256 i = 0; i < 4; ++i) { address underlyingCoin = curveYDeposit.underlying_coins(int128(i)); IERC20(underlyingCoin).safeTransferFrom( payer, address(this), amounts[i] ); uint256 stableAmount = IERC20(underlyingCoin).balanceOf(address(this)); stableAmounts[i] = stableAmount; totalStableAmount += stableAmount; } if (totalStableAmount > 0) { // Call to external contract curveYDeposit.add_liquidity(stableAmounts, 0); // Validate state uint256 afterStableBalance = curveYToken.balanceOf(address(this)); require( afterStableBalance > beforeBalance, 'No liquidity from stables' ); } // Handle Y pool uint256 yPoolAmount = amounts[4]; if (yPoolAmount > 0) { curveYToken.transferFrom(payer, address(this), yPoolAmount); } // Validate state uint256 afterBalance = curveYToken.balanceOf(address(this)); // Record assets in Farm contract. They don't earn rewards. // addAsset must only be called from Investment CFolios // This call is allowed without any investment. if (afterBalance > beforeBalance) cfolioFarm.addAssets(cFolio, afterBalance.sub(beforeBalance)); } // Transfer a dummy NFT token to cFolio so we get informed if the cFolio // gets burned IERC1155TokenReceiver(cFolio).onERC1155Received( address(this), address(0), 0, 1, '' ); } /** * @dev See {ICFolioItemHandler-deposit} * * Note: tokenId can be owned by a base SFT. In this case base SFT cannot be * locked. * * There is only need to update rewards if tokenId is part of an unlocked * base SFT. */ function deposit( uint256 baseTokenId, uint256 tokenId, uint256[] calldata amounts ) external override { // Validate parameters require(amounts.length == 5, 'Need DAI/USDC/USDT/TUSD/yCRV'); (address baseCFolio, address itemCFolio) = _verifyAssetAccess(baseTokenId, tokenId); // Keep track of how many Y pool tokens were received uint256 beforeBalance = curveYToken.balanceOf(address(this)); // Handle stablecoins uint256[4] memory stableAmounts; uint256 totalStableAmount; for (uint256 i = 0; i < 4; ++i) { address underlyingCoin = curveYDeposit.underlying_coins(int128(i)); IERC20(underlyingCoin).safeTransferFrom( _msgSender(), address(this), amounts[i] ); uint256 stableAmount = IERC20(underlyingCoin).balanceOf(address(this)); stableAmounts[i] = stableAmount; totalStableAmount += stableAmount; } if (totalStableAmount > 0) { // Call to external contract curveYDeposit.add_liquidity(stableAmounts, 0); // Validate state uint256 afterStableBalance = curveYToken.balanceOf(address(this)); require(afterStableBalance > beforeBalance, 'No liquidity from stables'); } // Handle Y pool uint256 yPoolAmount = amounts[4]; if (yPoolAmount > 0) { curveYToken.transferFrom(_msgSender(), address(this), yPoolAmount); } // Validate state uint256 afterBalance = curveYToken.balanceOf(address(this)); require(afterBalance > beforeBalance, 'No liquidity added'); // Record assets in Farm contract. They don't earn rewards. // addAsset must only be called from Investment CFolios cfolioFarm.addAssets(itemCFolio, afterBalance.sub(beforeBalance)); if (baseTokenId != uint256(-1)) { _updateRewards(baseCFolio, sftEvaluator.rewardRate(baseTokenId)); } } /** * @dev See {ICFolioItemHandler-withdraw} * * Note: tokenId can be owned by a base SFT. In this case, the base SFT * cannot be locked. * * There is only need to update rewards if tokenId is part of an unlocked * base SFT. * * @param baseTokenId The token ID of the base c-folio, or uint(-1) if * tokenId is not owned by a base c-folio. * @param tokenId The token ID of the investment SFT to withdraw from * @param amounts The amounts, with the tokens being DAI/USDC/USDT/TUSD/yCRV. * yCRV must be specified, as yCRV tokens are held by this contract. * If all four stablecoin amounts are 0, then yCRV is withdrawn to the * sender's wallet. If exactly one of the four stablecoin amounts is > 0, * then yCRV will be converted to the specified stablecoin. The amount in * the array is the minimum amount of stablecoin tokens that must be * withdrawn. */ function withdraw( uint256 baseTokenId, uint256 tokenId, uint256[] calldata amounts ) external override { // Validate parameters require(amounts.length == 5, 'Need DAI/USDC/USDT/TUSD/yCRV'); (address baseCFolio, address itemCFolio) = _verifyAssetAccess(baseTokenId, tokenId); // Validate parameters uint256 yPoolAmount = amounts[4]; require(yPoolAmount > 0, 'yCRV amount is 0'); // Get single coin and amount (int128 stableCoinIndex, uint256 stableCoinAmount) = _getStableCoinInfo(amounts); // Keep track of how many Y pool tokens were sent uint256 balanceBefore = curveYToken.balanceOf(address(this)); if (stableCoinIndex != -1) { // Call to external contract curveYDeposit.remove_liquidity_one_coin( yPoolAmount, stableCoinIndex, stableCoinAmount, true ); address underlyingCoin = curveYDeposit.underlying_coins(int128(stableCoinIndex)); uint256 underlyingCoinAmount = IERC20(underlyingCoin).balanceOf(address(this)); // Transfer stablecoins back to the sender IERC20(underlyingCoin).safeTransfer(_msgSender(), underlyingCoinAmount); } else { // No stablecoins were passed, sender is withdrawing Y pool tokens directly // Transfer Y pool tokens back to the sender curveYToken.transfer(_msgSender(), yPoolAmount); } // Valiate state uint256 balanceAfter = curveYToken.balanceOf(address(this)); require(balanceAfter < balanceBefore, 'Nothing withdrawn'); // Record assets in Farm contract. They don't earn rewards. // removeAsset must only be called from Investment CFolios cfolioFarm.removeAssets(itemCFolio, balanceBefore.sub(balanceAfter)); // Update state if (baseTokenId != uint256(-1)) _updateRewards(baseCFolio, sftEvaluator.rewardRate(baseTokenId)); } /** * @dev See {ICFolioItemHandler-getRewards} * * Note: tokenId must be a base SFT card * * We allow reward pull only for unlocked SFTs. */ function getRewards(address recipient, uint256 tokenId) external override { // Validate parameters require(recipient != address(0), 'CFIH: Invalid recipient'); require(tokenId.isBaseCard(), 'CFIH: Invalid tokenId'); // Verify that tokenId has a valid cFolio address uint256 sftTokenId = tokenId.toSftTokenId(); address cfolio = sftHolder.tokenIdToAddress(sftTokenId); require(cfolio != address(0), 'Invalid c-folio address'); // Verify that the tokenId is owned by msg.sender in case of direct // call or recipient in case of sftMinter call in the SFT contract. // This also verifies that the token is not locked in TradeFloor. require( IERC1155(address(sftHolder)).balanceOf(_msgSender(), sftTokenId) == 1 || (_msgSender() == sftMinter && IERC1155(address(sftHolder)).balanceOf(recipient, sftTokenId) == 1), 'CFHI: Access denied' ); cfolioFarm.getReward(cfolio, recipient); } /** * @dev See {ICFolioItemHandler-getAmounts} * * The returned token array is DAI/USDC/USDT/TUSD/yCRV. Tokens are held in * this contract as yCRV, so the fifth item will be the amount of yCRV. The * four stablecoin amounts are the amount that would be withdrawn if all * yCRV were converted to the corresponding stablecoin upon withdrawal. This * value is calculated by Curve. */ function getAmounts(address cfolioItem) external view override returns (uint256[] memory) { uint256[] memory result = new uint256[](5); uint256 wrappedAmount = cfolioFarm.balanceOf(cfolioItem); for (uint256 i = 0; i < 4; ++i) { result[i] = curveYDeposit.calc_withdraw_one_coin( wrappedAmount, int128(i) ); } result[4] = wrappedAmount; return result; } /** * @dev See {ICFolioItemHandler-getRewardInfo} */ function getRewardInfo(uint256[] calldata tokenIds) external view override returns (bytes memory result) { uint256[5] memory uiData; // get basic data once uiData = cfolioFarm.getUIData(address(0)); // total / rewardDuration / rewardPerDuration result = abi.encodePacked(uiData[0], uiData[2], uiData[3]); for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 sftTokenId = tokenIds[i].toSftTokenId(); uint256 share = 0; uint256 earned = 0; if (sftTokenId.isBaseCard()) { address cfolio = sftHolder.tokenIdToAddress(sftTokenId); if (cfolio != address(0)) { uiData = cfolioFarm.getUIData(cfolio); share = uiData[1]; earned = uiData[4]; } } result = abi.encodePacked(result, share, earned); } } ////////////////////////////////////////////////////////////////////////////// // Maintanace ////////////////////////////////////////////////////////////////////////////// /** * @dev Upgrade contract */ function upgradeContract(CFolioItemHandlerSC newContract) external { // Validate access require(_msgSender() == admin, 'Admin only'); // Let new handler control the reward farm cfolioFarm.transferOwnership(address(newContract)); // Dispatch event SCContractUpgraded(address(this), address(newContract)); selfdestruct(payable(address(newContract))); } /** * @dev Set a new SFT minter */ function setMinter(address newMinter) external { // Validate access require(_msgSender() == admin, 'Admin only'); // Validate parameters require(newMinter != address(0), 'Invalid newMinter'); // Update state sftMinter = newMinter; // Dispatch event emit NewSCMinter(newMinter); } ////////////////////////////////////////////////////////////////////////////// // Minimal ERC1155 implementation (called from SFTBase CFolio) ////////////////////////////////////////////////////////////////////////////// // We do nothing for our dummy burn tokenId function setApprovalForAll(address, bool) external {} // Check for length == 1, and then return always 1 function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external pure returns (uint256[] memory) { // Validate parameters require(_owners.length == 1 && _ids.length == 1, 'Length must be 1'); uint256[] memory result = new uint256[](1); result[0] = 1; return result; } /** * @dev We don't allow burning non-empty c-folios */ function burnBatch( address, /* account */ uint256[] calldata tokenIds, uint256[] calldata ) external view { // Validate parameters require(tokenIds.length == 1, 'Length must be 1'); // This call originates from the c-folio. We revert if there are investment // amounts left for this c-folio address. require(cfolioFarm.balanceOf(_msgSender()) == 0, 'CFIH: not empty'); } ////////////////////////////////////////////////////////////////////////////// // Internal details ////////////////////////////////////////////////////////////////////////////// /** * @dev Run through all cFolioItems collected in cFolio and select the amount * of tokens. Update cfolioFarm. */ function _updateRewards(address cfolio, uint32 rate) private { // Get c-folio items of this base cFolio (uint256[] memory tokenIds, uint256 length) = IWOWSCryptofolio(cfolio).getCryptofolio(tradeFloor); // Marginal increase in gas per item is around 25K. Bounding items to 100 // fits in sensible gas limits. require(length <= 100, 'CFIHSC: Too many items'); // Calculate new reward amount uint256 newRewardAmount = 0; for (uint256 i = 0; i < length; ++i) { address secondaryCFolio = sftHolder.tokenIdToAddress(tokenIds[i].toSftTokenId()); require(secondaryCFolio != address(0), 'CFIH: Invalid secondary cFolio'); if (IWOWSCryptofolio(secondaryCFolio)._tradefloors(0) == address(this)) newRewardAmount = newRewardAmount.add( cfolioFarm.balanceOf(secondaryCFolio) ); } newRewardAmount = newRewardAmount.mul(rate).div(1E6); // Calculate existing reward amount uint256 exitingRewardAmount = cfolioFarm.balanceOf(cfolio); // Compare amounts and add/remove shares if (newRewardAmount > exitingRewardAmount) { // Update state cfolioFarm.addShares(cfolio, newRewardAmount.sub(exitingRewardAmount)); // Dispatch event emit SCRewardUpdated(exitingRewardAmount, newRewardAmount); } else if (newRewardAmount < exitingRewardAmount) { // Update state cfolioFarm.removeShares(cfolio, exitingRewardAmount.sub(newRewardAmount)); // Dispatch event emit SCRewardUpdated(exitingRewardAmount, newRewardAmount); } } /** * @dev Verifies if an asset access operation is allowed * * @param baseTokenId Base card tokenId or uint(-1) * @param cfolioItemTokenId CFolioItem tokenId handled by this contract * * A tokenId is "unlocked", if msg.sender is the owner of a tokenId in SFT contract. * If baseTokenId is uint(-1), cfolioItemTokenId has to be be unlocked, otherwise * baseTokenId has to be unlocked and the locked cfolioItemTokenId inside its cfolio. */ function _verifyAssetAccess(uint256 baseTokenId, uint256 cfolioItemTokenId) private view returns (address, address) { // Verify it's a cfolioItemTokenId require(cfolioItemTokenId.isCFolioCard(), 'CFHI: Not CFolioCard'); // Verify that the tokenId is one of ours address cFolio = sftHolder.tokenIdToAddress(cfolioItemTokenId.toSftTokenId()); require(cFolio != address(0), 'CFIH: Invalid cFolioTokenId'); require( IWOWSCryptofolio(cFolio)._tradefloors(0) == address(this), 'CFIH: Not our SFT' ); address baseCFolio = address(0); if (baseTokenId != uint256(-1)) { // Verify it's a cfolio base card require(baseTokenId.isBaseCard(), 'CFHI: Not baseCard'); baseCFolio = sftHolder.tokenIdToAddress(baseTokenId.toSftTokenId()); require(baseCFolio != address(0), 'CFIH: Invalid baseCFolioTokenId'); // Verify that the tokenId is owned by msg.sender in SFT contract. // This also verifies that the token is not locked in TradeFloor. require( IERC1155(address(sftHolder)).balanceOf(_msgSender(), baseTokenId) == 1, 'CFHI: Access denied (B)' ); // Verify that the tokenId is owned by given baseCFolio. require( IERC1155(address(tradeFloor)).balanceOf( baseCFolio, cfolioItemTokenId ) == 1, 'CFHI: Access denied (CF)' ); } else { // Verify that the tokenId is owned by msg.sender in SFT contract. // This also verifies that the token is not locked in TradeFloor. require( IERC1155(address(sftHolder)).balanceOf( _msgSender(), cfolioItemTokenId ) == 1, 'CFHI: Access denied' ); } return (baseCFolio, cFolio); } /** * @dev Get single coin and amount * * This is a helper function for {withdraw}. Per the documentation above, no * more than one stablecoin amount can be > 0. If more than one stablecoin * amount is specified, the revert condition below will be reached. * * If exactly one stablecoin amount is specified, then the return values will * be the index of that coin and its amount. * * If no stablecoin amounts are > 0, then a coin index of -1 is returned, * with a 0 amount. * * @param amounts The amounts array: DAI/USDC/USDT/TUSD/yCRV * * @return stableCoinIndex The index of the stablecoin with amount > 0, or -1 * if all four stablecoin amounts are 0 * @return stableCoinAmount The amount of the stablecoin, or 0 if all four * stablecoin amounts are 0 */ function _getStableCoinInfo(uint256[] calldata amounts) private pure returns (int128 stableCoinIndex, uint256 stableCoinAmount) { stableCoinIndex = -1; for (uint128 i = 0; i < 4; ++i) { if (amounts[i] > 0) { require(stableCoinIndex == -1, 'Multiple amounts > 0'); stableCoinIndex = int8(i); stableCoinAmount = amounts[i]; } } } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; import '../../token/interfaces/ICFolioItemCallback.sol'; /** * @dev Interface to C-folio item contracts */ interface ICFolioItemHandler is ICFolioItemCallback { /** * @dev Called when a SFT tokens grade needs re-evaluation * * @param tokenId The ERC-1155 token ID. Rate is in 1E6 convention: 1E6 = 100% * @param newRate The new value rate */ function sftUpgrade(uint256 tokenId, uint32 newRate) external; /** * @dev Called from SFTMinter after an Investment SFT is minted * * @param payer The approved address to get investment from * @param sftTokenId The sftTokenId whose c-folio is the owner of investment * @param amounts The amounts of invested assets */ function setupCFolio( address payer, uint256 sftTokenId, uint256[] calldata amounts ) external; ////////////////////////////////////////////////////////////////////////////// // Asset access ////////////////////////////////////////////////////////////////////////////// /** * @dev Adds investments into a cFolioItem SFT * * Transfers amounts of assets from users wallet to the contract. In general, * an Approval call is required before the function is called. * * @param baseTokenId cFolio tokenId, must be unlocked, or -1 * @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio * @param amounts Investment amounts, implementation specific */ function deposit( uint256 baseTokenId, uint256 tokenId, uint256[] calldata amounts ) external; /** * @dev Removes investments from a cFolioItem SFT * * Withdrawn token are transfered back to msg.sender. * * @param baseTokenId cFolio tokenId, must be unlocked, or -1 * @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio * @param amounts Investment amounts, implementation specific */ function withdraw( uint256 baseTokenId, uint256 tokenId, uint256[] calldata amounts ) external; /** * @dev Get the rewards collected by an SFT base card * * @param recipient Recipient of the rewards (- fees) * @param tokenId SFT base card tokenId, must be unlocked */ function getRewards(address recipient, uint256 tokenId) external; /** * @dev Get amounts (handler specific) for a cfolioItem * * @param cfolioItem address of CFolioItem contract */ function getAmounts(address cfolioItem) external view returns (uint256[] memory); /** * @dev Get information obout the rewardFarm * * @param tokenIds List of basecard tokenIds * @return bytes of uint256[]: total, rewardDur, rewardRateForDur, [share, earned] */ function getRewardInfo(uint256[] calldata tokenIds) external view returns (bytes memory); } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; // BOIS feature bitmask uint256 constant LEVEL2BOIS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000F; uint256 constant LEVEL2WOLF = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000F0; interface ISFTEvaluator { /** * @dev Returns the reward in 1e6 factor notation (1e6 = 100%) */ function rewardRate(uint256 sftTokenId) external view returns (uint32); /** * @dev Returns the cFolioItemType of a given cFolioItem tokenId */ function getCFolioItemType(uint256 tokenId) external view returns (uint256); /** * @dev Calculate the current reward rate, and notify TFC in case of change * * Optional revert on unchange to save gas on external calls. */ function setRewardRate(uint256 tokenId, bool revertUnchanged) external; /** * @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used * sftHolder tokenId expected (without hash) */ function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) external; } /* * Copyright (C) 2020-2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.6.0 <0.8.0; /** * @title ICFolioFarm * * @dev ICFolioFarm is the business logic interface to c-folio farms. */ interface ICFolioFarm { /** * @dev Return invested balance of account */ function balanceOf(address account) external view returns (uint256); /** * @dev Return total, balances[account], rewardDuration, rewardForDuration, earned[account] */ function getUIData(address account) external view returns (uint256[5] memory); /** * @dev Increase amount of non-rewarded asset */ function addAssets(address account, uint256 amount) external; /** * @dev Remove amount of previous added assets */ function removeAssets(address account, uint256 amount) external; /** * @dev Increase amount of shares and earn rewards */ function addShares(address account, uint256 amount) external; /** * @dev Remove amount of previous added shares, rewards will not be claimed */ function removeShares(address account, uint256 amount) external; /** * @dev Claim rewards harvested during reward time */ function getReward(address account, address rewardRecipient) external; /** * @dev Remove all shares and call getRewards() in a single step */ function exit(address account, address rewardRecipient) external; } /** * @title ICFolioFarmOwnable */ interface ICFolioFarmOwnable is ICFolioFarm { /** * @dev Transfer ownership */ function transferOwnership(address newOwner) external; } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @dev Interface to receive callbacks when minted tokens are burnt */ interface ICFolioItemCallback { /** * @dev Called when a TradeFloor CFolioItem is transfered * * In case of mint `from` is address(0). * In case of burn `to` is address(0). * * cfolioHandlers are passed to let each cfolioHandler filter for its own * token. This eliminates the need for creating separate lists. * * @param from The account sending the token * @param to The account receiving the token * @param tokenIds The ERC-1155 token IDs * @param cfolioHandlers cFolioItem handlers */ function onCFolioItemsTransferedFrom( address from, address to, uint256[] calldata tokenIds, address[] calldata cfolioHandlers ) external; /** * @dev Append data we use later for hashing * * @param cfolioItem The token ID of the c-folio item * @param current The current data being hashes * * @return The current data, with internal data appended */ function appendHash(address cfolioItem, bytes calldata current) external view returns (bytes memory); /** * @dev get custom uri for tokenId */ function uri(uint256 tokenId) external view returns (string memory); } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @notice Cryptofolio interface */ interface IWOWSCryptofolio { ////////////////////////////////////////////////////////////////////////////// // Initialization ////////////////////////////////////////////////////////////////////////////// /** * @dev Initialize the deployed contract after creation * * This is a one time call which sets _deployer to msg.sender. * Subsequent calls reverts. */ function initialize() external; ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Return tradefloor at given index * * @param index The 0-based index in the tradefloor array * * @return The address of the tradefloor and position index */ function _tradefloors(uint256 index) external view returns (address); /** * @dev Return array of cryptofolio item token IDs * * The token IDs belong to the contract TradeFloor. * * @param tradefloor The TradeFloor that items belong to * * @return tokenIds The token IDs in scope of operator * @return idsLength The number of valid token IDs */ function getCryptofolio(address tradefloor) external view returns (uint256[] memory tokenIds, uint256 idsLength); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @dev Set the owner of the underlying NFT * * This function is called if ownership of the parent NFT has changed. * * The new owner gets allowance to transfer cryptofolio items. The new owner * is allowed to transfer / burn cryptofolio items. Make sure that allowance * is removed from previous owner. * * @param owner The new owner of the underlying NFT, or address(0) if the * underlying NFT is being burned */ function setOwner(address owner) external; /** * @dev Allow owner (of parent NFT) to approve external operators to transfer * our cryptofolio items * * The NFT owner is allowed to approve operator to handle cryptofolios. * * @param operator The operator * @param allow True to approve for all NFTs, false to revoke approval */ function setApprovalForAll(address operator, bool allow) external; /** * @dev Burn all cryptofolio items * * In case an underlying NFT is burned, we also burn the cryptofolio. */ function burn() external; } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @notice Cryptofolio interface */ interface IWOWSERC1155 { ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Check if the specified address is a known tradefloor * * @param account The address to check * * @return True if the address is a known tradefloor, false otherwise */ function isTradeFloor(address account) external view returns (bool); /** * @dev Get the token ID of a given address * * A cross check is required because token ID 0 is valid. * * @param tokenAddress The address to convert to a token ID * * @return The token ID on success, or uint256(-1) if `tokenAddress` does not * belong to a token ID */ function addressToTokenId(address tokenAddress) external view returns (uint256); /** * @dev Get the address for a given token ID * * @param tokenId The token ID to convert * * @return The address, or address(0) in case the token ID does not belong * to an NFT */ function tokenIdToAddress(uint256 tokenId) external view returns (address); /** * @dev Get the next mintable token ID for the specified card * * @param level The level of the card * @param cardId The ID of the card * * @return bool True if a free token ID was found, false otherwise * @return uint256 The first free token ID if one was found, or invalid otherwise */ function getNextMintableTokenId(uint8 level, uint8 cardId) external view returns (bool, uint256); /** * @dev Return the next mintable custom token ID */ function getNextMintableCustomToken() external view returns (uint256); /** * @dev Return the level and the mint timestamp of tokenId * * @param tokenId The tokenId to query * * @return mintTimestamp The timestamp token was minted * @return level The level token belongs to */ function getTokenData(uint256 tokenId) external view returns (uint64 mintTimestamp, uint8 level); /** * @dev Return all tokenIds owned by account */ function getTokenIds(address account) external view returns (uint256[] memory); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @dev Set the base URI for either predefined cards or custom cards * which don't have it's own URI. * * The resulting uri is baseUri+[hex(tokenId)] + '.json'. where * tokenId will be reduces to upper 16 bit (>> 16) before building the hex string. * */ function setBaseMetadataURI(string memory baseContractMetadata) external; /** * @dev Set the contracts metadata URI * * @param contractMetadataURI The URI which point to the contract metadata file. */ function setContractMetadataURI(string memory contractMetadataURI) external; /** * @dev Set the URI for a custom card * * @param tokenId The token ID whose URI is being set. * @param customURI The URI which point to an unique metadata file. */ function setCustomURI(uint256 tokenId, string memory customURI) external; /** * @dev Each custom card has its own level. Level will be used when * calculating rewards and raiding power. * * @param tokenId The ID of the token whose level is being set * @param cardLevel The new level of the specified token */ function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external; } /* * Copyright (C) 2020-2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; library AddressBook { bytes32 public constant DEPLOYER = 'DEPLOYER'; bytes32 public constant TEAM_WALLET = 'TEAM_WALLET'; bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET'; bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02'; bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM'; bytes32 public constant WOWS_TOKEN = 'WOWS_TOKEN'; bytes32 public constant UNISWAP_V2_PAIR = 'UNISWAP_V2_PAIR'; bytes32 public constant WOWS_BOOSTER = 'WOWS_BOOSTER'; bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER'; bytes32 public constant SFT_MINTER = 'SFT_MINTER'; bytes32 public constant SFT_HOLDER = 'SFT_HOLDER'; bytes32 public constant BOIS_REWARDS = 'BOIS_REWARDS'; bytes32 public constant WOLVES_REWARDS = 'WOLVES_REWARDS'; bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY'; bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY'; bytes32 public constant CURVE_Y_TOKEN = 'CURVE_Y_TOKEN'; bytes32 public constant CURVE_Y_DEPOSIT = 'CURVE_Y_DEPOSIT'; } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; library TokenIds { // 128 bit underlying hash uint256 public constant HASH_MASK = (1 << 128) - 1; function isBaseCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) < (1 << 64); } function isStockCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) < (1 << 32); } function isCFolioCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) >= (1 << 64) && (tokenId & HASH_MASK) < (1 << 128); } function toSftTokenId(uint256 tokenId) internal pure returns (uint256) { return tokenId & HASH_MASK; } function maskHash(uint256 tokenId) internal pure returns (uint256) { return tokenId & ~HASH_MASK; } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; interface IAddressRegistry { /** * @dev Set an abitrary key / address pair into the registry */ function setRegistryEntry(bytes32 _key, address _location) external; /** * @dev Get a registry enty with by key, returns 0 address if not existing */ function getRegistryEntry(bytes32 _key) external view returns (address); }
solhint-disable func-name-mixedcase */
abstract contract ICurveFiDepositY { function add_liquidity(uint256[4] calldata uAmounts, uint256 minMintAmount) external virtual; function remove_liquidity(uint256 amount, uint256[4] calldata minUAmounts) external virtual; function remove_liquidity_imbalance( uint256[4] calldata uAmounts, uint256 maxBurnAmount ) external virtual; function calc_withdraw_one_coin(uint256 wrappedAmount, int128 coinIndex) external view virtual returns (uint256 underlyingAmount); function remove_liquidity_one_coin( uint256 wrappedAmount, int128 coinIndex, uint256 minAmount, bool donateDust ) external virtual; function coins(int128 i) external view virtual returns (address); function underlying_coins(int128 i) external view virtual returns (address); function underlying_coins() external view virtual returns (address[4] memory); function curve() external view virtual returns (address); function token() external view virtual returns (address); }
405,045
[ 1, 18281, 11317, 17, 8394, 1326, 17, 529, 17, 19562, 3593, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 467, 9423, 42, 77, 758, 1724, 61, 288, 203, 225, 445, 527, 67, 549, 372, 24237, 12, 11890, 5034, 63, 24, 65, 745, 892, 582, 6275, 87, 16, 2254, 5034, 1131, 49, 474, 6275, 13, 203, 565, 3903, 203, 565, 5024, 31, 203, 203, 225, 445, 1206, 67, 549, 372, 24237, 12, 11890, 5034, 3844, 16, 2254, 5034, 63, 24, 65, 745, 892, 1131, 57, 6275, 87, 13, 203, 565, 3903, 203, 565, 5024, 31, 203, 203, 225, 445, 1206, 67, 549, 372, 24237, 67, 381, 12296, 12, 203, 565, 2254, 5034, 63, 24, 65, 745, 892, 582, 6275, 87, 16, 203, 565, 2254, 5034, 943, 38, 321, 6275, 203, 225, 262, 3903, 5024, 31, 203, 203, 225, 445, 7029, 67, 1918, 9446, 67, 476, 67, 12645, 12, 11890, 5034, 5805, 6275, 16, 509, 10392, 13170, 1016, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 5024, 203, 565, 1135, 261, 11890, 5034, 6808, 6275, 1769, 203, 203, 225, 445, 1206, 67, 549, 372, 24237, 67, 476, 67, 12645, 12, 203, 565, 2254, 5034, 5805, 6275, 16, 203, 565, 509, 10392, 13170, 1016, 16, 203, 565, 2254, 5034, 1131, 6275, 16, 203, 565, 1426, 2727, 340, 40, 641, 203, 225, 262, 3903, 5024, 31, 203, 203, 225, 445, 276, 9896, 12, 474, 10392, 277, 13, 3903, 1476, 5024, 1135, 261, 2867, 1769, 203, 203, 225, 445, 6808, 67, 71, 9896, 12, 474, 10392, 277, 13, 3903, 1476, 5024, 1135, 261, 2867, 1769, 203, 203, 225, 445, 6808, 67, 71, 9896, 1435, 3903, 2 ]
// SPDX-License-Identifier: BlueOak-1.0.0 pragma solidity 0.8.9; import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "contracts/interfaces/IAsset.sol"; import "contracts/interfaces/IBasketHandler.sol"; import "contracts/interfaces/IStRSR.sol"; import "contracts/interfaces/IMain.sol"; import "contracts/libraries/Fixed.sol"; import "contracts/p0/mixins/Component.sol"; /* * @title StRSRP0 * @notice The StRSR is where people can stake their RSR in order to provide insurance and * benefit from the supply expansion of an RToken. * * There's an important assymetry in the StRSR. When RSR is added, it must be split only * across non-withdrawing balances, while when RSR is seized, it must be seized from both * balances that are in the process of being withdrawn and those that are not. */ contract StRSRP0 is IStRSR, ComponentP0, EIP712Upgradeable { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; using FixLib for uint192; // ==== ERC20Permit ==== using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); // ==== // Staking Token Name and Symbol string private _name; string private _symbol; // Balances per account mapping(address => uint256) private balances; mapping(address => mapping(address => uint256)) private allowances; // List of accounts. If balances[user] > 0 then (user is in accounts) EnumerableSet.AddressSet internal accounts; // {qStRSR} Total of all stRSR balances, not including pending withdrawals uint256 internal totalStaked; // {qRSR} How much RSR is allocated to backing currently-staked balances uint256 internal rsrBacking; // {seconds} The last time stRSR paid out rewards to stakers uint256 internal payoutLastPaid; // {qRSR} How much reward RSR was held the last time rewards were paid out uint256 internal rsrRewardsAtLastPayout; // Era. If ever there's a total RSR wipeout, this is incremented // This is only really here for equivalence with P1, which requires it uint256 internal era; // The momentary stake/unstake rate is rsrBacking/totalStaked {RSR/stRSR} // That rate is locked in when slow unstaking *begins* // Delayed Withdrawals struct Withdrawal { address account; uint256 rsrAmount; // How much rsr this withdrawal will be redeemed for, if none is seized uint256 stakeAmount; // How much stRSR this withdrawal represents; immutable after creation uint256 availableAt; } // Withdrawal queues by account mapping(address => Withdrawal[]) public withdrawals; // Min exchange rate {qRSR/qStRSR} (compile-time constant) uint192 private constant MIN_EXCHANGE_RATE = uint192(1e9); // 1e-9 // ==== Gov Params ==== uint32 public unstakingDelay; uint32 public rewardPeriod; uint192 public rewardRatio; function init( IMain main_, string memory name_, string memory symbol_, uint32 unstakingDelay_, uint32 rewardPeriod_, uint192 rewardRatio_ ) public initializer { __Component_init(main_); __EIP712_init(name_, "1"); require(unstakingDelay_ > 0, "unstaking delay cannot be zero"); require(rewardPeriod_ * 2 <= unstakingDelay_, "unstakingDelay/rewardPeriod incompatible"); _name = name_; _symbol = symbol_; payoutLastPaid = block.timestamp; rsrRewardsAtLastPayout = main_.rsr().balanceOf(address(this)); unstakingDelay = unstakingDelay_; rewardPeriod = rewardPeriod_; rewardRatio = rewardRatio_; era = 1; } /// Assign reward payouts to the staker pool /// @custom:refresher function payoutRewards() external notPaused { _payoutRewards(); } /// Stakes an RSR `amount` on the corresponding RToken to earn yield and insure the system /// @param rsrAmount {qRSR} /// @custom:interaction function stake(uint256 rsrAmount) external interaction { address account = _msgSender(); require(rsrAmount > 0, "Cannot stake zero"); // Run state keepers main.poke(); uint256 stakeAmount = rsrAmount; // The next line is _not_ an overflow risk, in our expected ranges: // rsrAmount <= 1e29 and totalStaked <= 1e38, so their product <= 1e67 < 1e77 < 2^256 if (totalStaked > 0) stakeAmount = (rsrAmount * totalStaked) / rsrBacking; // Create stRSR balance if (balances[account] == 0) accounts.add(account); balances[account] += stakeAmount; totalStaked += stakeAmount; // Move deposited RSR to backing rsrBacking += rsrAmount; emit Staked(era, account, rsrAmount, stakeAmount); main.rsr().safeTransferFrom(account, address(this), rsrAmount); } /// Begins a delayed unstaking for `amount` stRSR /// @param stakeAmount {qStRSR} /// @custom:interaction function unstake(uint256 stakeAmount) external interaction { address account = _msgSender(); require(stakeAmount > 0, "Cannot withdraw zero"); require(balances[account] >= stakeAmount, "Not enough balance"); // Call state keepers main.poke(); // The next line is not an overflow risk: // stakeAmount = rsrAmount * (totalStaked / rsrBacking) <= 1e29 * 1e9 = 1e38 // rsrBacking <= 1e29 (an RSR amount) // so stakeAmount * rsrBacking <= 1e67 < 2^256 uint256 rsrAmount = (stakeAmount * rsrBacking) / totalStaked; // Destroy the stRSR balance balances[account] -= stakeAmount; totalStaked -= stakeAmount; // Move RSR from backing to withdrawal-queue balance rsrBacking -= rsrAmount; // Create the corresponding withdrawal ticket uint256 index = withdrawals[account].length; uint256 lastAvailableAt = index > 0 ? withdrawals[account][index - 1].availableAt : 0; uint256 availableAt = Math.max(block.timestamp + unstakingDelay, lastAvailableAt); withdrawals[account].push(Withdrawal(account, rsrAmount, stakeAmount, availableAt)); emit UnstakingStarted(index, era, account, rsrAmount, stakeAmount, availableAt); } /// Complete delayed staking for an account, up to but not including draft ID `endId` /// @custom:interaction function withdraw(address account, uint256 endId) external interaction { IBasketHandler bh = main.basketHandler(); require(bh.fullyCapitalized(), "RToken uncapitalized"); require(bh.status() == CollateralStatus.SOUND, "basket defaulted"); Withdrawal[] storage queue = withdrawals[account]; if (endId == 0) return; require(endId <= queue.length, "index out-of-bounds"); require(queue[endId - 1].availableAt <= block.timestamp, "withdrawal unavailable"); // Call state keepers main.poke(); // Skip executed withdrawals uint256 start = 0; while (queue[start].rsrAmount == 0 && start < endId) start++; // Accumulate and zero executable withdrawals uint256 total = 0; uint256 i = start; for (; i < endId && queue[i].availableAt <= block.timestamp; i++) { total += queue[i].rsrAmount; queue[i].rsrAmount = 0; queue[i].stakeAmount = 0; } // Execute accumulated withdrawals emit UnstakingCompleted(start, i, era, account, total); main.rsr().safeTransfer(account, total); } /// Return the maximum valid value of endId such that withdraw(endId) should immediately work function endIdForWithdraw(address account) external view returns (uint256) { Withdrawal[] storage queue = withdrawals[account]; uint256 i = 0; while (i < queue.length && queue[i].availableAt <= block.timestamp) i++; return i; } /// @param rsrAmount {qRSR} /// seizedRSR might be dust-larger than rsrAmount due to rounding. /// seizedRSR will _not_ be smaller than rsrAmount. /// @custom:protected function seizeRSR(uint256 rsrAmount) external notPaused { require(_msgSender() == address(main.backingManager()), "not backing manager"); require(rsrAmount > 0, "Amount cannot be zero"); uint192 initialExchangeRate = exchangeRate(); uint256 rewards = rsrRewards(); uint256 rsrBalance = main.rsr().balanceOf(address(this)); require(rsrAmount <= rsrBalance, "Cannot seize more RSR than we hold"); // Calculate dust RSR threshold, the point at which we might as well call it a wipeout uint256 allStakes = totalStaked + stakeBeingWithdrawn(); // {qStRSR} uint256 dustRSRAmt = MIN_EXCHANGE_RATE.mulu_toUint(allStakes); // {qRSR} uint256 seizedRSR; if (rsrBalance <= rsrAmount + dustRSRAmt) { // Everyone's wiped out! Doom! Mayhem! // Zero all balances and withdrawals seizedRSR = rsrBalance; rsrBacking = 0; for (uint256 i = 0; i < accounts.length(); i++) { address account = accounts.at(i); delete withdrawals[account]; balances[account] = 0; } totalStaked = 0; era++; emit AllBalancesReset(era); } else { // Remove RSR evenly from stakers, withdrawals, and the reward pool uint256 backingToTake = (rsrBacking * rsrAmount + (rsrBalance - 1)) / rsrBalance; rsrBacking -= backingToTake; seizedRSR = backingToTake; for (uint256 i = 0; i < accounts.length(); i++) { Withdrawal[] storage queue = withdrawals[accounts.at(i)]; for (uint256 j = 0; j < queue.length; j++) { uint256 withdrawAmt = queue[j].rsrAmount; uint256 amtToTake = (withdrawAmt * rsrAmount + (rsrBalance - 1)) / rsrBalance; queue[j].rsrAmount -= amtToTake; seizedRSR += amtToTake; } } // Removing from unpaid rewards is implicit uint256 rewardsToTake = (rewards * rsrAmount + (rsrBalance - 1)) / rsrBalance; seizedRSR += rewardsToTake; assert(rsrAmount <= seizedRSR); } // Transfer RSR to caller emit ExchangeRateSet(initialExchangeRate, exchangeRate()); main.rsr().safeTransfer(_msgSender(), seizedRSR); } function exchangeRate() public view returns (uint192) { return (rsrBacking == 0 || totalStaked == 0) ? FIX_ONE : divuu(totalStaked, rsrBacking); } // ==== ERC20 Interface ==== function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return 18; } function totalSupply() external view returns (uint256) { return totalStaked; } function balanceOf(address account) external view returns (uint256) { return balances[account]; } function transfer(address to, uint256 amount) external returns (bool) { _transfer(_msgSender(), to, amount); return true; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); uint256 fromBalance = balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { balances[from] = fromBalance - amount; } balances[to] += amount; accounts.add(to); } function allowance(address owner_, address spender) public view returns (uint256) { return allowances[owner_][spender]; } function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public returns (bool) { _spendAllowance(from, _msgSender(), amount); _transfer(from, to, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { address owner_ = _msgSender(); _approve(owner_, spender, allowances[owner_][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { address owner_ = _msgSender(); uint256 currentAllowance = allowances[owner_][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner_, spender, currentAllowance - subtractedValue); } return true; } function _approve( address owner_, address spender, uint256 amount ) private { require(owner_ != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowances[owner_][spender] = amount; emit Approval(owner_, spender, amount); } function _spendAllowance( address owner_, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner_, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner_, spender, currentAllowance - amount); } } } // ==== end ERC20 Interface ==== // ==== Internal Functions ==== /// Assign reward payouts to the staker pool /// @dev do this by effecting rsrBacking and payoutLastPaid as appropriate, given the current /// value of rsrRewards() function _payoutRewards() internal { if (block.timestamp < payoutLastPaid + rewardPeriod) return; uint192 initialExchangeRate = exchangeRate(); uint32 numPeriods = (uint32(block.timestamp) - uint32(payoutLastPaid)) / uint32(rewardPeriod); // Paying out the ratio r, N times, equals paying out the ratio (1 - (1-r)^N) 1 time. uint192 payoutRatio = FIX_ONE.minus(FIX_ONE.minus(rewardRatio).powu(numPeriods)); uint256 payout = payoutRatio.mulu_toUint(rsrRewardsAtLastPayout); // Apply payout to RSR backing rsrBacking += payout; payoutLastPaid += numPeriods * rewardPeriod; rsrRewardsAtLastPayout = rsrRewards(); emit ExchangeRateSet(initialExchangeRate, exchangeRate()); } /// @return total {qStakes} Total amount of qStRSR being withdrawn function stakeBeingWithdrawn() internal view returns (uint256 total) { for (uint256 i = 0; i < accounts.length(); i++) { for (uint256 j = 0; j < withdrawals[accounts.at(i)].length; j++) { total += withdrawals[accounts.at(i)][j].stakeAmount; } } } /// @return total {qRSR} Total amount of qRSR being withdrawn function rsrBeingWithdrawn() internal view returns (uint256 total) { for (uint256 i = 0; i < accounts.length(); i++) { for (uint256 j = 0; j < withdrawals[accounts.at(i)].length; j++) { total += withdrawals[accounts.at(i)][j].rsrAmount; } } } /// @return {qRSR} The balance of RSR that this contract owns dedicated to future RSR rewards. function rsrRewards() internal view returns (uint256) { return main.rsr().balanceOf(address(this)) - rsrBacking - rsrBeingWithdrawn(); } // ==== end Internal Functions ==== // === ERC20Permit ==== // From OZ 4.4 release at commit 6bd6b76 function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode(_PERMIT_TYPEHASH, owner_, spender, value, _useNonce(owner_), deadline) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner_, "ERC20Permit: invalid signature"); _approve(owner_, spender, value); } function nonces(address owner_) public view virtual returns (uint256) { return _nonces[owner_].current(); } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparatorV4(); } function _useNonce(address owner_) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner_]; current = nonce.current(); nonce.increment(); } // ==== Gov Param Setters ==== function setUnstakingDelay(uint32 val) external governance { require(val > 0, "unstaking delay cannot be zero"); emit UnstakingDelaySet(unstakingDelay, val); unstakingDelay = val; require(rewardPeriod * 2 <= unstakingDelay, "unstakingDelay/rewardPeriod incompatible"); } function setRewardPeriod(uint32 val) external governance { emit RewardPeriodSet(rewardPeriod, val); rewardPeriod = val; require(rewardPeriod * 2 <= unstakingDelay, "unstakingDelay/rewardPeriod incompatible"); } function setRewardRatio(uint192 val) external governance { emit RewardRatioSet(rewardRatio, val); rewardRatio = val; } }
@return total {qRSR} Total amount of qRSR being withdrawn
function rsrBeingWithdrawn() internal view returns (uint256 total) { for (uint256 i = 0; i < accounts.length(); i++) { for (uint256 j = 0; j < withdrawals[accounts.at(i)].length; j++) { total += withdrawals[accounts.at(i)][j].rsrAmount; } } }
1,790,799
[ 1, 2463, 2078, 288, 85, 54, 10090, 97, 10710, 3844, 434, 1043, 54, 10090, 3832, 598, 9446, 82, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3597, 86, 1919, 310, 1190, 9446, 82, 1435, 2713, 1476, 1135, 261, 11890, 5034, 2078, 13, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 9484, 18, 2469, 5621, 277, 27245, 288, 203, 5411, 364, 261, 11890, 5034, 525, 273, 374, 31, 525, 411, 598, 9446, 1031, 63, 13739, 18, 270, 12, 77, 13, 8009, 2469, 31, 525, 27245, 288, 203, 7734, 2078, 1011, 598, 9446, 1031, 63, 13739, 18, 270, 12, 77, 13, 6362, 78, 8009, 5453, 86, 6275, 31, 203, 5411, 289, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-03 */ // SPDX-License-Identifier: MIT // 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/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: token.sol // contracts/SimpleToken.sol pragma solidity ^0.8.7; /** * @title CRI * @dev CRI is the token for Crypto International * All rights reserved by Crypto International Inc. */ contract CRI is Context, IERC20, IERC20Metadata { address private _owner; uint256 private _reward; uint256 private _reward_period; mapping (address => uint256) private _stakes; mapping (address => uint256) private _stake_ts; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Constructor that gives _msgSender() all of existing tokens. * * - `initialSupply` and `initialReward` should have the unit of 1e-18. * */ constructor ( string memory name_, string memory symbol_, uint256 initialSupply, uint256 initialReward, uint32 rewardPeriod ) { _name = name_; _symbol = symbol_; _reward = initialReward; _reward_period = rewardPeriod; _owner = _msgSender(); _mint(_msgSender(), initialSupply); } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } /** * @dev adjusts the per-day reward value per token. * * - `reward` should have the unit of 1e-18 * */ function setReward(uint256 reward) public { require(_msgSender() == _owner); _reward = reward; } /** * @dev mints new tokens. * * - `amount` specifies amount of tokens to be minted (in 1e-18). * */ function mint(uint256 amount) public { require(_msgSender() == _owner); _mint(_msgSender(), amount); } /** * @dev rewards sender rewards for holding their tokens. * * CRI wallets can choose to obtain daily reward for tokens they are * currently holding. Wallet holders can specify any amount equals to or * below their balance to get reward for. Please note that by getting * reward, the specified portion of their balance will be locked. * */ function getReward() public { require(_stake_ts[_msgSender()] <= block.timestamp - _reward_period, "CRI: need to keep stake for at least a day."); uint256 unit_reward = _stakes[_msgSender()] * _reward / 1e18; uint256 units = (block.timestamp - _stake_ts[_msgSender()]) / _reward_period; _stake_ts[_msgSender()] += units * _reward_period; _mint(_msgSender(), unit_reward * units); } /** * @dev put tokens into staking. * * CRI allows user to obtain reward by participating in staking. Users need * to explicitly add their tokens for staking to be able to receive reward. * * - `amount` specifies amount of tokens to add stake for. * */ function putStake(uint256 amount) public { require(_balances[_msgSender()] >= amount, "CRI: Not enough balance"); require(_stakes[_msgSender()] == 0, "CRI: Must empty stake first"); _stakes[_msgSender()] = amount; _stake_ts[_msgSender()] = block.timestamp; _balances[_msgSender()] -= amount; } /** * @dev retrieve tokens from staking. * * CRI allows user to obtain reward by participating in staking. Users need * to explicitly add their tokens for staking to be able to receive reward. * */ function retrieveStake() public { require(_stakes[_msgSender()] >= 0, "CRI: Empty stake"); _balances[_msgSender()] += _stakes[_msgSender()]; _stakes[_msgSender()] = 0; } /** * @dev view the amount of stake that the sender currently has. * */ function viewStake() public view returns(uint256) { return _stakes[_msgSender()]; } /** * @dev view the current reward period. * */ function viewRewardPeriod() public view returns(uint256) { return _reward_period; } /** * @dev view the currenct reward per token. * */ function viewReward() public view returns(uint256) { return _reward; } }
* @dev view the amount of stake that the sender currently has./
function viewStake() public view returns(uint256) { return _stakes[_msgSender()]; }
7,954,024
[ 1, 1945, 326, 3844, 434, 384, 911, 716, 326, 5793, 4551, 711, 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, 1476, 510, 911, 1435, 1071, 203, 1377, 1476, 203, 1377, 1135, 12, 11890, 5034, 13, 288, 203, 1377, 327, 389, 334, 3223, 63, 67, 3576, 12021, 1435, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xBe86bf5C6431565c91f30e09f63724101fF43f29/sources/SeedChef.sol
for upgrading to a new farm seamlessly.
function upgrade(uint256 _pid) external onlyOwner{ PoolInfo memory pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; lpToken.safeApprove(address(upgrader), uint256(-1)); upgrader.importFarm(address(pool.lpToken)); }
11,093,294
[ 1, 1884, 731, 15210, 358, 279, 394, 284, 4610, 695, 301, 2656, 715, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8400, 12, 11890, 5034, 389, 6610, 13, 3903, 1338, 5541, 95, 203, 3639, 8828, 966, 3778, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 467, 654, 39, 3462, 12423, 1345, 273, 2845, 18, 9953, 1345, 31, 203, 3639, 12423, 1345, 18, 4626, 12053, 537, 12, 2867, 12, 416, 22486, 3631, 2254, 5034, 19236, 21, 10019, 203, 3639, 731, 22486, 18, 5666, 42, 4610, 12, 2867, 12, 6011, 18, 9953, 1345, 10019, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0; import {D} from "./data.sol"; import {Utils} from "./utils.sol"; contract PatriciaTree { // Mapping of hash of key to value mapping (bytes32 => bytes) values; // Particia tree nodes (hash to decoded contents) mapping (bytes32 => D.Node) nodes; // The current root hash, keccak256(node(path_M('')), path_M('')) bytes32 public root; D.Edge rootEdge; function getNode(bytes32 hash) constant returns (uint, bytes32, bytes32, uint, bytes32, bytes32) { var n = nodes[hash]; return ( n.children[0].label.length, n.children[0].label.data, n.children[0].node, n.children[1].label.length, n.children[1].label.data, n.children[1].node ); } function getRootEdge() constant returns (uint, bytes32, bytes32) { return (rootEdge.label.length, rootEdge.label.data, rootEdge.node); } function edgeHash(D.Edge e) internal returns (bytes32) { return keccak256(e.node, e.label.length, e.label.data); } // Returns the hash of the encoding of a node. function hash(D.Node memory n) internal returns (bytes32) { return keccak256(edgeHash(n.children[0]), edgeHash(n.children[1])); } // Returns the Merkle-proof for the given key // Proof format should be: // - uint branchMask - bitmask with high bits at the positions in the key // where we have branch nodes (bit in key denotes direction) // - bytes32[] hashes - hashes of sibling edges function getProof(bytes key) constant returns (uint branchMask, bytes32[] _siblings) { D.Label memory k = D.Label(keccak256(key), 256); D.Edge memory e = rootEdge; bytes32[256] memory siblings; uint length; uint numSiblings; while (true) { var (prefix, suffix) = Utils.splitCommonPrefix(k, e.label); require(prefix.length == e.label.length); if (suffix.length == 0) { // Found it break; } length += prefix.length; branchMask |= uint(1) << (255 - length); length += 1; var (head, tail) = Utils.chopFirstBit(suffix); siblings[numSiblings++] = edgeHash(nodes[e.node].children[1 - head]); e = nodes[e.node].children[head]; k = tail; } if (numSiblings > 0) { _siblings = new bytes32[](numSiblings); for (uint i = 0; i < numSiblings; i++) _siblings[i] = siblings[i]; } } function verifyProof(bytes32 rootHash, bytes key, bytes value, uint branchMask, bytes32[] siblings) constant returns (bool) { D.Label memory k = D.Label(keccak256(key), 256); D.Edge memory e; e.node = keccak256(value); for (uint i = 0; branchMask != 0; i++) { uint bitSet = Utils.lowestBitSet(branchMask); branchMask &= ~(uint(1) << bitSet); (k, e.label) = Utils.splitAt(k, 255 - bitSet); uint bit; (bit, e.label) = Utils.chopFirstBit(e.label); bytes32[2] memory edgeHashes; edgeHashes[bit] = edgeHash(e); edgeHashes[1 - bit] = siblings[siblings.length - i - 1]; e.node = keccak256(edgeHashes); } e.label = k; require(rootHash == edgeHash(e)); return true; } // TODO also return the proof function insert(bytes key, bytes value) { D.Label memory k = D.Label(keccak256(key), 256); bytes32 valueHash = keccak256(value); values[valueHash] = value; // keys.push(key); D.Edge memory e; if (rootEdge.node == 0 && rootEdge.label.length == 0) { // Empty Trie e.label = k; e.node = valueHash; } else { e = insertAtEdge(rootEdge, k, valueHash); } root = edgeHash(e); rootEdge = e; } function insertAtNode(bytes32 nodeHash, D.Label key, bytes32 value) internal returns (bytes32) { require(key.length > 1); D.Node memory n = nodes[nodeHash]; var (head, tail) = Utils.chopFirstBit(key); n.children[head] = insertAtEdge(n.children[head], tail, value); return replaceNode(nodeHash, n); } function insertAtEdge(D.Edge e, D.Label key, bytes32 value) internal returns (D.Edge) { require(key.length >= e.label.length); var (prefix, suffix) = Utils.splitCommonPrefix(key, e.label); bytes32 newNodeHash; if (suffix.length == 0) { // Full match with the key, update operation newNodeHash = value; } else if (prefix.length >= e.label.length) { // Partial match, just follow the path newNodeHash = insertAtNode(e.node, suffix, value); } else { // Mismatch, so let us create a new branch node. var (head, tail) = Utils.chopFirstBit(suffix); D.Node memory branchNode; branchNode.children[head] = D.Edge(value, tail); branchNode.children[1 - head] = D.Edge(e.node, Utils.removePrefix(e.label, prefix.length + 1)); newNodeHash = insertNode(branchNode); } return D.Edge(newNodeHash, prefix); } function insertNode(D.Node memory n) internal returns (bytes32 newHash) { bytes32 h = hash(n); nodes[h].children[0] = n.children[0]; nodes[h].children[1] = n.children[1]; return h; } function replaceNode(bytes32 oldHash, D.Node memory n) internal returns (bytes32 newHash) { delete nodes[oldHash]; return insertNode(n); } } contract PatriciaTreeTest is PatriciaTree { function test() { //testInsert(); testProofs(); } function testInsert() internal { insert("one", "ONE"); insert("two", "ONE"); insert("three", "ONE"); insert("four", "ONE"); insert("five", "ONE"); insert("six", "ONE"); insert("seven", "ONE"); // update insert("one", "TWO"); } function testProofs() internal { insert("one", "ONE"); var (branchMask, siblings) = getProof("one"); verifyProof(root, "one", "ONE", branchMask, siblings); insert("two", "TWO"); (branchMask, siblings) = getProof("one"); verifyProof(root, "one", "ONE", branchMask, siblings); (branchMask, siblings) = getProof("two"); verifyProof(root, "two", "TWO", branchMask, siblings); } }
TODO also return the proof keys.push(key); Empty Trie
function insert(bytes key, bytes value) { D.Label memory k = D.Label(keccak256(key), 256); bytes32 valueHash = keccak256(value); values[valueHash] = value; D.Edge memory e; if (rootEdge.node == 0 && rootEdge.label.length == 0) { e.label = k; e.node = valueHash; } else { e = insertAtEdge(rootEdge, k, valueHash); } root = edgeHash(e); rootEdge = e; }
15,834,903
[ 1, 6241, 2546, 327, 326, 14601, 1311, 18, 6206, 12, 856, 1769, 8953, 26336, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2243, 12, 3890, 498, 16, 1731, 460, 13, 288, 203, 3639, 463, 18, 2224, 3778, 417, 273, 463, 18, 2224, 12, 79, 24410, 581, 5034, 12, 856, 3631, 8303, 1769, 203, 3639, 1731, 1578, 460, 2310, 273, 417, 24410, 581, 5034, 12, 1132, 1769, 203, 3639, 924, 63, 1132, 2310, 65, 273, 460, 31, 203, 3639, 463, 18, 6098, 3778, 425, 31, 203, 3639, 309, 261, 3085, 6098, 18, 2159, 422, 374, 597, 1365, 6098, 18, 1925, 18, 2469, 422, 374, 13, 203, 3639, 288, 203, 5411, 425, 18, 1925, 273, 417, 31, 203, 5411, 425, 18, 2159, 273, 460, 2310, 31, 203, 3639, 289, 203, 3639, 469, 203, 3639, 288, 203, 5411, 425, 273, 2243, 861, 6098, 12, 3085, 6098, 16, 417, 16, 460, 2310, 1769, 203, 3639, 289, 203, 3639, 1365, 273, 3591, 2310, 12, 73, 1769, 203, 3639, 1365, 6098, 273, 425, 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 ]
./full_match/5/0xd24e6Ff54E08Ac3Bb2A3765b67e07F1670b46Dfa/sources/contracts/ERC20Upgradeable.sol
* @dev Throws if the high bit of the balance is set to 0 indicating non denylisting/
function _requireBalanceIsDenylisted( uint256 userBalance, address denylistee ) internal view virtual { if (!_isBalanceDenylisted(userBalance)) { } }
7,057,296
[ 1, 21845, 309, 326, 3551, 2831, 434, 326, 11013, 353, 444, 358, 374, 11193, 1661, 17096, 21228, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 6528, 13937, 2520, 8517, 93, 18647, 12, 203, 3639, 2254, 5034, 729, 13937, 16, 203, 3639, 1758, 17096, 1098, 1340, 203, 565, 262, 2713, 1476, 5024, 288, 203, 3639, 309, 16051, 67, 291, 13937, 8517, 93, 18647, 12, 1355, 13937, 3719, 288, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.5; interface IERC721 { 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 ); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * Based on: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol */ contract ERC721 is ERC165, IERC721 { mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } 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; } function tokenURI(uint256 tokenId) public view virtual 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)) : ""; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } 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" ); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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" ); } 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"); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (isContract(to)) { try IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(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; } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/7f6a1666fac8ecff5dd467d0938069bc221ea9e0/contracts/utils/Address.sol function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File contracts/Editions.sol /** * @title Editions * @author MirrorXYZ */ contract Editions is ERC721 { // ============ Constants ============ string public constant name = "Mirror Editions V2"; string public constant symbol = "EDITIONS_V2"; uint256 internal constant REENTRANCY_NOT_ENTERED = 1; uint256 internal constant REENTRANCY_ENTERED = 2; // ============ Structs ============ struct Edition { // The maximum number of tokens that can be sold. uint256 quantity; // The price at which each token will be sold, in ETH. uint256 price; // The account that will receive sales revenue. address payable fundingRecipient; // The number of tokens sold so far. uint256 numSold; // The content hash of the image being presented. bytes32 contentHash; } // A subset of Edition, for efficient production of multiple editions. struct EditionTier { // The maximum number of tokens that can be sold. uint256 quantity; // The price at which each token will be sold, in ETH. uint256 price; bytes32 contentHash; } mapping(address => uint256) public fundingBalance; // ============ Immutable Storage ============ // Fee updates take 2 days to take place, giving creators time to withdraw. uint256 public immutable feeUpdateTimelock; // ============ Mutable Storage ============ string internal baseURI; // Mapping of edition id to descriptive data. mapping(uint256 => Edition) public editions; // Mapping of token id to edition id. mapping(uint256 => uint256) public tokenToEdition; // The amount of funds that have already been withdrawn for a given edition. mapping(uint256 => uint256) public withdrawnForEdition; // `nextTokenId` increments with each token purchased, globally across all editions. uint256 private nextTokenId; // Editions start at 1, in order that unsold tokens don't map to the first edition. uint256 private nextEditionId = 1; // Withdrawals include a fee, specified as a percentage. uint16 public feePercent; // The address that holds fees. address payable public treasury; uint256 public feesAccrued; // Timelock information. uint256 public nextFeeUpdateTime; uint16 public nextFeePercent; // Reentrancy uint256 internal reentrancyStatus; address public owner; address public nextOwner; // ============ Events ============ event EditionCreated( uint256 quantity, uint256 price, address fundingRecipient, uint256 indexed editionId, bytes32 contentHash ); event EditionPurchased( uint256 indexed editionId, uint256 indexed tokenId, // `numSold` at time of purchase represents the "serial number" of the NFT. uint256 numSold, uint256 amountPaid, // The account that paid for and received the NFT. address indexed buyer ); event FundsWithdrawn( address fundingRecipient, uint256 amountWithdrawn, uint256 feeAmount ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event FeesWithdrawn(uint256 feesAccrued, address sender); event FeeUpdateQueued(uint256 newFee, address sender); event FeeUpdated(uint256 feePercent, address sender); // ============ Modifiers ============ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(reentrancyStatus != REENTRANCY_ENTERED, "Reentrant call"); // Any calls to nonReentrant after this point will fail reentrancyStatus = REENTRANCY_ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) reentrancyStatus = REENTRANCY_NOT_ENTERED; } modifier onlyOwner() { require(isOwner(), "caller is not the owner."); _; } modifier onlyNextOwner() { require(isNextOwner(), "current owner must set caller as next owner."); _; } // ============ Constructor ============ constructor( string memory baseURI_, address payable treasury_, uint16 initialFee, uint256 feeUpdateTimelock_, address owner_ ) { baseURI = baseURI_; treasury = treasury_; feePercent = initialFee; feeUpdateTimelock = feeUpdateTimelock_; owner = owner_; } // ============ Edition Methods ============ function createEditionTiers( EditionTier[] memory tiers, address payable fundingRecipient ) external nonReentrant { // Execute a loop that creates editions. for (uint8 i = 0; i < tiers.length; i++) { uint256 quantity = tiers[i].quantity; uint256 price = tiers[i].price; bytes32 contentHash = tiers[i].contentHash; editions[nextEditionId] = Edition({ quantity: quantity, price: price, fundingRecipient: fundingRecipient, numSold: 0, contentHash: contentHash }); emit EditionCreated( quantity, price, fundingRecipient, nextEditionId, contentHash ); nextEditionId++; } } function createEdition( // The number of tokens that can be minted and sold. uint256 quantity, // The price to purchase a token. uint256 price, // The account that should receive the revenue. address payable fundingRecipient, // Content hash is emitted in the event, for UI convenience. bytes32 contentHash ) external nonReentrant { editions[nextEditionId] = Edition({ quantity: quantity, price: price, fundingRecipient: fundingRecipient, numSold: 0, contentHash: contentHash }); emit EditionCreated( quantity, price, fundingRecipient, nextEditionId, contentHash ); nextEditionId++; } function buyEdition(uint256 editionId) external payable nonReentrant { // Check that the edition exists. Note: this is redundant // with the next check, but it is useful for clearer error messaging. require(editions[editionId].quantity > 0, "Edition does not exist"); // Check that there are still tokens available to purchase. require( editions[editionId].numSold < editions[editionId].quantity, "This edition is already sold out." ); // Check that the sender is paying the correct amount. require( msg.value >= editions[editionId].price, "Must send enough to purchase the edition." ); // Increment the number of tokens sold for this edition. editions[editionId].numSold++; fundingBalance[editions[editionId].fundingRecipient] += msg.value; // Mint a new token for the sender, using the `nextTokenId`. _mint(msg.sender, nextTokenId); // Store the mapping of token id to the edition being purchased. tokenToEdition[nextTokenId] = editionId; emit EditionPurchased( editionId, nextTokenId, editions[editionId].numSold, msg.value, msg.sender ); nextTokenId++; } // ============ Operational Methods ============ function withdrawFunds(address payable fundingRecipient) external nonReentrant { uint256 remaining = fundingBalance[fundingRecipient]; fundingBalance[fundingRecipient] = 0; if (feePercent > 0) { // Send the amount that was remaining for the edition, to the funding recipient. uint256 fee = computeFee(remaining); // Allocate fee to the treasury. feesAccrued += fee; // Send the remainder to the funding recipient. _sendFunds(fundingRecipient, remaining - fee); emit FundsWithdrawn(fundingRecipient, remaining - fee, fee); } else { _sendFunds(fundingRecipient, remaining); emit FundsWithdrawn(fundingRecipient, remaining, 0); } } function computeFee(uint256 _amount) public view returns (uint256) { return (_amount * feePercent) / 100; } // ============ Admin Methods ============ function withdrawFees() public { _sendFunds(treasury, feesAccrued); emit FeesWithdrawn(feesAccrued, msg.sender); feesAccrued = 0; } function updateTreasury(address payable newTreasury) public { require(msg.sender == treasury, "Only available to current treasury"); treasury = newTreasury; } function queueFeeUpdate(uint16 newFee) public { require(msg.sender == treasury, "Only available to treasury"); nextFeeUpdateTime = block.timestamp + feeUpdateTimelock; nextFeePercent = newFee; emit FeeUpdateQueued(newFee, msg.sender); } function executeFeeUpdate() public { require(msg.sender == treasury, "Only available to current treasury"); require( block.timestamp >= nextFeeUpdateTime, "Timelock hasn't elapsed" ); feePercent = nextFeePercent; nextFeePercent = 0; nextFeeUpdateTime = 0; emit FeeUpdated(feePercent, msg.sender); } function changeBaseURI(string memory baseURI_) public onlyOwner { baseURI = baseURI_; } function isOwner() public view returns (bool) { return msg.sender == owner; } function isNextOwner() public view returns (bool) { return msg.sender == nextOwner; } function transferOwnership(address nextOwner_) external onlyOwner { require(nextOwner_ != address(0), "Next owner is the zero address."); nextOwner = nextOwner_; } function cancelOwnershipTransfer() external onlyOwner { delete nextOwner; } function acceptOwnership() external onlyNextOwner { delete nextOwner; emit OwnershipTransferred(owner, msg.sender); owner = msg.sender; } function renounceOwnership() external onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } // ============ NFT Methods ============ // Returns e.g. https://mirror-api.com/editions/[editionId]/[tokenId] function tokenURI(uint256 tokenId) public view override returns (string memory) { // If the token does not map to an edition, it'll be 0. require(tokenToEdition[tokenId] > 0, "Token has not been sold yet"); // Concatenate the components, baseURI, editionId and tokenId, to create URI. return string( abi.encodePacked( baseURI, _toString(tokenToEdition[tokenId]), "/", _toString(tokenId) ) ); } // The hash of the given content for the NFT. Can be used // for IPFS storage, verifying authenticity, etc. function contentHash(uint256 tokenId) public view returns (bytes32) { // If the token does not map to an edition, it'll be 0. require(tokenToEdition[tokenId] > 0, "Token has not been sold yet"); // Concatenate the components, baseURI, editionId and tokenId, to create URI. return editions[tokenToEdition[tokenId]].contentHash; } // Returns e.g. https://mirror-api.com/editions/metadata function contractURI() public view returns (string memory) { // Concatenate the components, baseURI, editionId and tokenId, to create URI. return string(abi.encodePacked(baseURI, "metadata")); } function getRoyaltyRecipient(uint256 tokenId) public view returns (address) { require(tokenToEdition[tokenId] > 0, "Token has not been minted yet"); return editions[tokenToEdition[tokenId]].fundingRecipient; } function setRoyaltyRecipient( uint256 editionId, address payable newFundingRecipient ) public { require( editions[editionId].fundingRecipient == msg.sender, "Only current fundingRecipient can modify its value" ); editions[editionId].fundingRecipient = newFundingRecipient; } // ============ Private Methods ============ function _sendFunds(address payable recipient, uint256 amount) private { require( address(this).balance >= amount, "Insufficient balance for send" ); (bool success, ) = recipient.call{value: amount}(""); require(success, "Unable to send value: recipient may have reverted"); } // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol 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); } }
* @title Editions @author MirrorXYZ/ ============ Constants ============ ============ Structs ============
contract Editions is ERC721 { string public constant name = "Mirror Editions V2"; string public constant symbol = "EDITIONS_V2"; uint256 internal constant REENTRANCY_NOT_ENTERED = 1; uint256 internal constant REENTRANCY_ENTERED = 2; struct Edition { uint256 quantity; uint256 price; address payable fundingRecipient; uint256 numSold; bytes32 contentHash; } struct EditionTier { uint256 quantity; uint256 price; bytes32 contentHash; } mapping(address => uint256) public fundingBalance; string internal baseURI; uint256 public feesAccrued; uint16 public nextFeePercent; address public owner; address public nextOwner; event EditionCreated( uint256 quantity, uint256 price, address fundingRecipient, uint256 indexed editionId, bytes32 contentHash ); event EditionPurchased( uint256 indexed editionId, uint256 indexed tokenId, uint256 amountPaid, ); event FundsWithdrawn( address fundingRecipient, uint256 amountWithdrawn, uint256 feeAmount ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event FeesWithdrawn(uint256 feesAccrued, address sender); event FeeUpdateQueued(uint256 newFee, address sender); event FeeUpdated(uint256 feePercent, address sender); uint256 public immutable feeUpdateTimelock; mapping(uint256 => Edition) public editions; mapping(uint256 => uint256) public tokenToEdition; mapping(uint256 => uint256) public withdrawnForEdition; uint256 private nextTokenId; uint256 private nextEditionId = 1; uint16 public feePercent; address payable public treasury; uint256 public nextFeeUpdateTime; uint256 internal reentrancyStatus; uint256 numSold, address indexed buyer modifier nonReentrant() { require(reentrancyStatus != REENTRANCY_ENTERED, "Reentrant call"); reentrancyStatus = REENTRANCY_ENTERED; _; reentrancyStatus = REENTRANCY_NOT_ENTERED; } modifier onlyOwner() { require(isOwner(), "caller is not the owner."); _; } modifier onlyNextOwner() { require(isNextOwner(), "current owner must set caller as next owner."); _; } constructor( string memory baseURI_, address payable treasury_, uint16 initialFee, uint256 feeUpdateTimelock_, address owner_ ) { baseURI = baseURI_; treasury = treasury_; feePercent = initialFee; feeUpdateTimelock = feeUpdateTimelock_; owner = owner_; } function createEditionTiers( EditionTier[] memory tiers, address payable fundingRecipient ) external nonReentrant { for (uint8 i = 0; i < tiers.length; i++) { uint256 quantity = tiers[i].quantity; uint256 price = tiers[i].price; bytes32 contentHash = tiers[i].contentHash; editions[nextEditionId] = Edition({ quantity: quantity, price: price, fundingRecipient: fundingRecipient, numSold: 0, contentHash: contentHash }); emit EditionCreated( quantity, price, fundingRecipient, nextEditionId, contentHash ); nextEditionId++; } } function createEditionTiers( EditionTier[] memory tiers, address payable fundingRecipient ) external nonReentrant { for (uint8 i = 0; i < tiers.length; i++) { uint256 quantity = tiers[i].quantity; uint256 price = tiers[i].price; bytes32 contentHash = tiers[i].contentHash; editions[nextEditionId] = Edition({ quantity: quantity, price: price, fundingRecipient: fundingRecipient, numSold: 0, contentHash: contentHash }); emit EditionCreated( quantity, price, fundingRecipient, nextEditionId, contentHash ); nextEditionId++; } } function createEditionTiers( EditionTier[] memory tiers, address payable fundingRecipient ) external nonReentrant { for (uint8 i = 0; i < tiers.length; i++) { uint256 quantity = tiers[i].quantity; uint256 price = tiers[i].price; bytes32 contentHash = tiers[i].contentHash; editions[nextEditionId] = Edition({ quantity: quantity, price: price, fundingRecipient: fundingRecipient, numSold: 0, contentHash: contentHash }); emit EditionCreated( quantity, price, fundingRecipient, nextEditionId, contentHash ); nextEditionId++; } } function createEdition( uint256 quantity, uint256 price, address payable fundingRecipient, bytes32 contentHash ) external nonReentrant { editions[nextEditionId] = Edition({ quantity: quantity, price: price, fundingRecipient: fundingRecipient, numSold: 0, contentHash: contentHash }); emit EditionCreated( quantity, price, fundingRecipient, nextEditionId, contentHash ); nextEditionId++; } function createEdition( uint256 quantity, uint256 price, address payable fundingRecipient, bytes32 contentHash ) external nonReentrant { editions[nextEditionId] = Edition({ quantity: quantity, price: price, fundingRecipient: fundingRecipient, numSold: 0, contentHash: contentHash }); emit EditionCreated( quantity, price, fundingRecipient, nextEditionId, contentHash ); nextEditionId++; } function buyEdition(uint256 editionId) external payable nonReentrant { require(editions[editionId].quantity > 0, "Edition does not exist"); require( editions[editionId].numSold < editions[editionId].quantity, "This edition is already sold out." ); require( msg.value >= editions[editionId].price, "Must send enough to purchase the edition." ); editions[editionId].numSold++; fundingBalance[editions[editionId].fundingRecipient] += msg.value; _mint(msg.sender, nextTokenId); tokenToEdition[nextTokenId] = editionId; emit EditionPurchased( editionId, nextTokenId, editions[editionId].numSold, msg.value, msg.sender ); nextTokenId++; } function withdrawFunds(address payable fundingRecipient) external nonReentrant { uint256 remaining = fundingBalance[fundingRecipient]; fundingBalance[fundingRecipient] = 0; if (feePercent > 0) { uint256 fee = computeFee(remaining); feesAccrued += fee; _sendFunds(fundingRecipient, remaining - fee); emit FundsWithdrawn(fundingRecipient, remaining - fee, fee); _sendFunds(fundingRecipient, remaining); emit FundsWithdrawn(fundingRecipient, remaining, 0); } } function withdrawFunds(address payable fundingRecipient) external nonReentrant { uint256 remaining = fundingBalance[fundingRecipient]; fundingBalance[fundingRecipient] = 0; if (feePercent > 0) { uint256 fee = computeFee(remaining); feesAccrued += fee; _sendFunds(fundingRecipient, remaining - fee); emit FundsWithdrawn(fundingRecipient, remaining - fee, fee); _sendFunds(fundingRecipient, remaining); emit FundsWithdrawn(fundingRecipient, remaining, 0); } } } else { function computeFee(uint256 _amount) public view returns (uint256) { return (_amount * feePercent) / 100; } function withdrawFees() public { _sendFunds(treasury, feesAccrued); emit FeesWithdrawn(feesAccrued, msg.sender); feesAccrued = 0; } function updateTreasury(address payable newTreasury) public { require(msg.sender == treasury, "Only available to current treasury"); treasury = newTreasury; } function queueFeeUpdate(uint16 newFee) public { require(msg.sender == treasury, "Only available to treasury"); nextFeeUpdateTime = block.timestamp + feeUpdateTimelock; nextFeePercent = newFee; emit FeeUpdateQueued(newFee, msg.sender); } function executeFeeUpdate() public { require(msg.sender == treasury, "Only available to current treasury"); require( block.timestamp >= nextFeeUpdateTime, "Timelock hasn't elapsed" ); feePercent = nextFeePercent; nextFeePercent = 0; nextFeeUpdateTime = 0; emit FeeUpdated(feePercent, msg.sender); } function changeBaseURI(string memory baseURI_) public onlyOwner { baseURI = baseURI_; } function isOwner() public view returns (bool) { return msg.sender == owner; } function isNextOwner() public view returns (bool) { return msg.sender == nextOwner; } function transferOwnership(address nextOwner_) external onlyOwner { require(nextOwner_ != address(0), "Next owner is the zero address."); nextOwner = nextOwner_; } function cancelOwnershipTransfer() external onlyOwner { delete nextOwner; } function acceptOwnership() external onlyNextOwner { delete nextOwner; emit OwnershipTransferred(owner, msg.sender); owner = msg.sender; } function renounceOwnership() external onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(tokenToEdition[tokenId] > 0, "Token has not been sold yet"); return string( abi.encodePacked( baseURI, _toString(tokenToEdition[tokenId]), "/", _toString(tokenId) ) ); } function contentHash(uint256 tokenId) public view returns (bytes32) { require(tokenToEdition[tokenId] > 0, "Token has not been sold yet"); return editions[tokenToEdition[tokenId]].contentHash; } function contractURI() public view returns (string memory) { return string(abi.encodePacked(baseURI, "metadata")); } function getRoyaltyRecipient(uint256 tokenId) public view returns (address) { require(tokenToEdition[tokenId] > 0, "Token has not been minted yet"); return editions[tokenToEdition[tokenId]].fundingRecipient; } function setRoyaltyRecipient( uint256 editionId, address payable newFundingRecipient ) public { require( editions[editionId].fundingRecipient == msg.sender, "Only current fundingRecipient can modify its value" ); editions[editionId].fundingRecipient = newFundingRecipient; } function _sendFunds(address payable recipient, uint256 amount) private { require( address(this).balance >= amount, "Insufficient balance for send" ); require(success, "Unable to send value: recipient may have reverted"); } (bool success, ) = recipient.call{value: amount}(""); function _toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function _toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function _toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function _toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
239,226
[ 1, 41, 1460, 87, 225, 490, 8299, 23479, 19, 422, 1432, 631, 5245, 422, 1432, 631, 422, 1432, 631, 7362, 87, 422, 1432, 631, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 512, 1460, 87, 353, 4232, 39, 27, 5340, 288, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 13035, 512, 1460, 87, 776, 22, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 2056, 7022, 55, 67, 58, 22, 14432, 203, 203, 565, 2254, 5034, 2713, 5381, 2438, 2222, 54, 1258, 16068, 67, 4400, 67, 12278, 2056, 273, 404, 31, 203, 565, 2254, 5034, 2713, 5381, 2438, 2222, 54, 1258, 16068, 67, 12278, 2056, 273, 576, 31, 203, 203, 203, 203, 565, 1958, 512, 1460, 288, 203, 3639, 2254, 5034, 10457, 31, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 1758, 8843, 429, 22058, 18241, 31, 203, 3639, 2254, 5034, 818, 55, 1673, 31, 203, 3639, 1731, 1578, 913, 2310, 31, 203, 565, 289, 203, 203, 565, 1958, 512, 1460, 15671, 288, 203, 3639, 2254, 5034, 10457, 31, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 1731, 1578, 913, 2310, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 22058, 13937, 31, 203, 203, 203, 565, 533, 2713, 1026, 3098, 31, 203, 565, 2254, 5034, 1071, 1656, 281, 8973, 86, 5957, 31, 203, 565, 2254, 2313, 1071, 1024, 14667, 8410, 31, 203, 203, 565, 1758, 1071, 3410, 31, 203, 565, 1758, 1071, 1024, 5541, 31, 203, 203, 565, 871, 512, 1460, 6119, 12, 203, 3639, 2254, 5034, 10457, 16, 203, 3639, 2254, 5034, 6205, 16, 203, 3639, 1758, 22058, 18241, 16, 203, 3639, 2254, 5034, 8808, 28432, 548, 16, 203, 3639, 1731, 1578, 913, 2310, 203, 565, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./interfaces/IERC20.sol"; import "./interfaces/ILockManager.sol"; import "./lib/SafeMath.sol"; import "./lib/SafeERC20.sol"; /** * @title Vault * @dev Contract for locking up tokens for set periods of time * + optionally providing locked tokens with voting power */ contract Vault { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice lockManager contract ILockManager public lockManager; /// @notice Lock definition struct Lock { address token; address receiver; uint48 startTime; uint16 vestingDurationInDays; uint16 cliffDurationInDays; uint256 amount; uint256 amountClaimed; uint256 votingPower; } /// @notice Lock balance definition struct LockBalance { uint256 id; uint256 claimableAmount; Lock lock; } ///@notice Token balance definition struct TokenBalance { uint256 totalAmount; uint256 claimableAmount; uint256 claimedAmount; uint256 votingPower; } /// @dev Used to translate lock periods specified in days to seconds uint256 constant internal SECONDS_PER_DAY = 86400; /// @notice Mapping of lock id > token locks mapping (uint256 => Lock) public tokenLocks; /// @notice Mapping of address to lock id mapping (address => uint256[]) public lockIds; ///@notice Number of locks uint256 public numLocks; /// @notice Event emitted when a new lock is created event LockCreated(address indexed token, address indexed locker, address indexed receiver, uint256 lockId, uint256 amount, uint48 startTime, uint16 durationInDays, uint16 cliffInDays, uint256 votingPower); /// @notice Event emitted when tokens are claimed by a receiver from an unlocked balance event UnlockedTokensClaimed(address indexed receiver, address indexed token, uint256 indexed lockId, uint256 amountClaimed, uint256 votingPowerRemoved); /// @notice Event emitted when lock duration extended event LockExtended(uint256 indexed lockId, uint16 indexed oldDuration, uint16 indexed newDuration, uint16 oldCliff, uint16 newCliff, uint48 startTime); /** * @notice Create a new Vault contract */ constructor(address _lockManager) { lockManager = ILockManager(_lockManager); } /** * @notice Lock tokens, optionally providing voting power * @param locker The account that is locking tokens * @param receiver The account that will be able to retrieve unlocked tokens * @param startTime The unix timestamp when the lock period will start * @param amount The amount of tokens being locked * @param vestingDurationInDays The vesting period in days * @param cliffDurationInDays The cliff duration in days * @param grantVotingPower if true, give user voting power from tokens */ function lockTokens( address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 vestingDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower ) external { require(vestingDurationInDays > 0, "Vault::lockTokens: vesting duration must be > 0"); require(vestingDurationInDays <= 25*365, "Vault::lockTokens: vesting duration more than 25 years"); require(vestingDurationInDays >= cliffDurationInDays, "Vault::lockTokens: vesting duration < cliff"); require(amount > 0, "Vault::lockTokens: amount not > 0"); _lockTokens(token, locker, receiver, startTime, amount, vestingDurationInDays, cliffDurationInDays, grantVotingPower); } /** * @notice Lock tokens, using permit for approval * @dev It is up to the frontend developer to ensure the token implements permit - otherwise this will fail * @param token Address of token to lock * @param locker The account that is locking tokens * @param receiver The account that will be able to retrieve unlocked tokens * @param startTime The unix timestamp when the lock period will start * @param amount The amount of tokens being locked * @param vestingDurationInDays The lock period in days * @param cliffDurationInDays The lock cliff duration in days * @param grantVotingPower if true, give user voting power from tokens * @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 lockTokensWithPermit( address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 vestingDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(vestingDurationInDays > 0, "Vault::lockTokensWithPermit: vesting duration must be > 0"); require(vestingDurationInDays <= 25*365, "Vault::lockTokensWithPermit: vesting duration more than 25 years"); require(vestingDurationInDays >= cliffDurationInDays, "Vault::lockTokensWithPermit: duration < cliff"); require(amount > 0, "Vault::lockTokensWithPermit: amount not > 0"); // Set approval using permit signature IERC20(token).permit(locker, address(this), amount, deadline, v, r, s); _lockTokens(token, locker, receiver, startTime, amount, vestingDurationInDays, cliffDurationInDays, grantVotingPower); } /** * @notice Get all active token lock ids * @return the lock ids */ function allActiveLockIds() external view returns(uint256[] memory){ uint256 activeCount; // Get number of active locks for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` uint256[] memory result = new uint256[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { result[j] = i; j++; } } return result; } /** * @notice Get all active token locks * @return the locks */ function allActiveLocks() external view returns(Lock[] memory){ uint256 activeCount; // Get number of active locks for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` Lock[] memory result = new Lock[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { result[j] = lock; j++; } } return result; } /** * @notice Get all active token lock balances * @return the active lock balances */ function allActiveLockBalances() external view returns(LockBalance[] memory){ uint256 activeCount; // Get number of active locks for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` LockBalance[] memory result = new LockBalance[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { result[j] = lockBalance(i); j++; } } return result; } /** * @notice Get all active token lock ids for receiver * @param receiver The address that has locked balances * @return the active lock ids */ function activeLockIds(address receiver) external view returns(uint256[] memory){ uint256 activeCount; uint256[] memory receiverLockIds = lockIds[receiver]; // Get number of active locks for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` uint256[] memory result = new uint256[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { result[j] = receiverLockIds[i]; j++; } } return result; } /** * @notice Get all token locks for receiver * @param receiver The address that has locked balances * @return the locks */ function allLocks(address receiver) external view returns(Lock[] memory){ uint256[] memory allLockIds = lockIds[receiver]; Lock[] memory result = new Lock[](allLockIds.length); for (uint256 i; i < allLockIds.length; i++) { result[i] = tokenLocks[allLockIds[i]]; } return result; } /** * @notice Get all active token locks for receiver * @param receiver The address that has locked balances * @return the locks */ function activeLocks(address receiver) external view returns(Lock[] memory){ uint256 activeCount; uint256[] memory receiverLockIds = lockIds[receiver]; // Get number of active locks for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` Lock[] memory result = new Lock[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { result[j] = tokenLocks[receiverLockIds[i]]; j++; } } return result; } /** * @notice Get all active token lock balances for receiver * @param receiver The address that has locked balances * @return the active lock balances */ function activeLockBalances(address receiver) external view returns(LockBalance[] memory){ uint256 activeCount; uint256[] memory receiverLockIds = lockIds[receiver]; // Get number of active locks for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` LockBalance[] memory result = new LockBalance[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { result[j] = lockBalance(receiverLockIds[i]); j++; } } return result; } /** * @notice Get total token balance * @param token The token to check * @return balance the total active balance of `token` */ function totalTokenBalance(address token) external view returns(TokenBalance memory balance){ for (uint256 i; i < numLocks; i++) { Lock memory tokenLock = tokenLocks[i]; if(tokenLock.token == token && tokenLock.amount != tokenLock.amountClaimed){ balance.totalAmount = balance.totalAmount.add(tokenLock.amount); balance.votingPower = balance.votingPower.add(tokenLock.votingPower); if(block.timestamp > tokenLock.startTime) { balance.claimedAmount = balance.claimedAmount.add(tokenLock.amountClaimed); uint256 elapsedTime = block.timestamp.sub(tokenLock.startTime); uint256 elapsedDays = elapsedTime.div(SECONDS_PER_DAY); if ( elapsedDays >= tokenLock.cliffDurationInDays ) { if (elapsedDays >= tokenLock.vestingDurationInDays) { balance.claimableAmount = balance.claimableAmount.add(tokenLock.amount).sub(tokenLock.amountClaimed); } else { uint256 vestingDurationInSecs = uint256(tokenLock.vestingDurationInDays).mul(SECONDS_PER_DAY); uint256 vestingAmountPerSec = tokenLock.amount.div(vestingDurationInSecs); uint256 amountVested = vestingAmountPerSec.mul(elapsedTime); balance.claimableAmount = balance.claimableAmount.add(amountVested.sub(tokenLock.amountClaimed)); } } } } } } /** * @notice Get token balance of receiver * @param token The token to check * @param receiver The address that has unlocked balances * @return balance the total active balance of `token` for `receiver` */ function tokenBalance(address token, address receiver) external view returns(TokenBalance memory balance){ uint256[] memory receiverLockIds = lockIds[receiver]; for (uint256 i; i < receiverLockIds.length; i++) { Lock memory receiverLock = tokenLocks[receiverLockIds[i]]; if(receiverLock.token == token && receiverLock.amount != receiverLock.amountClaimed){ balance.totalAmount = balance.totalAmount.add(receiverLock.amount); balance.votingPower = balance.votingPower.add(receiverLock.votingPower); if(block.timestamp > receiverLock.startTime) { balance.claimedAmount = balance.claimedAmount.add(receiverLock.amountClaimed); uint256 elapsedTime = block.timestamp.sub(receiverLock.startTime); uint256 elapsedDays = elapsedTime.div(SECONDS_PER_DAY); if ( elapsedDays >= receiverLock.cliffDurationInDays ) { if (elapsedDays >= receiverLock.vestingDurationInDays) { balance.claimableAmount = balance.claimableAmount.add(receiverLock.amount).sub(receiverLock.amountClaimed); } else { uint256 vestingDurationInSecs = uint256(receiverLock.vestingDurationInDays).mul(SECONDS_PER_DAY); uint256 vestingAmountPerSec = receiverLock.amount.div(vestingDurationInSecs); uint256 amountVested = vestingAmountPerSec.mul(elapsedTime); balance.claimableAmount = balance.claimableAmount.add(amountVested.sub(receiverLock.amountClaimed)); } } } } } } /** * @notice Get lock balance for a given lock id * @param lockId The lock ID * @return balance the lock balance */ function lockBalance(uint256 lockId) public view returns (LockBalance memory balance) { balance.id = lockId; balance.claimableAmount = claimableBalance(lockId); balance.lock = tokenLocks[lockId]; } /** * @notice Get claimable balance for a given lock id * @dev Returns 0 if cliff duration has not ended * @param lockId The lock ID * @return The amount that can be claimed */ function claimableBalance(uint256 lockId) public view returns (uint256) { Lock storage lock = tokenLocks[lockId]; // For locks created with a future start date, that hasn't been reached, return 0 if (block.timestamp < lock.startTime) { return 0; } uint256 elapsedTime = block.timestamp.sub(lock.startTime); uint256 elapsedDays = elapsedTime.div(SECONDS_PER_DAY); if (elapsedDays < lock.cliffDurationInDays) { return 0; } if (elapsedDays >= lock.vestingDurationInDays) { return lock.amount.sub(lock.amountClaimed); } else { uint256 vestingDurationInSecs = uint256(lock.vestingDurationInDays).mul(SECONDS_PER_DAY); uint256 vestingAmountPerSec = lock.amount.div(vestingDurationInSecs); uint256 amountVested = vestingAmountPerSec.mul(elapsedTime); return amountVested.sub(lock.amountClaimed); } } /** * @notice Allows receiver to claim all of their unlocked tokens for a set of locks * @dev Errors if no tokens are claimable * @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this * @param locks The lock ids for unlocked token balances */ function claimAllUnlockedTokens(uint256[] memory locks) external { for (uint i = 0; i < locks.length; i++) { uint256 claimableAmount = claimableBalance(locks[i]); require(claimableAmount > 0, "Vault::claimAllUnlockedTokens: claimableAmount is 0"); _claimTokens(locks[i], claimableAmount); } } /** * @notice Allows receiver to claim a portion of their unlocked tokens for a given lock * @dev Errors if token amounts provided are > claimable amounts * @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this * @param locks The lock ids for unlocked token balances * @param amounts The amount of each unlocked token to claim */ function claimUnlockedTokenAmounts(uint256[] memory locks, uint256[] memory amounts) external { require(locks.length == amounts.length, "Vault::claimUnlockedTokenAmounts: arrays must be same length"); for (uint i = 0; i < locks.length; i++) { uint256 claimableAmount = claimableBalance(locks[i]); require(claimableAmount >= amounts[i], "Vault::claimUnlockedTokenAmounts: claimableAmount < amount"); _claimTokens(locks[i], amounts[i]); } } /** * @notice Allows receiver extend lock periods for a given lock * @param lockId The lock id for a locked token balance * @param vestingDaysToAdd The number of days to add to vesting duration * @param cliffDaysToAdd The number of days to add to cliff duration */ function extendLock(uint256 lockId, uint16 vestingDaysToAdd, uint16 cliffDaysToAdd) external { Lock storage lock = tokenLocks[lockId]; require(msg.sender == lock.receiver, "Vault::extendLock: msg.sender must be receiver"); uint16 oldVestingDuration = lock.vestingDurationInDays; uint16 newVestingDuration = _add16(oldVestingDuration, vestingDaysToAdd, "Vault::extendLock: vesting max days exceeded"); uint16 oldCliffDuration = lock.cliffDurationInDays; uint16 newCliffDuration = _add16(oldCliffDuration, cliffDaysToAdd, "Vault::extendLock: cliff max days exceeded"); require(newCliffDuration <= 10*365, "Vault::extendLock: cliff more than 10 years"); require(newVestingDuration <= 25*365, "Vault::extendLock: vesting duration more than 25 years"); require(newVestingDuration >= newCliffDuration, "Vault::extendLock: duration < cliff"); lock.vestingDurationInDays = newVestingDuration; emit LockExtended(lockId, oldVestingDuration, newVestingDuration, oldCliffDuration, newCliffDuration, lock.startTime); } /** * @notice Internal implementation of lockTokens * @param locker The account that is locking tokens * @param receiver The account that will be able to retrieve unlocked tokens * @param startTime The unix timestamp when the lock period will start * @param amount The amount of tokens being locked * @param vestingDurationInDays The vesting period in days * @param cliffDurationInDays The cliff duration in days * @param grantVotingPower if true, give user voting power from tokens */ function _lockTokens( address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 vestingDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower ) internal { // Transfer the tokens under the control of the vault contract IERC20(token).safeTransferFrom(locker, address(this), amount); uint48 lockStartTime = startTime == 0 ? uint48(block.timestamp) : startTime; uint256 votingPowerGranted; // Grant voting power, if specified if(grantVotingPower) { votingPowerGranted = lockManager.grantVotingPower(receiver, token, amount); } // Create lock Lock memory lock = Lock({ token: token, receiver: receiver, startTime: lockStartTime, vestingDurationInDays: vestingDurationInDays, cliffDurationInDays: cliffDurationInDays, amount: amount, amountClaimed: 0, votingPower: votingPowerGranted }); tokenLocks[numLocks] = lock; lockIds[receiver].push(numLocks); emit LockCreated(token, locker, receiver, numLocks, amount, lockStartTime, vestingDurationInDays, cliffDurationInDays, votingPowerGranted); // Increment lock id numLocks++; } /** * @notice Internal implementation of token claims * @param lockId The lock id for claim * @param claimAmount The amount to claim */ function _claimTokens(uint256 lockId, uint256 claimAmount) internal { Lock storage lock = tokenLocks[lockId]; uint256 votingPowerRemoved; // Remove voting power, if exists if (lock.votingPower > 0) { votingPowerRemoved = lockManager.removeVotingPower(lock.receiver, lock.token, claimAmount); lock.votingPower = lock.votingPower.sub(votingPowerRemoved); } // Update claimed amount lock.amountClaimed = lock.amountClaimed.add(claimAmount); // Release tokens IERC20(lock.token).safeTransfer(lock.receiver, claimAmount); emit UnlockedTokensClaimed(lock.receiver, lock.token, lockId, claimAmount, votingPowerRemoved); } /** * @notice Adds uint16 to uint16 safely * @param a First number * @param b Second number * @param errorMessage Error message to use if numbers cannot be added * @return uint16 number */ function _add16(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { uint16 c = a + b; require(c >= a, errorMessage); return c; } }
@notice Lock balance definition
struct LockBalance { uint256 id; uint256 claimableAmount; Lock lock; }
6,484,949
[ 1, 2531, 11013, 2379, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 3488, 13937, 288, 203, 3639, 2254, 5034, 612, 31, 203, 3639, 2254, 5034, 7516, 429, 6275, 31, 203, 3639, 3488, 2176, 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 ]
/** CrazyVibez (CVZ) is launching April 13, 2022 The launch is powered by Dexvibez and guarantees you a safe token play. More info at t.me/Dexvibez */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library 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); } } } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface 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 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 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 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 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 implementation contract CVZ is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; 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; address[] private _excluded; mapping (address => bool) private _isProtected; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'CrazyVibez (by Dexvibez)'; string private _symbol = 'CVZ'; uint8 private _decimals = 9; uint256 private _taxFee = 10; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamFee = _teamFee; address payable public _teamWalletAddress; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable teamWalletAddress, address payable marketingWalletAddress) public { _teamWalletAddress = teamWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } 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) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public 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 excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function protectAccount(address account) external onlyOwner() { _isProtected[account] = true; } function releaseAccount(address account) external onlyOwner() { _isProtected[account] = false; } function protectAccounts(address[] calldata accounts) external onlyOwner() { for (uint256 i = 0; i < accounts.length; i++) { _isProtected[accounts[i]]= true; } } function removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousTeamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousTeamFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToTeam(uint256 amount) private { _teamWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { require (!_isProtected[sender]); if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _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); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); 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 _getTaxFee() private view returns(uint256) { return _taxFee; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25'); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _teamFee = teamFee; } }
Contract implementation
contract CVZ is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; 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; address[] private _excluded; mapping (address => bool) private _isProtected; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'CrazyVibez (by Dexvibez)'; string private _symbol = 'CVZ'; uint8 private _decimals = 9; uint256 private _taxFee = 10; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamFee = _teamFee; address payable public _teamWalletAddress; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable teamWalletAddress, address payable marketingWalletAddress) public { _teamWalletAddress = teamWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } 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) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { 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 excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function protectAccount(address account) external onlyOwner() { _isProtected[account] = true; } function releaseAccount(address account) external onlyOwner() { _isProtected[account] = false; } function protectAccounts(address[] calldata accounts) external onlyOwner() { for (uint256 i = 0; i < accounts.length; i++) { _isProtected[accounts[i]]= true; } } function protectAccounts(address[] calldata accounts) external onlyOwner() { for (uint256 i = 0; i < accounts.length; i++) { _isProtected[accounts[i]]= true; } } function removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousTeamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousTeamFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToTeam(uint256 amount) private { _teamWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { require (!_isProtected[sender]); if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { require (!_isProtected[sender]); if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _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); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); 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 _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 _getTaxFee() private view returns(uint256) { return _taxFee; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25'); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _teamFee = teamFee; } }
1,474,938
[ 1, 8924, 4471, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6835, 385, 58, 62, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 3639, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 3639, 1450, 5267, 364, 1758, 31, 203, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 3639, 1758, 8526, 3238, 389, 24602, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 15933, 31, 203, 540, 203, 3639, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 3639, 2254, 5034, 3238, 389, 88, 5269, 273, 15088, 9449, 380, 1728, 636, 29, 31, 203, 3639, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 3639, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 203, 3639, 533, 3238, 389, 529, 273, 296, 39, 354, 21832, 58, 495, 6664, 261, 1637, 463, 338, 90, 495, 6664, 2506, 31, 203, 3639, 533, 3238, 389, 7175, 273, 296, 22007, 62, 13506, 203, 3639, 2254, 28, 3238, 389, 31734, 273, 2468, 31, 203, 540, 203, 3639, 2254, 5034, 3238, 389, 8066, 14667, 273, 1728, 31, 7010, 3639, 2 ]
pragma solidity ^0.5.16; import "./VToken.sol"; import "./PriceOracle.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./VAIControllerStorage.sol"; import "./VAIUnitroller.sol"; import "./VAI/VAI.sol"; interface ComptrollerLensInterface { function protocolPaused() external view returns (bool); function mintedVAIs(address account) external view returns (uint); function vaiMintRate() external view returns (uint); function venusVAIRate() external view returns (uint); function venusAccrued(address account) external view returns(uint); function getAssetsIn(address account) external view returns (VToken[] memory); function oracle() external view returns (PriceOracle); function distributeVAIMinterVenus(address vaiMinter, bool distributeAll) external; } /** * @title Venus's VAI Comptroller Contract * @author Venus */ contract VAIController is VAIControllerStorage, VAIControllerErrorReporter, Exponential { /// @notice Emitted when Comptroller is changed event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when VAI is minted */ event MintVAI(address minter, uint mintVAIAmount); /** * @notice Event emitted when VAI is repaid */ event RepayVAI(address repayer, uint repayVAIAmount); /// @notice The initial Venus index for a market uint224 public constant venusInitialIndex = 1e36; /*** Main Actions ***/ function mintVAI(uint mintVAIAmount) external returns (uint) { if(address(comptroller) != address(0)) { require(!ComptrollerLensInterface(address(comptroller)).protocolPaused(), "protocol is paused"); address minter = msg.sender; // Keep the flywheel moving updateVenusVAIMintIndex(); ComptrollerLensInterface(address(comptroller)).distributeVAIMinterVenus(minter, false); uint oErr; MathError mErr; uint accountMintVAINew; uint accountMintableVAI; (oErr, accountMintableVAI) = getMintableVAI(minter); if (oErr != uint(Error.NO_ERROR)) { return uint(Error.REJECTION); } // check that user have sufficient mintableVAI balance if (mintVAIAmount > accountMintableVAI) { return fail(Error.REJECTION, FailureInfo.VAI_MINT_REJECTION); } (mErr, accountMintVAINew) = addUInt(ComptrollerLensInterface(address(comptroller)).mintedVAIs(minter), mintVAIAmount); require(mErr == MathError.NO_ERROR, "VAI_MINT_AMOUNT_CALCULATION_FAILED"); uint error = comptroller.setMintedVAIOf(minter, accountMintVAINew); if (error != 0 ) { return error; } VAI(getVAIAddress()).mint(minter, mintVAIAmount); emit MintVAI(minter, mintVAIAmount); return uint(Error.NO_ERROR); } } /** * @notice Repay VAI */ function repayVAI(uint repayVAIAmount) external returns (uint) { if(address(comptroller) != address(0)) { require(!ComptrollerLensInterface(address(comptroller)).protocolPaused(), "protocol is paused"); address repayer = msg.sender; updateVenusVAIMintIndex(); ComptrollerLensInterface(address(comptroller)).distributeVAIMinterVenus(repayer, false); uint actualBurnAmount; uint vaiBalance = ComptrollerLensInterface(address(comptroller)).mintedVAIs(repayer); if(vaiBalance > repayVAIAmount) { actualBurnAmount = repayVAIAmount; } else { actualBurnAmount = vaiBalance; } uint error = comptroller.setMintedVAIOf(repayer, vaiBalance - actualBurnAmount); if (error != 0) { return error; } VAI(getVAIAddress()).burn(repayer, actualBurnAmount); emit RepayVAI(repayer, actualBurnAmount); return uint(Error.NO_ERROR); } } /** * @notice Initialize the VenusVAIState */ function _initializeVenusVAIState(uint blockNumber) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } if (isVenusVAIInitialized == false) { isVenusVAIInitialized = true; uint vaiBlockNumber = blockNumber == 0 ? getBlockNumber() : blockNumber; venusVAIState = VenusVAIState({ index: venusInitialIndex, block: safe32(vaiBlockNumber, "block number overflows") }); } } /** * @notice Accrue XVS to by updating the VAI minter index */ function updateVenusVAIMintIndex() public returns (uint) { uint vaiMinterSpeed = ComptrollerLensInterface(address(comptroller)).venusVAIRate(); uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(venusVAIState.block)); if (deltaBlocks > 0 && vaiMinterSpeed > 0) { uint vaiAmount = VAI(getVAIAddress()).totalSupply(); uint venusAccrued = mul_(deltaBlocks, vaiMinterSpeed); Double memory ratio = vaiAmount > 0 ? fraction(venusAccrued, vaiAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: venusVAIState.index}), ratio); venusVAIState = VenusVAIState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { venusVAIState.block = safe32(blockNumber, "block number overflows"); } } /** * @notice Calculate XVS accrued by a VAI minter * @param vaiMinter The address of the VAI minter to distribute XVS to */ function calcDistributeVAIMinterVenus(address vaiMinter) public returns(uint, uint, uint, uint) { // Check caller is comptroller if (msg.sender != address(comptroller)) { return (fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK), 0, 0, 0); } Double memory vaiMintIndex = Double({mantissa: venusVAIState.index}); Double memory vaiMinterIndex = Double({mantissa: venusVAIMinterIndex[vaiMinter]}); venusVAIMinterIndex[vaiMinter] = vaiMintIndex.mantissa; if (vaiMinterIndex.mantissa == 0 && vaiMintIndex.mantissa > 0) { vaiMinterIndex.mantissa = venusInitialIndex; } Double memory deltaIndex = sub_(vaiMintIndex, vaiMinterIndex); uint vaiMinterAmount = ComptrollerLensInterface(address(comptroller)).mintedVAIs(vaiMinter); uint vaiMinterDelta = mul_(vaiMinterAmount, deltaIndex); uint vaiMinterAccrued = add_(ComptrollerLensInterface(address(comptroller)).venusAccrued(vaiMinter), vaiMinterDelta); return (uint(Error.NO_ERROR), vaiMinterAccrued, vaiMinterDelta, vaiMintIndex.mantissa); } /*** Admin Functions ***/ /** * @notice Sets a new comptroller * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface comptroller_) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; comptroller = comptroller_; emit NewComptroller(oldComptroller, comptroller_); return uint(Error.NO_ERROR); } function _become(VAIUnitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @dev Local vars for avoiding stack-depth limits in calculating account total supply balance. * Note that `vTokenBalance` is the number of vTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountAmountLocalVars { uint totalSupplyAmount; uint sumSupply; uint sumBorrowPlusEffects; uint vTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } function getMintableVAI(address minter) public view returns (uint, uint) { PriceOracle oracle = ComptrollerLensInterface(address(comptroller)).oracle(); VToken[] memory enteredMarkets = ComptrollerLensInterface(address(comptroller)).getAssetsIn(minter); AccountAmountLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; uint accountMintableVAI; uint i; /** * We use this formula to calculate mintable VAI amount. * totalSupplyAmount * VAIMintRate - (totalBorrowAmount + mintedVAIOf) */ for (i = 0; i < enteredMarkets.length; i++) { (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = enteredMarkets[i].getAccountSnapshot(minter); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (uint(Error.SNAPSHOT_ERROR), 0); } vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(enteredMarkets[i]); if (vars.oraclePriceMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); (mErr, vars.tokensToDenom) = mulExp(vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } // sumSupply += tokensToDenom * vTokenBalance (mErr, vars.sumSupply) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.vTokenBalance, vars.sumSupply); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } } (mErr, vars.sumBorrowPlusEffects) = addUInt(vars.sumBorrowPlusEffects, ComptrollerLensInterface(address(comptroller)).mintedVAIs(minter)); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mErr, accountMintableVAI) = mulUInt(vars.sumSupply, ComptrollerLensInterface(address(comptroller)).vaiMintRate()); require(mErr == MathError.NO_ERROR, "VAI_MINT_AMOUNT_CALCULATION_FAILED"); (mErr, accountMintableVAI) = divUInt(accountMintableVAI, 10000); require(mErr == MathError.NO_ERROR, "VAI_MINT_AMOUNT_CALCULATION_FAILED"); (mErr, accountMintableVAI) = subUInt(accountMintableVAI, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (uint(Error.REJECTION), 0); } return (uint(Error.NO_ERROR), accountMintableVAI); } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the VAI token * @return The address of VAI */ function getVAIAddress() public view returns (address) { return 0x4BD17003473389A42DAF6a0a729f6Fdb328BbBd7; } }
* We use this formula to calculate mintable VAI amount. totalSupplyAmount VAIMintRate - (totalBorrowAmount + mintedVAIOf)/
function getMintableVAI(address minter) public view returns (uint, uint) { PriceOracle oracle = ComptrollerLensInterface(address(comptroller)).oracle(); VToken[] memory enteredMarkets = ComptrollerLensInterface(address(comptroller)).getAssetsIn(minter); uint oErr; MathError mErr; uint accountMintableVAI; uint i; for (i = 0; i < enteredMarkets.length; i++) { (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = enteredMarkets[i].getAccountSnapshot(minter); return (uint(Error.SNAPSHOT_ERROR), 0); } if (vars.oraclePriceMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } (mErr, vars.tokensToDenom) = mulExp(vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } } (mErr, vars.sumBorrowPlusEffects) = addUInt(vars.sumBorrowPlusEffects, ComptrollerLensInterface(address(comptroller)).mintedVAIs(minter));
12,816,679
[ 1, 3218, 999, 333, 8013, 358, 4604, 312, 474, 429, 776, 18194, 3844, 18, 2078, 3088, 1283, 6275, 225, 776, 37, 3445, 474, 4727, 300, 261, 4963, 38, 15318, 6275, 397, 312, 474, 329, 58, 18194, 951, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2108, 474, 429, 58, 18194, 12, 2867, 1131, 387, 13, 1071, 1476, 1135, 261, 11890, 16, 2254, 13, 288, 203, 3639, 20137, 23601, 20865, 273, 1286, 337, 1539, 48, 773, 1358, 12, 2867, 12, 832, 337, 1539, 13, 2934, 280, 16066, 5621, 203, 3639, 776, 1345, 8526, 3778, 16219, 3882, 2413, 273, 1286, 337, 1539, 48, 773, 1358, 12, 2867, 12, 832, 337, 1539, 13, 2934, 588, 10726, 382, 12, 1154, 387, 1769, 203, 203, 203, 3639, 2254, 320, 2524, 31, 203, 3639, 2361, 668, 312, 2524, 31, 203, 203, 3639, 2254, 2236, 49, 474, 429, 58, 18194, 31, 203, 3639, 2254, 277, 31, 203, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 411, 16219, 3882, 2413, 18, 2469, 31, 277, 27245, 288, 203, 5411, 261, 83, 2524, 16, 4153, 18, 90, 1345, 13937, 16, 4153, 18, 70, 15318, 13937, 16, 4153, 18, 16641, 4727, 49, 970, 21269, 13, 273, 16219, 3882, 2413, 63, 77, 8009, 588, 3032, 4568, 12, 1154, 387, 1769, 203, 7734, 327, 261, 11890, 12, 668, 18, 13653, 31667, 67, 3589, 3631, 374, 1769, 203, 5411, 289, 203, 203, 5411, 309, 261, 4699, 18, 280, 16066, 5147, 49, 970, 21269, 422, 374, 13, 288, 203, 7734, 327, 261, 11890, 12, 668, 18, 7698, 1441, 67, 3589, 3631, 374, 1769, 203, 5411, 289, 203, 203, 5411, 261, 81, 2524, 16, 4153, 18, 7860, 774, 8517, 362, 13, 273, 14064, 2966, 12, 4699, 18, 16641, 4727, 16, 4153, 18, 280, 16066, 5147, 1769, 203, 5411, 309, 261, 81, 2524, 2 ]
pragma solidity 0.4.25; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } } 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; } } contract DecoBaseProjectsMarketplace is Ownable { using SafeMath for uint256; // `DecoRelay` contract address. address public relayContractAddress; /** * @dev Payble fallback for reverting transactions of any incoming ETH. */ function () public payable { require(msg.value == 0, "Blocking any incoming ETH."); } /** * @dev Set the new address of the `DecoRelay` contract. * @param _newAddress An address of the new contract. */ function setRelayContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Relay address must not be 0x0."); relayContractAddress = _newAddress; } /** * @dev Allows to trasnfer any ERC20 tokens from the contract balance to owner's address. * @param _tokenAddress An `address` of an ERC20 token. * @param _tokens An `uint` tokens amount. * @return A `bool` operation result state. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { IERC20 token = IERC20(_tokenAddress); return token.transfer(owner(), _tokens); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /// @title Contract to store other contracts newest versions addresses and service information. contract DecoRelay is DecoBaseProjectsMarketplace { address public projectsContractAddress; address public milestonesContractAddress; address public escrowFactoryContractAddress; address public arbitrationContractAddress; address public feesWithdrawalAddress; uint8 public shareFee; function setProjectsContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); projectsContractAddress = _newAddress; } function setMilestonesContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); milestonesContractAddress = _newAddress; } function setEscrowFactoryContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); escrowFactoryContractAddress = _newAddress; } function setArbitrationContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); arbitrationContractAddress = _newAddress; } function setFeesWithdrawalAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); feesWithdrawalAddress = _newAddress; } function setShareFee(uint8 _shareFee) external onlyOwner { require(_shareFee <= 100, "Deconet share fee must be less than 100%."); shareFee = _shareFee; } } /** * @title Escrow contract, every project deploys a clone and transfer ownership to the project client, so all * funds not reserved to pay for a milestone can be safely moved in/out. */ contract DecoEscrow is DecoBaseProjectsMarketplace { using SafeMath for uint256; // Indicates if the current clone has been initialized. bool internal isInitialized; // Stores share fee that should apply on any successful distribution. uint8 public shareFee; // Authorized party for executing funds distribution operations. address public authorizedAddress; // State variable to track available ETH Escrow owner balance. // Anything that is not blocked or distributed in favor of any party can be withdrawn by the owner. uint public balance; // Mapping of available for withdrawal funds by the address. // Accounted amounts are excluded from the `balance`. mapping (address => uint) public withdrawalAllowanceForAddress; // Maps information about the amount of deposited ERC20 token to the token address. mapping(address => uint) public tokensBalance; /** * Mapping of ERC20 tokens amounts to token addresses that are available for withdrawal for a given address. * Accounted here amounts are excluded from the `tokensBalance`. */ mapping(address => mapping(address => uint)) public tokensWithdrawalAllowanceForAddress; // ETH amount blocked in Escrow. // `balance` excludes this amount. uint public blockedBalance; // Mapping of the amount of ERC20 tokens to the the token address that are blocked in Escrow. // A token value in `tokensBalance` excludes stored here amount. mapping(address => uint) public blockedTokensBalance; // Logged when an operation with funds occurred. event FundsOperation ( address indexed sender, address indexed target, address tokenAddress, uint amount, PaymentType paymentType, OperationType indexed operationType ); // Logged when the given address authorization to distribute Escrow funds changed. event FundsDistributionAuthorization ( address targetAddress, bool isAuthorized ); // Accepted types of payments. enum PaymentType { Ether, Erc20 } // Possible operations with funds. enum OperationType { Receive, Send, Block, Unblock, Distribute } // Restrict function call to be originated from an address that was authorized to distribute funds. modifier onlyAuthorized() { require(authorizedAddress == msg.sender, "Only authorized addresses allowed."); _; } /** * @dev Default `payable` fallback to accept incoming ETH from any address. */ function () public payable { deposit(); } /** * @dev Initialize the Escrow clone with default values. * @param _newOwner An address of a new escrow owner. * @param _authorizedAddress An address that will be stored as authorized. */ function initialize( address _newOwner, address _authorizedAddress, uint8 _shareFee, address _relayContractAddress ) external { require(!isInitialized, "Only uninitialized contracts allowed."); isInitialized = true; authorizedAddress = _authorizedAddress; emit FundsDistributionAuthorization(_authorizedAddress, true); _transferOwnership(_newOwner); shareFee = _shareFee; relayContractAddress = _relayContractAddress; } /** * @dev Start transfering the given amount of the ERC20 tokens available by provided address. * @param _tokenAddress ERC20 token contract address. * @param _amount Amount to transfer from sender`s address. */ function depositErc20(address _tokenAddress, uint _amount) external { require(_tokenAddress != address(0x0), "Token Address shouldn't be 0x0."); IERC20 token = IERC20(_tokenAddress); require( token.transferFrom(msg.sender, address(this), _amount), "Transfer operation should be successful." ); tokensBalance[_tokenAddress] = tokensBalance[_tokenAddress].add(_amount); emit FundsOperation ( msg.sender, address(this), _tokenAddress, _amount, PaymentType.Erc20, OperationType.Receive ); } /** * @dev Withdraw the given amount of ETH to sender`s address if allowance or contract balance is sufficient. * @param _amount Amount to withdraw. */ function withdraw(uint _amount) external { withdrawForAddress(msg.sender, _amount); } /** * @dev Withdraw the given amount of ERC20 token to sender`s address if allowance or contract balance is sufficient. * @param _tokenAddress ERC20 token address. * @param _amount Amount to withdraw. */ function withdrawErc20(address _tokenAddress, uint _amount) external { withdrawErc20ForAddress(msg.sender, _tokenAddress, _amount); } /** * @dev Block funds for future use by authorized party stored in `authorizedAddress`. * @param _amount An uint of Wei to be blocked. */ function blockFunds(uint _amount) external onlyAuthorized { require(_amount <= balance, "Amount to block should be less or equal than balance."); balance = balance.sub(_amount); blockedBalance = blockedBalance.add(_amount); emit FundsOperation ( address(this), msg.sender, address(0x0), _amount, PaymentType.Ether, OperationType.Block ); } /** * @dev Blocks ERC20 tokens funds for future use by authorized party listed in `authorizedAddress`. * @param _tokenAddress An address of ERC20 token. * @param _amount An uint of tokens to be blocked. */ function blockTokenFunds(address _tokenAddress, uint _amount) external onlyAuthorized { uint accountedTokensBalance = tokensBalance[_tokenAddress]; require( _amount <= accountedTokensBalance, "Tokens mount to block should be less or equal than balance." ); tokensBalance[_tokenAddress] = accountedTokensBalance.sub(_amount); blockedTokensBalance[_tokenAddress] = blockedTokensBalance[_tokenAddress].add(_amount); emit FundsOperation ( address(this), msg.sender, _tokenAddress, _amount, PaymentType.Erc20, OperationType.Block ); } /** * @dev Distribute funds between contract`s balance and allowance for some address. * Deposit may be returned back to the contract address, i.e. to the escrow owner. * Or deposit may flow to the allowance for an address as a result of an evidence * given by an authorized party about fullfilled obligations. * **IMPORTANT** This operation includes fees deduction. * @param _destination Destination address for funds distribution. * @param _amount Amount to distribute in favor of a destination address. */ function distributeFunds( address _destination, uint _amount ) external onlyAuthorized { require( _amount <= blockedBalance, "Amount to distribute should be less or equal than blocked balance." ); uint amount = _amount; if (shareFee > 0 && relayContractAddress != address(0x0)) { DecoRelay relayContract = DecoRelay(relayContractAddress); address feeDestination = relayContract.feesWithdrawalAddress(); uint fee = amount.mul(shareFee).div(100); amount = amount.sub(fee); blockedBalance = blockedBalance.sub(fee); withdrawalAllowanceForAddress[feeDestination] = withdrawalAllowanceForAddress[feeDestination].add(fee); emit FundsOperation( msg.sender, feeDestination, address(0x0), fee, PaymentType.Ether, OperationType.Distribute ); } if (_destination == owner()) { unblockFunds(amount); return; } blockedBalance = blockedBalance.sub(amount); withdrawalAllowanceForAddress[_destination] = withdrawalAllowanceForAddress[_destination].add(amount); emit FundsOperation( msg.sender, _destination, address(0x0), amount, PaymentType.Ether, OperationType.Distribute ); } /** * @dev Distribute ERC20 token funds between contract`s balance and allowanc for some address. * Deposit may be returned back to the contract address, i.e. to the escrow owner. * Or deposit may flow to the allowance for an address as a result of an evidence * given by authorized party about fullfilled obligations. * **IMPORTANT** This operation includes fees deduction. * @param _destination Destination address for funds distribution. * @param _tokenAddress ERC20 Token address. * @param _amount Amount to distribute in favor of a destination address. */ function distributeTokenFunds( address _destination, address _tokenAddress, uint _amount ) external onlyAuthorized { require( _amount <= blockedTokensBalance[_tokenAddress], "Amount to distribute should be less or equal than blocked balance." ); uint amount = _amount; if (shareFee > 0 && relayContractAddress != address(0x0)) { DecoRelay relayContract = DecoRelay(relayContractAddress); address feeDestination = relayContract.feesWithdrawalAddress(); uint fee = amount.mul(shareFee).div(100); amount = amount.sub(fee); blockedTokensBalance[_tokenAddress] = blockedTokensBalance[_tokenAddress].sub(fee); uint allowance = tokensWithdrawalAllowanceForAddress[feeDestination][_tokenAddress]; tokensWithdrawalAllowanceForAddress[feeDestination][_tokenAddress] = allowance.add(fee); emit FundsOperation( msg.sender, feeDestination, _tokenAddress, fee, PaymentType.Erc20, OperationType.Distribute ); } if (_destination == owner()) { unblockTokenFunds(_tokenAddress, amount); return; } blockedTokensBalance[_tokenAddress] = blockedTokensBalance[_tokenAddress].sub(amount); uint allowanceForSender = tokensWithdrawalAllowanceForAddress[_destination][_tokenAddress]; tokensWithdrawalAllowanceForAddress[_destination][_tokenAddress] = allowanceForSender.add(amount); emit FundsOperation( msg.sender, _destination, _tokenAddress, amount, PaymentType.Erc20, OperationType.Distribute ); } /** * @dev Withdraws ETH amount from the contract's balance to the provided address. * @param _targetAddress An `address` for transfer ETH to. * @param _amount An `uint` amount to be transfered. */ function withdrawForAddress(address _targetAddress, uint _amount) public { require( _amount <= address(this).balance, "Amount to withdraw should be less or equal than balance." ); if (_targetAddress == owner()) { balance = balance.sub(_amount); } else { uint withdrawalAllowance = withdrawalAllowanceForAddress[_targetAddress]; withdrawalAllowanceForAddress[_targetAddress] = withdrawalAllowance.sub(_amount); } _targetAddress.transfer(_amount); emit FundsOperation ( address(this), _targetAddress, address(0x0), _amount, PaymentType.Ether, OperationType.Send ); } /** * @dev Withdraws ERC20 token amount from the contract's balance to the provided address. * @param _targetAddress An `address` for transfer tokens to. * @param _tokenAddress An `address` of ERC20 token. * @param _amount An `uint` amount of ERC20 tokens to be transfered. */ function withdrawErc20ForAddress(address _targetAddress, address _tokenAddress, uint _amount) public { IERC20 token = IERC20(_tokenAddress); require( _amount <= token.balanceOf(this), "Token amount to withdraw should be less or equal than balance." ); if (_targetAddress == owner()) { tokensBalance[_tokenAddress] = tokensBalance[_tokenAddress].sub(_amount); } else { uint tokenWithdrawalAllowance = getTokenWithdrawalAllowance(_targetAddress, _tokenAddress); tokensWithdrawalAllowanceForAddress[_targetAddress][_tokenAddress] = tokenWithdrawalAllowance.sub( _amount ); } token.transfer(_targetAddress, _amount); emit FundsOperation ( address(this), _targetAddress, _tokenAddress, _amount, PaymentType.Erc20, OperationType.Send ); } /** * @dev Returns allowance for withdrawing the given token for sender address. * @param _tokenAddress An address of ERC20 token. * @return An uint value of allowance. */ function getTokenWithdrawalAllowance(address _account, address _tokenAddress) public view returns(uint) { return tokensWithdrawalAllowanceForAddress[_account][_tokenAddress]; } /** * @dev Accept and account incoming deposit in contract state. */ function deposit() public payable { require(msg.value > 0, "Deposited amount should be greater than 0."); balance = balance.add(msg.value); emit FundsOperation ( msg.sender, address(this), address(0x0), msg.value, PaymentType.Ether, OperationType.Receive ); } /** * @dev Unblock blocked funds and make them available to the contract owner. * @param _amount An uint of Wei to be unblocked. */ function unblockFunds(uint _amount) public onlyAuthorized { require( _amount <= blockedBalance, "Amount to unblock should be less or equal than balance" ); blockedBalance = blockedBalance.sub(_amount); balance = balance.add(_amount); emit FundsOperation ( msg.sender, address(this), address(0x0), _amount, PaymentType.Ether, OperationType.Unblock ); } /** * @dev Unblock blocked token funds and make them available to the contract owner. * @param _amount An uint of Wei to be unblocked. */ function unblockTokenFunds(address _tokenAddress, uint _amount) public onlyAuthorized { uint accountedBlockedTokensAmount = blockedTokensBalance[_tokenAddress]; require( _amount <= accountedBlockedTokensAmount, "Tokens amount to unblock should be less or equal than balance" ); blockedTokensBalance[_tokenAddress] = accountedBlockedTokensAmount.sub(_amount); tokensBalance[_tokenAddress] = tokensBalance[_tokenAddress].add(_amount); emit FundsOperation ( msg.sender, address(this), _tokenAddress, _amount, PaymentType.Erc20, OperationType.Unblock ); } /** * @dev Override base contract logic to block this operation for Escrow contract. * @param _tokenAddress An `address` of an ERC20 token. * @param _tokens An `uint` tokens amount. * @return A `bool` operation result state. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { return false; } } contract CloneFactory { event CloneCreated(address indexed target, address clone); function createClone(address target) internal returns (address result) { bytes memory clone = hex"600034603b57603080600f833981f36000368180378080368173bebebebebebebebebebebebebebebebebebebebe5af43d82803e15602c573d90f35b3d90fd"; bytes20 targetBytes = bytes20(target); for (uint i = 0; i < 20; i++) { clone[26 + i] = targetBytes[i]; } assembly { let len := mload(clone) let data := add(clone, 0x20) result := create(0, data, len) } } } /** * @title Utility contract that provides a way to execute cheap clone deployment of the DecoEscrow contract * on chain. */ contract DecoEscrowFactory is DecoBaseProjectsMarketplace, CloneFactory { // Escrow master-contract address. address public libraryAddress; // Logged when a new Escrow clone is deployed to the chain. event EscrowCreated(address newEscrowAddress); /** * @dev Constructor for the contract. * @param _libraryAddress Escrow master-contract address. */ constructor(address _libraryAddress) public { libraryAddress = _libraryAddress; } /** * @dev Updates library address with the given value. * @param _libraryAddress Address of a new base contract. */ function setLibraryAddress(address _libraryAddress) external onlyOwner { require(libraryAddress != _libraryAddress); require(_libraryAddress != address(0x0)); libraryAddress = _libraryAddress; } /** * @dev Create Escrow clone. * @param _ownerAddress An address of the Escrow contract owner. * @param _authorizedAddress An addresses that is going to be authorized in Escrow contract. */ function createEscrow( address _ownerAddress, address _authorizedAddress ) external returns(address) { address clone = createClone(libraryAddress); DecoRelay relay = DecoRelay(relayContractAddress); DecoEscrow(clone).initialize( _ownerAddress, _authorizedAddress, relay.shareFee(), relayContractAddress ); emit EscrowCreated(clone); return clone; } } contract IDecoArbitrationTarget { /** * @dev Prepare arbitration target for a started dispute. * @param _idHash A `bytes32` hash of id. */ function disputeStartedFreeze(bytes32 _idHash) public; /** * @dev React to an active dispute settlement with given parameters. * @param _idHash A `bytes32` hash of id. * @param _respondent An `address` of a respondent. * @param _respondentShare An `uint8` share for the respondent. * @param _initiator An `address` of a dispute initiator. * @param _initiatorShare An `uint8` share for the initiator. * @param _isInternal A `bool` indicating if dispute was settled by participants without an arbiter. * @param _arbiterWithdrawalAddress An `address` for sending out arbiter compensation. */ function disputeSettledTerminate( bytes32 _idHash, address _respondent, uint8 _respondentShare, address _initiator, uint8 _initiatorShare, bool _isInternal, address _arbiterWithdrawalAddress ) public; /** * @dev Check eligibility of a given address to perform operations. * @param _idHash A `bytes32` hash of id. * @param _addressToCheck An `address` to check. * @return A `bool` check status. */ function checkEligibility(bytes32 _idHash, address _addressToCheck) public view returns(bool); /** * @dev Check if target is ready for a dispute. * @param _idHash A `bytes32` hash of id. * @return A `bool` check status. */ function canStartDispute(bytes32 _idHash) public view returns(bool); } 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; } } interface IDecoArbitration { /** * @dev Should be logged upon dispute start. */ event LogStartedDispute( address indexed sender, bytes32 indexed idHash, uint timestamp, int respondentShareProposal ); /** * @dev Should be logged upon proposal rejection. */ event LogRejectedProposal( address indexed sender, bytes32 indexed idHash, uint timestamp, uint8 rejectedProposal ); /** * @dev Should be logged upon dispute settlement. */ event LogSettledDispute( address indexed sender, bytes32 indexed idHash, uint timestamp, uint8 respondentShare, uint8 initiatorShare ); /** * @dev Should be logged when contract owner updates fees. */ event LogFeesUpdated( uint timestamp, uint fixedFee, uint8 shareFee ); /** * @dev Should be logged when time limit to accept/reject proposal for respondent is updated. */ event LogProposalTimeLimitUpdated( uint timestamp, uint proposalActionTimeLimit ); /** * @dev Should be logged when the withdrawal address for the contract owner changed. */ event LogWithdrawalAddressChanged( uint timestamp, address newWithdrawalAddress ); /** * @notice Start dispute for the given project. * @dev This call should log event and save dispute information and notify `IDecoArbitrationTarget` object * about started dispute. Dipsute can be started only if target instance call of * `canStartDispute` method confirms that state is valid. Also, txn sender and respondent addresses * eligibility must be confirmed by arbitation target `checkEligibility` method call. * @param _idHash A `bytes32` hash of a project id. * @param _respondent An `address` of the second paty involved in the dispute. * @param _respondentShareProposal An `int` value indicating percentage of disputed funds * proposed to the respondent. Valid values range is 0-100, different values are considered as 'No Proposal'. * When provided percentage is 100 then this dispute is processed automatically, * and all funds are distributed in favor of the respondent. */ function startDispute(bytes32 _idHash, address _respondent, int _respondentShareProposal) external; /** * @notice Accept active dispute proposal, sender should be the respondent. * @dev Respondent of a dispute can accept existing proposal and if proposal exists then `settleDispute` * method should be called with proposal value. Time limit for respondent to accept/reject proposal * must not be exceeded. * @param _idHash A `bytes32` hash of a project id. */ function acceptProposal(bytes32 _idHash) external; /** * @notice Reject active dispute proposal and escalate dispute. * @dev Txn sender should be dispute's respondent. Dispute automatically gets escalated to this contract * owner aka arbiter. Proposal must exist, otherwise this method should do nothing. When respondent * rejects proposal then it should get removed and corresponding event should be logged. * There should be a time limit for a respondent to reject a given proposal, and if it is overdue * then arbiter should take on a dispute to settle it. * @param _idHash A `bytes32` hash of a project id. */ function rejectProposal(bytes32 _idHash) external; /** * @notice Settle active dispute. * @dev Sender should be the current contract or its owner(arbiter). Action is possible only when there is no active * proposal or time to accept the proposal is over. Sum of shares should be 100%. Should notify target * instance about a dispute settlement via `disputeSettledTerminate` method call. Also corresponding * event must be emitted. * @param _idHash A `bytes32` hash of a project id. * @param _respondentShare An `uint` percents of respondent share. * @param _initiatorShare An `uint` percents of initiator share. */ function settleDispute(bytes32 _idHash, uint _respondentShare, uint _initiatorShare) external; /** * @return Retuns this arbitration contract withdrawal `address`. */ function getWithdrawalAddress() external view returns(address); /** * @return The arbitration contract fixed `uint` fee and `uint8` share of all disputed funds fee. */ function getFixedAndShareFees() external view returns(uint, uint8); /** * @return An `uint` time limit for accepting/rejecting a proposal by respondent. */ function getTimeLimitForReplyOnProposal() external view returns(uint); } pragma solidity 0.4.25; /// @title Contract for Project events and actions handling. contract DecoProjects is DecoBaseProjectsMarketplace { using SafeMath for uint256; using ECDSA for bytes32; // struct for project details struct Project { string agreementId; address client; address maker; address arbiter; address escrowContractAddress; uint startDate; uint endDate; uint8 milestoneStartWindow; uint8 feedbackWindow; uint8 milestonesCount; uint8 customerSatisfaction; uint8 makerSatisfaction; bool agreementsEncrypted; } struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } struct Proposal { string agreementId; address arbiter; } bytes32 constant private EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 constant private PROPOSAL_TYPEHASH = keccak256( "Proposal(string agreementId,address arbiter)" ); bytes32 private DOMAIN_SEPARATOR; // enumeration to describe possible project states for easier state changes reporting. enum ProjectState { Active, Completed, Terminated } // enumeration to describe possible satisfaction score types. enum ScoreType { CustomerSatisfaction, MakerSatisfaction } // Logged when a project state changes. event LogProjectStateUpdate ( bytes32 indexed agreementHash, address updatedBy, uint timestamp, ProjectState state ); // Logged when either party sets satisfaction score after the completion of a project. event LogProjectRated ( bytes32 indexed agreementHash, address indexed ratedBy, address indexed ratingTarget, uint8 rating, uint timestamp ); // maps the agreement`s unique hash to the project details. mapping (bytes32 => Project) public projects; // maps hashes of all maker's projects to the maker's address. mapping (address => bytes32[]) public makerProjects; // maps hashes of all client's projects to the client's address. mapping (address => bytes32[]) public clientProjects; // maps arbiter's fixed fee to a project. mapping (bytes32 => uint) public projectArbiterFixedFee; // maps arbiter's share fee to a project. mapping (bytes32 => uint8) public projectArbiterShareFee; // Modifier to restrict method to be called either by project`s owner or maker modifier eitherClientOrMaker(bytes32 _agreementHash) { Project memory project = projects[_agreementHash]; require( project.client == msg.sender || project.maker == msg.sender, "Only project owner or maker can perform this operation." ); _; } // Modifier to restrict method to be called either by project`s owner or maker modifier eitherClientOrMakerOrMilestoneContract(bytes32 _agreementHash) { Project memory project = projects[_agreementHash]; DecoRelay relay = DecoRelay(relayContractAddress); require( project.client == msg.sender || project.maker == msg.sender || relay.milestonesContractAddress() == msg.sender, "Only project owner or maker can perform this operation." ); _; } // Modifier to restrict method to be called by the milestones contract. modifier onlyMilestonesContract(bytes32 _agreementHash) { DecoRelay relay = DecoRelay(relayContractAddress); require( msg.sender == relay.milestonesContractAddress(), "Only milestones contract can perform this operation." ); Project memory project = projects[_agreementHash]; _; } constructor (uint256 _chainId) public { require(_chainId != 0, "You must specify a nonzero chainId"); DOMAIN_SEPARATOR = hash(EIP712Domain({ name: "Deco.Network", version: "1", chainId: _chainId, verifyingContract: address(this) })); } /** * @dev Creates a new milestone-based project with pre-selected maker and owner. All parameters are required. * @param _agreementId A `string` unique id of the agreement document for that project. * @param _client An `address` of the project owner. * @param _arbiter An `address` of the referee to settle all escalated disputes between parties. * @param _maker An `address` of the project`s maker. * @param _makersSignature A `bytes` digital signature of the maker to proof the agreement acceptance. * @param _milestonesCount An `uint8` count of planned milestones for the project. * @param _milestoneStartWindow An `uint8` count of days project`s owner has to start the next milestone. * If this time is exceeded then the maker can terminate the project. * @param _feedbackWindow An `uint8` time in days project`s owner has to provide feedback for the last milestone. * If that time is exceeded then maker can terminate the project and get paid for awaited * milestone. * @param _agreementEncrypted A `bool` flag indicating whether or not the agreement is encrypted. */ function startProject( string _agreementId, address _client, address _arbiter, address _maker, bytes _makersSignature, uint8 _milestonesCount, uint8 _milestoneStartWindow, uint8 _feedbackWindow, bool _agreementEncrypted ) external { require(msg.sender == _client, "Only the client can kick off the project."); require(_client != _maker, "Client can`t be a maker on her own project."); require(_arbiter != _maker && _arbiter != _client, "Arbiter must not be a client nor a maker."); require( isMakersSignatureValid(_maker, _makersSignature, _agreementId, _arbiter), "Maker should sign the hash of immutable agreement doc." ); require(_milestonesCount >= 1 && _milestonesCount <= 24, "Milestones count is not in the allowed 1-24 range."); bytes32 hash = keccak256(_agreementId); require(projects[hash].client == address(0x0), "Project shouldn't exist yet."); saveCurrentArbitrationFees(_arbiter, hash); address newEscrowCloneAddress = deployEscrowClone(msg.sender); projects[hash] = Project( _agreementId, msg.sender, _maker, _arbiter, newEscrowCloneAddress, now, 0, // end date is unknown yet _milestoneStartWindow, _feedbackWindow, _milestonesCount, 0, // CSAT is 0 to indicate that it isn't set by maker yet 0, // MSAT is 0 to indicate that it isn't set by client yet _agreementEncrypted ); makerProjects[_maker].push(hash); clientProjects[_client].push(hash); emit LogProjectStateUpdate(hash, msg.sender, now, ProjectState.Active); } /** * @dev Terminate the project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. */ function terminateProject(bytes32 _agreementHash) external eitherClientOrMakerOrMilestoneContract(_agreementHash) { Project storage project = projects[_agreementHash]; require(project.client != address(0x0), "Only allowed for existing projects."); require(project.endDate == 0, "Only allowed for active projects."); address milestoneContractAddress = DecoRelay(relayContractAddress).milestonesContractAddress(); if (msg.sender != milestoneContractAddress) { DecoMilestones milestonesContract = DecoMilestones(milestoneContractAddress); milestonesContract.terminateLastMilestone(_agreementHash, msg.sender); } project.endDate = now; emit LogProjectStateUpdate(_agreementHash, msg.sender, now, ProjectState.Terminated); } /** * @dev Complete the project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. */ function completeProject( bytes32 _agreementHash ) external onlyMilestonesContract(_agreementHash) { Project storage project = projects[_agreementHash]; require(project.client != address(0x0), "Only allowed for existing projects."); require(project.endDate == 0, "Only allowed for active projects."); projects[_agreementHash].endDate = now; DecoMilestones milestonesContract = DecoMilestones( DecoRelay(relayContractAddress).milestonesContractAddress() ); bool isLastMilestoneAccepted; uint8 milestoneNumber; (isLastMilestoneAccepted, milestoneNumber) = milestonesContract.isLastMilestoneAccepted( _agreementHash ); require( milestoneNumber == projects[_agreementHash].milestonesCount, "The last milestone should be the last for that project." ); require(isLastMilestoneAccepted, "Only allowed when all milestones are completed."); emit LogProjectStateUpdate(_agreementHash, msg.sender, now, ProjectState.Completed); } /** * @dev Rate the second party on the project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @param _rating An `uint8` satisfaction score of either client or maker. Min value is 1, max is 10. */ function rateProjectSecondParty( bytes32 _agreementHash, uint8 _rating ) external eitherClientOrMaker(_agreementHash) { require(_rating >= 1 && _rating <= 10, "Project rating should be in the range 1-10."); Project storage project = projects[_agreementHash]; require(project.endDate != 0, "Only allowed for active projects."); address ratingTarget; if (msg.sender == project.client) { require(project.customerSatisfaction == 0, "CSAT is allowed to provide only once."); project.customerSatisfaction = _rating; ratingTarget = project.maker; } else { require(project.makerSatisfaction == 0, "MSAT is allowed to provide only once."); project.makerSatisfaction = _rating; ratingTarget = project.client; } emit LogProjectRated(_agreementHash, msg.sender, ratingTarget, _rating, now); } /** * @dev Query for getting the address of Escrow contract clone deployed for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of a clone. */ function getProjectEscrowAddress(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].escrowContractAddress; } /** * @dev Query for getting the address of a client for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of a client. */ function getProjectClient(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].client; } /** * @dev Query for getting the address of a maker for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of a maker. */ function getProjectMaker(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].maker; } /** * @dev Query for getting the address of an arbiter for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of an arbiter. */ function getProjectArbiter(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].arbiter; } /** * @dev Query for getting the feedback window for a client for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint8` feedback window in days. */ function getProjectFeedbackWindow(bytes32 _agreementHash) public view returns(uint8) { return projects[_agreementHash].feedbackWindow; } /** * @dev Query for getting the milestone start window for a client for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint8` milestone start window in days. */ function getProjectMilestoneStartWindow(bytes32 _agreementHash) public view returns(uint8) { return projects[_agreementHash].milestoneStartWindow; } /** * @dev Query for getting the start date for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint` start date. */ function getProjectStartDate(bytes32 _agreementHash) public view returns(uint) { return projects[_agreementHash].startDate; } /** * @dev Calculates sum and number of CSAT scores of ended & rated projects for the given maker`s address. * @param _maker An `address` of the maker to look up. * @return An `uint` sum of all scores and an `uint` number of projects counted in sum. */ function makersAverageRating(address _maker) public view returns(uint, uint) { return calculateScore(_maker, ScoreType.CustomerSatisfaction); } /** * @dev Calculates sum and number of MSAT scores of ended & rated projects for the given client`s address. * @param _client An `address` of the client to look up. * @return An `uint` sum of all scores and an `uint` number of projects counted in sum. */ function clientsAverageRating(address _client) public view returns(uint, uint) { return calculateScore(_client, ScoreType.MakerSatisfaction); } /** * @dev Returns hashes of all client`s projects * @param _client An `address` to look up. * @return `bytes32[]` of projects hashes. */ function getClientProjects(address _client) public view returns(bytes32[]) { return clientProjects[_client]; } /** @dev Returns hashes of all maker`s projects * @param _maker An `address` to look up. * @return `bytes32[]` of projects hashes. */ function getMakerProjects(address _maker) public view returns(bytes32[]) { return makerProjects[_maker]; } /** * @dev Checks if a project with the given hash exists. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return A `bool` stating for the project`s existence. */ function checkIfProjectExists(bytes32 _agreementHash) public view returns(bool) { return projects[_agreementHash].client != address(0x0); } /** * @dev Query for getting end date of the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint` end time of the project */ function getProjectEndDate(bytes32 _agreementHash) public view returns(uint) { return projects[_agreementHash].endDate; } /** * @dev Returns preconfigured count of milestones for a project with the given hash. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint8` count of milestones set upon the project creation. */ function getProjectMilestonesCount(bytes32 _agreementHash) public view returns(uint8) { return projects[_agreementHash].milestonesCount; } /** * @dev Returns configured for the given project arbiter fees. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint` fixed fee and an `uint8` share fee of the project's arbiter. */ function getProjectArbitrationFees(bytes32 _agreementHash) public view returns(uint, uint8) { return ( projectArbiterFixedFee[_agreementHash], projectArbiterShareFee[_agreementHash] ); } function getInfoForDisputeAndValidate( bytes32 _agreementHash, address _respondent, address _initiator, address _arbiter ) public view returns(uint, uint8, address) { require(checkIfProjectExists(_agreementHash), "Project must exist."); Project memory project = projects[_agreementHash]; address client = project.client; address maker = project.maker; require(project.arbiter == _arbiter, "Arbiter should be same as saved in project."); require( (_initiator == client && _respondent == maker) || (_initiator == maker && _respondent == client), "Initiator and respondent must be different and equal to maker/client addresses." ); (uint fixedFee, uint8 shareFee) = getProjectArbitrationFees(_agreementHash); return (fixedFee, shareFee, project.escrowContractAddress); } /** * @dev Pulls the current arbitration contract fixed & share fees and save them for a project. * @param _arbiter An `address` of arbitration contract. * @param _agreementHash A `bytes32` hash of agreement id. */ function saveCurrentArbitrationFees(address _arbiter, bytes32 _agreementHash) internal { IDecoArbitration arbitration = IDecoArbitration(_arbiter); uint fixedFee; uint8 shareFee; (fixedFee, shareFee) = arbitration.getFixedAndShareFees(); projectArbiterFixedFee[_agreementHash] = fixedFee; projectArbiterShareFee[_agreementHash] = shareFee; } /** * @dev Calculates the sum of scores and the number of ended and rated projects for the given client`s or * maker`s address. * @param _address An `address` to look up. * @param _scoreType A `ScoreType` indicating what score should be calculated. * `CustomerSatisfaction` type means that CSAT score for the given address as a maker should be calculated. * `MakerSatisfaction` type means that MSAT score for the given address as a client should be calculated. * @return An `uint` sum of all scores and an `uint` number of projects counted in sum. */ function calculateScore( address _address, ScoreType _scoreType ) internal view returns(uint, uint) { bytes32[] memory allProjectsHashes = getProjectsByScoreType(_address, _scoreType); uint rating = 0; uint endedProjectsCount = 0; for (uint index = 0; index < allProjectsHashes.length; index++) { bytes32 agreementHash = allProjectsHashes[index]; if (projects[agreementHash].endDate == 0) { continue; } uint8 score = getProjectScoreByType(agreementHash, _scoreType); if (score == 0) { continue; } endedProjectsCount++; rating = rating.add(score); } return (rating, endedProjectsCount); } /** * @dev Returns all projects for the given address depending on the provided score type. * @param _address An `address` to look up. * @param _scoreType A `ScoreType` to identify projects source. * @return `bytes32[]` of projects hashes either from `clientProjects` or `makerProjects` storage arrays. */ function getProjectsByScoreType(address _address, ScoreType _scoreType) internal view returns(bytes32[]) { if (_scoreType == ScoreType.CustomerSatisfaction) { return makerProjects[_address]; } else { return clientProjects[_address]; } } /** * @dev Returns project score by the given type. * @param _agreementHash A `bytes32` hash of a project`s agreement id. * @param _scoreType A `ScoreType` to identify what score is requested. * @return An `uint8` score of the given project and of the given type. */ function getProjectScoreByType(bytes32 _agreementHash, ScoreType _scoreType) internal view returns(uint8) { if (_scoreType == ScoreType.CustomerSatisfaction) { return projects[_agreementHash].customerSatisfaction; } else { return projects[_agreementHash].makerSatisfaction; } } /** * @dev Deploy DecoEscrow contract clone for the newly created project. * @param _newContractOwner An `address` of a new contract owner. * @return An `address` of a new deployed escrow contract. */ function deployEscrowClone(address _newContractOwner) internal returns(address) { DecoRelay relay = DecoRelay(relayContractAddress); DecoEscrowFactory factory = DecoEscrowFactory(relay.escrowFactoryContractAddress()); return factory.createEscrow(_newContractOwner, relay.milestonesContractAddress()); } /** * @dev Check validness of maker's signature on project creation. * @param _maker An `address` of a maker. * @param _signature A `bytes` digital signature generated by a maker. * @param _agreementId A unique id of the agreement document for a project * @param _arbiter An `address` of a referee to settle all escalated disputes between parties. * @return A `bool` indicating validity of the signature. */ function isMakersSignatureValid(address _maker, bytes _signature, string _agreementId, address _arbiter) internal view returns (bool) { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(Proposal(_agreementId, _arbiter)) )); address signatureAddress = digest.recover(_signature); return signatureAddress == _maker; } function hash(EIP712Domain eip712Domain) internal view returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract )); } function hash(Proposal proposal) internal view returns (bytes32) { return keccak256(abi.encode( PROPOSAL_TYPEHASH, keccak256(bytes(proposal.agreementId)), proposal.arbiter )); } } /// @title Contract for Milesotone events and actions handling. contract DecoMilestones is IDecoArbitrationTarget, DecoBaseProjectsMarketplace { address public constant ETH_TOKEN_ADDRESS = address(0x0); // struct to describe Milestone struct Milestone { uint8 milestoneNumber; // original duration of a milestone. uint32 duration; // track all adjustments caused by state changes Active <-> Delivered <-> Rejected // `adjustedDuration` time gets increased by the time that is spent by client // to provide a feedback when agreed milestone time is not exceeded yet. // Initial value is the same as duration. uint32 adjustedDuration; uint depositAmount; address tokenAddress; uint startedTime; uint deliveredTime; uint acceptedTime; // indicates that a milestone progress was paused. bool isOnHold; } // enumeration to describe possible milestone states. enum MilestoneState { Active, Delivered, Accepted, Rejected, Terminated, Paused } // map agreement id hash to milestones list. mapping (bytes32 => Milestone[]) public projectMilestones; // Logged when milestone state changes. event LogMilestoneStateUpdated ( bytes32 indexed agreementHash, address indexed sender, uint timestamp, uint8 milestoneNumber, MilestoneState indexed state ); event LogMilestoneDurationAdjusted ( bytes32 indexed agreementHash, address indexed sender, uint32 amountAdded, uint8 milestoneNumber ); /** * @dev Starts a new milestone for the project and deposit ETH in smart contract`s escrow. * @param _agreementHash A `bytes32` hash of the agreement id. * @param _depositAmount An `uint` of wei that are going to be deposited for a new milestone. * @param _duration An `uint` seconds of a milestone duration. */ function startMilestone( bytes32 _agreementHash, uint _depositAmount, address _tokenAddress, uint32 _duration ) external { uint8 completedMilestonesCount = uint8(projectMilestones[_agreementHash].length); if (completedMilestonesCount > 0) { Milestone memory lastMilestone = projectMilestones[_agreementHash][completedMilestonesCount - 1]; require(lastMilestone.acceptedTime > 0, "All milestones must be accepted prior starting a new one."); } DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require( projectsContract.getProjectClient(_agreementHash) == msg.sender, "Only project's client starts a miestone" ); require( projectsContract.getProjectMilestonesCount(_agreementHash) > completedMilestonesCount, "Milestones count should not exceed the number configured in the project." ); require( projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active." ); blockFundsInEscrow( projectsContract.getProjectEscrowAddress(_agreementHash), _depositAmount, _tokenAddress ); uint nowTimestamp = now; projectMilestones[_agreementHash].push( Milestone( completedMilestonesCount + 1, _duration, _duration, _depositAmount, _tokenAddress, nowTimestamp, 0, 0, false ) ); emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, completedMilestonesCount + 1, MilestoneState.Active ); } /** * @dev Maker delivers the current active milestone. * @param _agreementHash Project`s unique hash. */ function deliverLastMilestone(bytes32 _agreementHash) external { DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require(projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active."); require(projectsContract.getProjectMaker(_agreementHash) == msg.sender, "Sender must be a maker."); uint nowTimestamp = now; uint8 milestonesCount = uint8(projectMilestones[_agreementHash].length); require(milestonesCount > 0, "There must be milestones to make a delivery."); Milestone storage milestone = projectMilestones[_agreementHash][milestonesCount - 1]; require( milestone.startedTime > 0 && milestone.deliveredTime == 0 && milestone.acceptedTime == 0, "Milestone must be active, not delivered and not accepted." ); require(!milestone.isOnHold, "Milestone must not be paused."); milestone.deliveredTime = nowTimestamp; emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, milestonesCount, MilestoneState.Delivered ); } /** * @dev Project owner accepts the current delivered milestone. * @param _agreementHash Project`s unique hash. */ function acceptLastMilestone(bytes32 _agreementHash) external { DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require(projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active."); require(projectsContract.getProjectClient(_agreementHash) == msg.sender, "Sender must be a client."); uint8 milestonesCount = uint8(projectMilestones[_agreementHash].length); require(milestonesCount > 0, "There must be milestones to accept a delivery."); Milestone storage milestone = projectMilestones[_agreementHash][milestonesCount - 1]; require( milestone.startedTime > 0 && milestone.acceptedTime == 0 && milestone.deliveredTime > 0 && milestone.isOnHold == false, "Milestone should be active and delivered, but not rejected, or already accepted, or put on hold." ); uint nowTimestamp = now; milestone.acceptedTime = nowTimestamp; if (projectsContract.getProjectMilestonesCount(_agreementHash) == milestonesCount) { projectsContract.completeProject(_agreementHash); } distributeFundsInEscrow( projectsContract.getProjectEscrowAddress(_agreementHash), projectsContract.getProjectMaker(_agreementHash), milestone.depositAmount, milestone.tokenAddress ); emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, milestonesCount, MilestoneState.Accepted ); } /** * @dev Project owner rejects the current active milestone. * @param _agreementHash Project`s unique hash. */ function rejectLastDeliverable(bytes32 _agreementHash) external { DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require(projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active."); require(projectsContract.getProjectClient(_agreementHash) == msg.sender, "Sender must be a client."); uint8 milestonesCount = uint8(projectMilestones[_agreementHash].length); require(milestonesCount > 0, "There must be milestones to reject a delivery."); Milestone storage milestone = projectMilestones[_agreementHash][milestonesCount - 1]; require( milestone.startedTime > 0 && milestone.acceptedTime == 0 && milestone.deliveredTime > 0 && milestone.isOnHold == false, "Milestone should be active and delivered, but not rejected, or already accepted, or on hold." ); uint nowTimestamp = now; if (milestone.startedTime.add(milestone.adjustedDuration) > milestone.deliveredTime) { uint32 timeToAdd = uint32(nowTimestamp.sub(milestone.deliveredTime)); milestone.adjustedDuration += timeToAdd; emit LogMilestoneDurationAdjusted ( _agreementHash, msg.sender, timeToAdd, milestonesCount ); } milestone.deliveredTime = 0; emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, milestonesCount, MilestoneState.Rejected ); } /** * @dev Prepare arbitration target for a started dispute. * @param _idHash A `bytes32` hash of id. */ function disputeStartedFreeze(bytes32 _idHash) public { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); require( projectsContract.getProjectArbiter(_idHash) == msg.sender, "Freezing upon dispute start can be sent only by arbiter." ); uint milestonesCount = projectMilestones[_idHash].length; require(milestonesCount > 0, "There must be active milestone."); Milestone storage lastMilestone = projectMilestones[_idHash][milestonesCount - 1]; lastMilestone.isOnHold = true; emit LogMilestoneStateUpdated( _idHash, msg.sender, now, uint8(milestonesCount), MilestoneState.Paused ); } /** * @dev React to an active dispute settlement with given parameters. * @param _idHash A `bytes32` hash of id. * @param _respondent An `address` of a respondent. * @param _respondentShare An `uint8` share for the respondent. * @param _initiator An `address` of a dispute initiator. * @param _initiatorShare An `uint8` share for the initiator. * @param _isInternal A `bool` indicating if dispute was settled by participants without an arbiter. * @param _arbiterWithdrawalAddress An `address` for sending out arbiter compensation. */ function disputeSettledTerminate( bytes32 _idHash, address _respondent, uint8 _respondentShare, address _initiator, uint8 _initiatorShare, bool _isInternal, address _arbiterWithdrawalAddress ) public { uint milestonesCount = projectMilestones[_idHash].length; require(milestonesCount > 0, "There must be at least one milestone."); Milestone memory lastMilestone = projectMilestones[_idHash][milestonesCount - 1]; require(lastMilestone.isOnHold, "Last milestone must be on hold."); require(uint(_respondentShare).add(uint(_initiatorShare)) == 100, "Shares must be 100% in sum."); DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); ( uint fixedFee, uint8 shareFee, address escrowAddress ) = projectsContract.getInfoForDisputeAndValidate ( _idHash, _respondent, _initiator, msg.sender ); distributeDisputeFunds( escrowAddress, lastMilestone.tokenAddress, _respondent, _initiator, _initiatorShare, _isInternal, _arbiterWithdrawalAddress, lastMilestone.depositAmount, fixedFee, shareFee ); projectsContract.terminateProject(_idHash); emit LogMilestoneStateUpdated( _idHash, msg.sender, now, uint8(milestonesCount), MilestoneState.Terminated ); } /** * @dev Check eligibility of a given address to perform operations, * basically the address should be either client or maker. * @param _idHash A `bytes32` hash of id. * @param _addressToCheck An `address` to check. * @return A `bool` check status. */ function checkEligibility(bytes32 _idHash, address _addressToCheck) public view returns(bool) { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); return _addressToCheck == projectsContract.getProjectClient(_idHash) || _addressToCheck == projectsContract.getProjectMaker(_idHash); } /** * @dev Check if target is ready for a dispute. * @param _idHash A `bytes32` hash of id. * @return A `bool` check status. */ function canStartDispute(bytes32 _idHash) public view returns(bool) { uint milestonesCount = projectMilestones[_idHash].length; if (milestonesCount == 0) return false; Milestone memory lastMilestone = projectMilestones[_idHash][milestonesCount - 1]; if (lastMilestone.isOnHold || lastMilestone.acceptedTime > 0) return false; address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); uint feedbackWindow = uint(projectsContract.getProjectFeedbackWindow(_idHash)).mul(24 hours); uint nowTimestamp = now; uint plannedDeliveryTime = lastMilestone.startedTime.add(uint(lastMilestone.adjustedDuration)); if (plannedDeliveryTime < lastMilestone.deliveredTime || plannedDeliveryTime < nowTimestamp) { return false; } if (lastMilestone.deliveredTime > 0 && lastMilestone.deliveredTime.add(feedbackWindow) < nowTimestamp) return false; return true; } /** * @dev Either project owner or maker can terminate the project in certain cases * and the current active milestone must be marked as terminated for records-keeping. * All blocked funds should be distributed in favor of eligible project party. * The termination with this method initiated only by project contract. * @param _agreementHash Project`s unique hash. * @param _initiator An `address` of the termination initiator. */ function terminateLastMilestone(bytes32 _agreementHash, address _initiator) public { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); require(msg.sender == projectsContractAddress, "Method should be called by Project contract."); DecoProjects projectsContract = DecoProjects(projectsContractAddress); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); address projectClient = projectsContract.getProjectClient(_agreementHash); address projectMaker = projectsContract.getProjectMaker(_agreementHash); require( _initiator == projectClient || _initiator == projectMaker, "Initiator should be either maker or client address." ); if (_initiator == projectClient) { require(canClientTerminate(_agreementHash)); } else { require(canMakerTerminate(_agreementHash)); } uint milestonesCount = projectMilestones[_agreementHash].length; if (milestonesCount == 0) return; Milestone memory lastMilestone = projectMilestones[_agreementHash][milestonesCount - 1]; if (lastMilestone.acceptedTime > 0) return; address projectEscrowContractAddress = projectsContract.getProjectEscrowAddress(_agreementHash); if (_initiator == projectClient) { unblockFundsInEscrow( projectEscrowContractAddress, lastMilestone.depositAmount, lastMilestone.tokenAddress ); } else { distributeFundsInEscrow( projectEscrowContractAddress, _initiator, lastMilestone.depositAmount, lastMilestone.tokenAddress ); } emit LogMilestoneStateUpdated( _agreementHash, msg.sender, now, uint8(milestonesCount), MilestoneState.Terminated ); } /** * @dev Returns the last project milestone completion status and number. * @param _agreementHash Project's unique hash. * @return isAccepted A boolean flag for acceptance state, and milestoneNumber for the last milestone. */ function isLastMilestoneAccepted( bytes32 _agreementHash ) public view returns(bool isAccepted, uint8 milestoneNumber) { milestoneNumber = uint8(projectMilestones[_agreementHash].length); if (milestoneNumber > 0) { isAccepted = projectMilestones[_agreementHash][milestoneNumber - 1].acceptedTime > 0; } else { isAccepted = false; } } /** * @dev Client can terminate milestone if the last milestone delivery is overdue and * milestone is not on hold. By default termination is not available. * @param _agreementHash Project`s unique hash. * @return `true` if the last project's milestone could be terminated by client. */ function canClientTerminate(bytes32 _agreementHash) public view returns(bool) { uint milestonesCount = projectMilestones[_agreementHash].length; if (milestonesCount == 0) return false; Milestone memory lastMilestone = projectMilestones[_agreementHash][milestonesCount - 1]; return lastMilestone.acceptedTime == 0 && !lastMilestone.isOnHold && lastMilestone.startedTime.add(uint(lastMilestone.adjustedDuration)) < now; } /** * @dev Maker can terminate milestone if delivery review is taking longer than project feedback window and * milestone is not on hold, or if client doesn't start the next milestone for a period longer than * project's milestone start window. By default termination is not available. * @param _agreementHash Project`s unique hash. * @return `true` if the last project's milestone could be terminated by maker. */ function canMakerTerminate(bytes32 _agreementHash) public view returns(bool) { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); uint feedbackWindow = uint(projectsContract.getProjectFeedbackWindow(_agreementHash)).mul(24 hours); uint milestoneStartWindow = uint(projectsContract.getProjectMilestoneStartWindow( _agreementHash )).mul(24 hours); uint projectStartDate = projectsContract.getProjectStartDate(_agreementHash); uint milestonesCount = projectMilestones[_agreementHash].length; if (milestonesCount == 0) return now.sub(projectStartDate) > milestoneStartWindow; Milestone memory lastMilestone = projectMilestones[_agreementHash][milestonesCount - 1]; uint nowTimestamp = now; if (!lastMilestone.isOnHold && lastMilestone.acceptedTime > 0 && nowTimestamp.sub(lastMilestone.acceptedTime) > milestoneStartWindow) return true; return !lastMilestone.isOnHold && lastMilestone.acceptedTime == 0 && lastMilestone.deliveredTime > 0 && nowTimestamp.sub(feedbackWindow) > lastMilestone.deliveredTime; } /* * @dev Block funds in escrow from balance to the blocked balance. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _amount An `uint` amount to distribute. * @param _tokenAddress An `address` of a token. */ function blockFundsInEscrow( address _projectEscrowContractAddress, uint _amount, address _tokenAddress ) internal { if (_amount == 0) return; DecoEscrow escrow = DecoEscrow(_projectEscrowContractAddress); if (_tokenAddress == ETH_TOKEN_ADDRESS) { escrow.blockFunds(_amount); } else { escrow.blockTokenFunds(_tokenAddress, _amount); } } /* * @dev Unblock funds in escrow from blocked balance to the balance. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _amount An `uint` amount to distribute. * @param _tokenAddress An `address` of a token. */ function unblockFundsInEscrow( address _projectEscrowContractAddress, uint _amount, address _tokenAddress ) internal { if (_amount == 0) return; DecoEscrow escrow = DecoEscrow(_projectEscrowContractAddress); if (_tokenAddress == ETH_TOKEN_ADDRESS) { escrow.unblockFunds(_amount); } else { escrow.unblockTokenFunds(_tokenAddress, _amount); } } /** * @dev Distribute funds in escrow from blocked balance to the target address. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _distributionTargetAddress Target `address`. * @param _amount An `uint` amount to distribute. * @param _tokenAddress An `address` of a token. */ function distributeFundsInEscrow( address _projectEscrowContractAddress, address _distributionTargetAddress, uint _amount, address _tokenAddress ) internal { if (_amount == 0) return; DecoEscrow escrow = DecoEscrow(_projectEscrowContractAddress); if (_tokenAddress == ETH_TOKEN_ADDRESS) { escrow.distributeFunds(_distributionTargetAddress, _amount); } else { escrow.distributeTokenFunds(_distributionTargetAddress, _tokenAddress, _amount); } } /** * @dev Distribute project funds between arbiter and project parties. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _tokenAddress An `address` of a token. * @param _respondent An `address` of a respondent. * @param _initiator An `address` of an initiator. * @param _initiatorShare An `uint8` iniator`s share. * @param _isInternal A `bool` indicating if dispute was settled solely by project parties. * @param _arbiterWithdrawalAddress A withdrawal `address` of an arbiter. * @param _amount An `uint` amount for distributing between project parties and arbiter. * @param _fixedFee An `uint` fixed fee of an arbiter. * @param _shareFee An `uint8` share fee of an arbiter. */ function distributeDisputeFunds( address _projectEscrowContractAddress, address _tokenAddress, address _respondent, address _initiator, uint8 _initiatorShare, bool _isInternal, address _arbiterWithdrawalAddress, uint _amount, uint _fixedFee, uint8 _shareFee ) internal { if (!_isInternal && _arbiterWithdrawalAddress != address(0x0)) { uint arbiterFee = getArbiterFeeAmount(_fixedFee, _shareFee, _amount, _tokenAddress); distributeFundsInEscrow( _projectEscrowContractAddress, _arbiterWithdrawalAddress, arbiterFee, _tokenAddress ); _amount = _amount.sub(arbiterFee); } uint initiatorAmount = _amount.mul(_initiatorShare).div(100); distributeFundsInEscrow( _projectEscrowContractAddress, _initiator, initiatorAmount, _tokenAddress ); distributeFundsInEscrow( _projectEscrowContractAddress, _respondent, _amount.sub(initiatorAmount), _tokenAddress ); } /** * @dev Calculates arbiter`s fee. * @param _fixedFee An `uint` fixed fee of an arbiter. * @param _shareFee An `uint8` share fee of an arbiter. * @param _amount An `uint` amount for distributing between project parties and arbiter. * @param _tokenAddress An `address` of a token. * @return An `uint` amount allotted to the arbiter. */ function getArbiterFeeAmount(uint _fixedFee, uint8 _shareFee, uint _amount, address _tokenAddress) internal pure returns(uint) { if (_tokenAddress != ETH_TOKEN_ADDRESS) { _fixedFee = 0; } return _amount.sub(_fixedFee).mul(uint(_shareFee)).div(100).add(_fixedFee); } } contract DecoProxy { using ECDSA for bytes32; /// Emitted when incoming ETH funds land into account. event Received (address indexed sender, uint value); /// Emitted when transaction forwarded to the next destination. event Forwarded ( bytes signature, address indexed signer, address indexed destination, uint value, bytes data, bytes32 _hash ); /// Emitted when owner is changed event OwnerChanged ( address indexed newOwner ); bool internal isInitialized; // Keep track to avoid replay attack. uint public nonce; /// Proxy owner. address public owner; /** * @dev Initialize the Proxy clone with default values. * @param _owner An address that orders forwarding of transactions. */ function initialize(address _owner) public { require(!isInitialized, "Clone must be initialized only once."); isInitialized = true; owner = _owner; } /** * @dev Payable fallback to accept incoming payments. */ function () external payable { emit Received(msg.sender, msg.value); } /** * @dev Change the owner of this proxy. Used when the user forgets their key, and we can recover it via SSSS split key. This will be the final txn of the forgotten key as it transfers ownership of the proxy to the new replacement key. Note that this is also callable by the contract itself, which would be used in the case that a user is changing their owner address via a metatxn * @param _newOwner An `address` of the new proxy owner. */ function changeOwner(address _newOwner) public { require(owner == msg.sender || address(this) == msg.sender, "Only owner can change owner"); owner = _newOwner; emit OwnerChanged(_newOwner); } /** * @dev Forward a regular (non meta) transaction to the destination address. * @param _destination An `address` where txn should be forwarded to. * @param _value An `uint` of Wei value to be sent out. * @param _data A `bytes` data array of the given transaction. */ function forwardFromOwner(address _destination, uint _value, bytes memory _data) public { require(owner == msg.sender, "Only owner can use forwardFromOwner method"); require(executeCall(_destination, _value, _data), "Call must be successfull."); emit Forwarded("", owner, _destination, _value, _data, ""); } /** * @dev Returns hash for the given transaction. * @param _signer An `address` of transaction signer. * @param _destination An `address` where txn should be forwarded to. * @param _value An `uint` of Wei value to be sent out. * @param _data A `bytes` data array of the given transaction. * @return A `bytes32` hash calculated for all incoming parameters. */ function getHash( address _signer, address _destination, uint _value, bytes memory _data ) public view returns(bytes32) { return keccak256(abi.encodePacked(address(this), _signer, _destination, _value, _data, nonce)); } /** * @dev Forward a meta transaction to the destination address. * @param _signature A `bytes` array cotaining signature generated by owner. * @param _signer An `address` of transaction signer. * @param _destination An `address` where txn should be forwarded to. * @param _value An `uint` of Wei value to be sent out. * @param _data A `bytes` data array of the given transaction. */ function forward(bytes memory _signature, address _signer, address _destination, uint _value, bytes memory _data) public { bytes32 hash = getHash(_signer, _destination, _value, _data); nonce++; require(owner == hash.toEthSignedMessageHash().recover(_signature), "Signer must be owner."); require(executeCall(_destination, _value, _data), "Call must be successfull."); emit Forwarded(_signature, _signer, _destination, _value, _data, hash); } /** * @dev Withdraw given amount of wei to the specified address. * @param _to An `address` of where to send the wei. * @param _value An `uint` amount to withdraw from the contract balance. */ function withdraw(address _to, uint _value) public { require(owner == msg.sender || address(this) == msg.sender, "Only owner can withdraw"); _to.transfer(_value); } /** * @dev Withdraw any ERC20 tokens from the contract balance to owner's address. * @param _tokenAddress An `address` of an ERC20 token. * @param _to An `address` of where to send the tokens. * @param _tokens An `uint` tokens amount. */ function withdrawERC20Token(address _tokenAddress, address _to, uint _tokens) public { require(owner == msg.sender || address(this) == msg.sender, "Only owner can withdraw"); IERC20 token = IERC20(_tokenAddress); require(token.transfer(_to, _tokens), "Tokens transfer must complete successfully."); } /** * @dev Forward txn by executing a call. * @param _to Destination `address`. * @param _value An `uint256` Wei value to be sent out. * @param _data A `bytes` array with txn data. * @return A `bool` completion status. */ function executeCall(address _to, uint256 _value, bytes memory _data) internal returns (bool success) { assembly { let x := mload(0x40) success := call(gas, _to, _value, add(_data, 0x20), mload(_data), 0, 0) } } } contract DecoProxyFactory is DecoBaseProjectsMarketplace, CloneFactory { // Proxy master-contract address. address public libraryAddress; // Logged when a new Escrow clone is deployed to the chain. event ProxyCreated(address newProxyAddress); /** * @dev Constructor for the contract. * @param _libraryAddress Proxy master-contract address. */ constructor(address _libraryAddress) public { libraryAddress = _libraryAddress; } /** * @dev Updates library address with the given value. * @param _libraryAddress Address of a new base contract. */ function setLibraryAddress(address _libraryAddress) external onlyOwner { require(libraryAddress != _libraryAddress); require(_libraryAddress != address(0x0)); libraryAddress = _libraryAddress; } /** * @dev Create Proxy clone. * @param _ownerAddress An address of the Proxy contract owner. */ function createProxy( address _ownerAddress ) external returns(address) { address clone = createClone(libraryAddress); DecoProxy(clone).initialize( _ownerAddress ); emit ProxyCreated(clone); return clone; } }
* @dev Forward txn by executing a call. @param _to Destination `address`. @param _value An `uint256` Wei value to be sent out. @param _data A `bytes` array with txn data. @return A `bool` completion status./
function executeCall(address _to, uint256 _value, bytes memory _data) internal returns (bool success) { assembly { let x := mload(0x40) success := call(gas, _to, _value, add(_data, 0x20), mload(_data), 0, 0) } }
1,084,746
[ 1, 8514, 7827, 635, 11274, 279, 745, 18, 225, 389, 869, 10691, 1375, 2867, 8338, 225, 389, 1132, 1922, 1375, 11890, 5034, 68, 1660, 77, 460, 358, 506, 3271, 596, 18, 225, 389, 892, 432, 1375, 3890, 68, 526, 598, 7827, 501, 18, 327, 432, 1375, 6430, 68, 8364, 1267, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1836, 1477, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 16, 1731, 3778, 389, 892, 13, 2713, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 19931, 288, 203, 5411, 2231, 619, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 2216, 519, 745, 12, 31604, 16, 389, 869, 16, 389, 1132, 16, 527, 24899, 892, 16, 374, 92, 3462, 3631, 312, 945, 24899, 892, 3631, 374, 16, 374, 13, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-29 */ // Sources flattened with hardhat v2.3.0 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File contracts/libs/TransferHelper.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint)'))); (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,uint)'))); (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,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/interfaces/ICoFiXRouter.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines methods for CoFiXRouter interface ICoFiXRouter { /// @dev Register trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @param pool Pool for the trade pair function registerPair(address token0, address token1, address pool) external; /// @dev Get pool address for trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @return pool Pool for the trade pair function pairFor(address token0, address token1) external view returns (address pool); /// @dev Register routing path /// @param src Src token address /// @param dest Dest token address /// @param path Routing path function registerRouterPath(address src, address dest, address[] calldata path) external; /// @dev Get routing path from src token address to dest token address /// @param src Src token address /// @param dest Dest token address /// @return path If success, return the routing path, /// each address in the array represents the token address experienced during the trading function getRouterPath(address src, address dest) external view returns (address[] memory path); /// @dev Maker add liquidity to pool, get pool token (mint XToken to maker) /// (notice: msg.value = amountETH + oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The deadline of this request /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function addLiquidity( address pool, address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (address xtoken, uint liquidity); /// @dev Maker add liquidity to pool, get pool token (mint XToken) and stake automatically /// (notice: msg.value = amountETH + oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The deadline of this request /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function addLiquidityAndStake( address pool, address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (address xtoken, uint liquidity); /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) /// (notice: msg.value = oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountETHMin The minimum amount of ETH wanted to get from pool /// @param to The target address receiving the Token /// @param deadline The deadline of this request /// @return amountETH The real amount of ETH transferred from the pool /// @return amountToken The real amount of Token transferred from the pool function removeLiquidityGetTokenAndETH( address pool, address token, uint liquidity, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountETH, uint amountToken); /// @dev Swap exact tokens for tokens /// @param path Routing path. If you need to exchange through multi-level routes, you need to write down all /// token addresses (ETH address is represented by 0) of the exchange path /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param amountOutMin The minimum amount of ETH a trader want to swap out of pool /// @param to The target address receiving the ETH /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The deadline of this request /// @return amountOut The real amount of Token transferred out of pool function swapExactTokensForTokens( address[] calldata path, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint amountOut); /// @dev Acquire the transaction mining share of the target XToken /// @param xtoken The destination XToken address /// @return Target XToken's transaction mining share function getTradeReward(address xtoken) external view returns (uint); } // File contracts/interfaces/ICoFiXPool.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines methods and events for CoFiXPool interface ICoFiXPool { /* ****************************************************************************************** * Note: In order to unify the authorization entry, all transferFrom operations are carried * out in the CoFiXRouter, and the CoFiXPool needs to be fixed, CoFiXRouter does trust and * needs to be taken into account when calculating the pool balance before and after rollover * ******************************************************************************************/ /// @dev Add liquidity and mining xtoken event /// @param token Target token address /// @param to The address to receive xtoken /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidity The real liquidity or XToken minted from pool event Mint(address token, address to, uint amountETH, uint amountToken, uint liquidity); /// @dev Remove liquidity and burn xtoken event /// @param token The address of ERC20 Token /// @param to The target address receiving the Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountETHOut The real amount of ETH transferred from the pool /// @param amountTokenOut The real amount of Token transferred from the pool event Burn(address token, address to, uint liquidity, uint amountETHOut, uint amountTokenOut); /// @dev Set configuration /// @param theta Trade fee rate, ten thousand points system. 20 /// @param impactCostVOL Impact cost threshold /// @param nt Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based function setConfig(uint16 theta, uint96 impactCostVOL, uint96 nt) external; /// @dev Get configuration /// @return theta Trade fee rate, ten thousand points system. 20 /// @return impactCostVOL Impact cost threshold /// @return nt Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based function getConfig() external view returns (uint16 theta, uint96 impactCostVOL, uint96 nt); /// @dev Add liquidity and mint xtoken /// @param token Target token address /// @param to The address to receive xtoken /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function mint( address token, address to, uint amountETH, uint amountToken, address payback ) external payable returns ( address xtoken, uint liquidity ); /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) /// @param token The address of ERC20 Token /// @param to The target address receiving the Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountETHOut The real amount of ETH transferred from the pool /// @return amountTokenOut The real amount of Token transferred from the pool function burn( address token, address to, uint liquidity, address payback ) external payable returns ( uint amountETHOut, uint amountTokenOut ); /// @dev Swap token /// @param src Src token address /// @param dest Dest token address /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param to The target address receiving the ETH /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountOut The real amount of ETH transferred out of pool /// @return mined The amount of CoFi which will be mind by this trade function swap( address src, address dest, uint amountIn, address to, address payback ) external payable returns ( uint amountOut, uint mined ); /// @dev Gets the token address of the share obtained by the specified token market making /// @param token Target token address /// @return If the fund pool supports the specified token, return the token address of the market share function getXToken(address token) external view returns (address); } // File contracts/interfaces/ICoFiXVaultForStaking.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines methods for CoFiXVaultForStaking interface ICoFiXVaultForStaking { /// @dev Modify configuration /// @param cofiUnit CoFi mining unit function setConfig(uint cofiUnit) external; /// @dev Get configuration /// @return cofiUnit CoFi mining unit function getConfig() external view returns (uint cofiUnit); /// @dev Initialize ore drawing weight /// @param xtokens xtoken array /// @param weights weight array function batchSetPoolWeight(address[] calldata xtokens, uint[] calldata weights) external; /// @dev Get total staked amount of xtoken /// @param xtoken xtoken address (or CNode address) /// @return totalStaked Total lock volume of target xtoken /// @return cofiPerBlock Mining speed, cofi per block function getChannelInfo(address xtoken) external view returns (uint totalStaked, uint cofiPerBlock); /// @dev Get staked amount of target address /// @param xtoken xtoken address (or CNode address) /// @param addr Target address /// @return Staked amount of target address function balanceOf(address xtoken, address addr) external view returns (uint); /// @dev Get the number of CoFi to be collected by the target address on the designated transaction pair lock /// @param xtoken xtoken address (or CNode address) /// @param addr Target address /// @return The number of CoFi to be collected by the target address on the designated transaction lock function earned(address xtoken, address addr) external view returns (uint); /// @dev Stake xtoken to earn CoFi, this method is only for CoFiXRouter /// @param xtoken xtoken address (or CNode address) /// @param to Target address /// @param amount Stake amount function routerStake(address xtoken, address to, uint amount) external; /// @dev Stake xtoken to earn CoFi /// @param xtoken xtoken address (or CNode address) /// @param amount Stake amount function stake(address xtoken, uint amount) external; /// @dev Withdraw xtoken, and claim earned CoFi /// @param xtoken xtoken address (or CNode address) /// @param amount Withdraw amount function withdraw(address xtoken, uint amount) external; /// @dev Claim CoFi /// @param xtoken xtoken address (or CNode address) function getReward(address xtoken) external; } // File contracts/interfaces/ICoFiXDAO.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the DAO methods interface ICoFiXDAO { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Configuration structure of CoFiXDAO contract struct Config { // Redeem status, 1 means normal uint8 status; // The number of CoFi redeem per block. 100 uint16 cofiPerBlock; // The maximum number of CoFi in a single redeem. 30000 uint32 cofiLimit; // Price deviation limit, beyond this upper limit stop redeem (10000 based). 1000 uint16 priceDeviationLimit; } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Set the exchange relationship between the token and the price of the anchored target currency. /// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places. /// so exchange = 1e6 * 1 ether / 1e18 = 1e6 /// @param token Address of origin token /// @param target Address of target anchor token /// @param exchange Exchange rate of token and target function setTokenExchange(address token, address target, uint exchange) external; /// @dev Get the exchange relationship between the token and the price of the anchored target currency. /// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places. /// so exchange = 1e6 * 1 ether / 1e18 = 1e6 /// @param token Address of origin token /// @return target Address of target anchor token /// @return exchange Exchange rate of token and target function getTokenExchange(address token) external view returns (address target, uint exchange); /// @dev Add reward /// @param pool Destination pool function addETHReward(address pool) external payable; /// @dev The function returns eth rewards of specified pool /// @param pool Destination pool function totalETHRewards(address pool) external view returns (uint); /// @dev Settlement /// @param pool Destination pool. Indicates which pool to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address pool, address tokenAddress, address to, uint value) external payable; /// @dev Redeem CoFi for ethers /// @notice Eth fee will be charged /// @param amount The amount of CoFi /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address function redeem(uint amount, address payback) external payable; /// @dev Redeem CoFi for Token /// @notice Eth fee will be charged /// @param token The target token /// @param amount The amount of CoFi /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address function redeemToken(address token, uint amount, address payback) external payable; /// @dev Get the current amount available for repurchase function quotaOf() external view returns (uint); } // File contracts/interfaces/ICoFiXMapping.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev The interface defines methods for CoFiX builtin contract address mapping interface ICoFiXMapping { /// @dev Set the built-in contract address of the system /// @param cofiToken Address of CoFi token contract /// @param cofiNode Address of CoFi Node contract /// @param cofixDAO ICoFiXDAO implementation contract address /// @param cofixRouter ICoFiXRouter implementation contract address for CoFiX /// @param cofixController ICoFiXController implementation contract address /// @param cofixVaultForStaking ICoFiXVaultForStaking implementation contract address function setBuiltinAddress( address cofiToken, address cofiNode, address cofixDAO, address cofixRouter, address cofixController, address cofixVaultForStaking ) external; /// @dev Get the built-in contract address of the system /// @return cofiToken Address of CoFi token contract /// @return cofiNode Address of CoFi Node contract /// @return cofixDAO ICoFiXDAO implementation contract address /// @return cofixRouter ICoFiXRouter implementation contract address for CoFiX /// @return cofixController ICoFiXController implementation contract address function getBuiltinAddress() external view returns ( address cofiToken, address cofiNode, address cofixDAO, address cofixRouter, address cofixController, address cofixVaultForStaking ); /// @dev Get address of CoFi token contract /// @return Address of CoFi Node token contract function getCoFiTokenAddress() external view returns (address); /// @dev Get address of CoFi Node contract /// @return Address of CoFi Node contract function getCoFiNodeAddress() external view returns (address); /// @dev Get ICoFiXDAO implementation contract address /// @return ICoFiXDAO implementation contract address function getCoFiXDAOAddress() external view returns (address); /// @dev Get ICoFiXRouter implementation contract address for CoFiX /// @return ICoFiXRouter implementation contract address for CoFiX function getCoFiXRouterAddress() external view returns (address); /// @dev Get ICoFiXController implementation contract address /// @return ICoFiXController implementation contract address function getCoFiXControllerAddress() external view returns (address); /// @dev Get ICoFiXVaultForStaking implementation contract address /// @return ICoFiXVaultForStaking implementation contract address function getCoFiXVaultForStakingAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by CoFiX system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string calldata key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string calldata key) external view returns (address); } // File contracts/interfaces/ICoFiXGovernance.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the governance methods interface ICoFiXGovernance is ICoFiXMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight /// to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File contracts/CoFiXBase.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // Router contract to interact with each CoFiXPair, no owner or governance /// @dev Base contract of CoFiX contract CoFiXBase { // Address of CoFiToken contract address constant COFI_TOKEN_ADDRESS = 0x1a23a6BfBAdB59fa563008c0fB7cf96dfCF34Ea1; // Address of CoFiNode contract address constant CNODE_TOKEN_ADDRESS = 0x558201DC4741efc11031Cdc3BC1bC728C23bF512; // Genesis block number of CoFi // CoFiToken contract is created at block height 11040156. However, because the mining algorithm of CoFiX1.0 // is different from that at present, a new mining algorithm is adopted from CoFiX2.1. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the CoFi begins to decay. According to the circulation when CoFi2.0 is online, the new mining // algorithm is used to deduce and convert the CoFi, and the new algorithm is used to mine the CoFiX2.1 // on-line flow, the actual block is 11040688 uint constant COFI_GENESIS_BLOCK = 11040688; /// @dev ICoFiXGovernance implementation contract address address public _governance; /// @dev To support open-zeppelin/upgrades /// @param governance ICoFiXGovernance implementation contract address function initialize(address governance) virtual public { require(_governance == address(0), "CoFiX:!initialize"); _governance = governance; } /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(newGovernance) when overriding, and override method without onlyGovernance /// @param newGovernance ICoFiXGovernance implementation contract address function update(address newGovernance) public virtual { address governance = _governance; require(governance == msg.sender || ICoFiXGovernance(governance).checkGovernance(msg.sender, 0), "CoFiX:!gov"); _governance = newGovernance; } /// @dev Migrate funds from current contract to CoFiXDAO /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = ICoFiXGovernance(_governance).getCoFiXDAOAddress(); if (tokenAddress == address(0)) { ICoFiXDAO(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(ICoFiXGovernance(_governance).checkGovernance(msg.sender, 0), "CoFiX:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "CoFiX:!contract"); _; } } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/utils/[email protected] // MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/CoFiToken.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // CoFiToken with Governance. It offers possibilities to adopt off-chain gasless governance infra. contract CoFiToken is ERC20("CoFi Token", "CoFi") { address public governance; mapping (address => bool) public minters; // Copied and modified from SUSHI code: // https://github.com/sushiswap/sushiswap/blob/master/contracts/SushiToken.sol // Which is copied and modified from YAM code and COMPOUND: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @dev An event thats emitted when a new governance account is set /// @param _new The new governance address event NewGovernance(address _new); /// @dev An event thats emitted when a new minter account is added /// @param _minter The new minter address added event MinterAdded(address _minter); /// @dev An event thats emitted when a minter account is removed /// @param _minter The minter address removed event MinterRemoved(address _minter); modifier onlyGovernance() { require(msg.sender == governance, "CoFi: !governance"); _; } constructor() { governance = msg.sender; } function setGovernance(address _new) external onlyGovernance { require(_new != address(0), "CoFi: zero addr"); require(_new != governance, "CoFi: same addr"); governance = _new; emit NewGovernance(_new); } function addMinter(address _minter) external onlyGovernance { minters[_minter] = true; emit MinterAdded(_minter); } function removeMinter(address _minter) external onlyGovernance { minters[_minter] = false; emit MinterRemoved(_minter); } /// @notice mint is used to distribute CoFi token to users, minters are CoFi mining pools function mint(address _to, uint _amount) external { require(minters[msg.sender], "CoFi: !minter"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice SUSHI has a vote governance bug in its token implementation, CoFi fixed it here /// read https://blog.peckshield.com/2020/09/08/sushi/ function transfer(address _recipient, uint _amount) public override returns (bool) { super.transfer(_recipient, _amount); _moveDelegates(_delegates[msg.sender], _delegates[_recipient], _amount); return true; } /// @notice override original transferFrom to fix vote issue function transferFrom(address _sender, address _recipient, uint _amount) public override returns (bool) { super.transferFrom(_sender, _recipient, _amount); _moveDelegates(_delegates[_sender], _delegates[_recipient], _amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CoFi::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CoFi::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "CoFi::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint) { require(blockNumber < block.number, "CoFi::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint delegatorBalance = balanceOf(delegator); // balance of underlying CoFis (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld - (amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld + (amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes ) internal { uint32 blockNumber = safe32(block.number, "CoFi::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal view returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } // File contracts/CoFiXRouter.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Router contract to interact with each CoFiXPair contract CoFiXRouter is CoFiXBase, ICoFiXRouter { /* ****************************************************************************************** * Note: In order to unify the authorization entry, all transferFrom operations are carried * out in the CoFiXRouter, and the CoFiXPool needs to be fixed, CoFiXRouter does trust and * needs to be taken into account when calculating the pool balance before and after rollover * ******************************************************************************************/ // Address of CoFiXVaultForStaking address _cofixVaultForStaking; // Mapping for trade pairs. keccak256(token0, token1)=>pool mapping(bytes32=>address) _pairs; // Mapping for trade paths. keccak256(token0, token1) = > path mapping(bytes32=>address[]) _paths; // Record the total CoFi share of CNode uint _cnodeReward; /// @dev Create CoFiXRouter constructor () { } // Verify that the cutoff time has exceeded modifier ensure(uint deadline) { require(block.timestamp <= deadline, "CoFiXRouter: EXPIRED"); _; } /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(newGovernance) when overriding, and override method without onlyGovernance /// @param newGovernance ICoFiXGovernance implementation contract address function update(address newGovernance) public override { super.update(newGovernance); _cofixVaultForStaking = ICoFiXGovernance(newGovernance).getCoFiXVaultForStakingAddress(); } /// @dev Register trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @param pool Pool for the trade pair function registerPair(address token0, address token1, address pool) public override onlyGovernance { _pairs[_getKey(token0, token1)] = pool; } /// @dev Get pool address for trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @return pool Pool for the trade pair function pairFor(address token0, address token1) external view override returns (address pool) { return _pairFor(token0, token1); } /// @dev Register routing path /// @param src Src token address /// @param dest Dest token address /// @param path Routing path function registerRouterPath(address src, address dest, address[] calldata path) external override onlyGovernance { // Check that the source and destination addresses are correct require(src == path[0], "CoFiXRouter: first token error"); require(dest == path[path.length - 1], "CoFiXRouter: last token error"); // Register routing path _paths[_getKey(src, dest)] = path; } /// @dev Get routing path from src token address to dest token address /// @param src Src token address /// @param dest Dest token address /// @return path If success, return the routing path, /// each address in the array represents the token address experienced during the trading function getRouterPath(address src, address dest) external view override returns (address[] memory path) { // Load the routing path path = _paths[_getKey(src, dest)]; uint j = path.length; // If it is a reverse path, reverse the path require(j > 0, "CoFiXRouter: path not exist"); if (src == path[--j] && dest == path[0]) { for (uint i = 0; i < j;) { address tmp = path[i]; path[i++] = path[j]; path[j--] = tmp; } } else { require(src == path[0] && dest == path[j], "CoFiXRouter: path error"); } } /// @dev Get pool address for trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @return pool Pool for the trade pair function _pairFor(address token0, address token1) private view returns (address pool) { return _pairs[_getKey(token0, token1)]; } // Generate the mapping key based on the token address function _getKey(address token0, address token1) private pure returns (bytes32) { (token0, token1) = _sort(token0, token1); return keccak256(abi.encodePacked(token0, token1)); } // Sort the address pair function _sort(address token0, address token1) private pure returns (address min, address max) { if (token0 < token1) { min = token0; max = token1; } else { min = token1; max = token0; } } /// @dev Maker add liquidity to pool, get pool token (mint XToken to maker) /// (notice: msg.value = amountETH + oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The deadline of this request /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function addLiquidity( address pool, address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external override payable ensure(deadline) returns (address xtoken, uint liquidity) { // 1. Transfer token to pool if (token != address(0)) { TransferHelper.safeTransferFrom(token, msg.sender, pool, amountToken); } // 2. Add liquidity, and increase xtoken (xtoken, liquidity) = ICoFiXPool(pool).mint { value: msg.value } (token, to, amountETH, amountToken, to); // The number of shares should not be lower than the expected minimum value require(liquidity >= liquidityMin, "CoFiXRouter: less liquidity than expected"); } /// @dev Maker add liquidity to pool, get pool token (mint XToken) and stake automatically /// (notice: msg.value = amountETH + oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The deadline of this request /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function addLiquidityAndStake( address pool, address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external override payable ensure(deadline) returns (address xtoken, uint liquidity) { // 1. Transfer token to pool if (token != address(0)) { TransferHelper.safeTransferFrom(token, msg.sender, pool, amountToken); } // 2. Add liquidity, and increase xtoken address cofixVaultForStaking = _cofixVaultForStaking; (xtoken, liquidity) = ICoFiXPool(pool).mint { value: msg.value } (token, cofixVaultForStaking, amountETH, amountToken, to); // The number of shares should not be lower than the expected minimum value require(liquidity >= liquidityMin, "CoFiXRouter: less liquidity than expected"); // 3. Stake xtoken to CoFiXVaultForStaking ICoFiXVaultForStaking(cofixVaultForStaking).routerStake(xtoken, to, liquidity); } /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) /// (notice: msg.value = oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountETHMin The minimum amount of ETH wanted to get from pool /// @param to The target address receiving the Token /// @param deadline The deadline of this request /// @return amountETH The real amount of ETH transferred from the pool /// @return amountToken The real amount of Token transferred from the pool function removeLiquidityGetTokenAndETH( address pool, address token, uint liquidity, uint amountETHMin, address to, uint deadline ) external override payable ensure(deadline) returns (uint amountETH, uint amountToken) { // 0. Get xtoken corresponding to the token address xtoken = ICoFiXPool(pool).getXToken(token); // 1. Transfer xtoken to pool TransferHelper.safeTransferFrom(xtoken, msg.sender, pool, liquidity); // 2. Remove liquidity and return tokens (amountETH, amountToken) = ICoFiXPool(pool).burn { value: msg.value } (token, to, liquidity, to); // 3. amountETH must not less than expected require(amountETH >= amountETHMin, "CoFiXRouter: less eth than expected"); } /// @dev Swap exact tokens for tokens /// @param path Routing path. If you need to exchange through multi-level routes, you need to write down all /// token addresses (ETH address is represented by 0) of the exchange path /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param amountOutMin The minimum amount of ETH a trader want to swap out of pool /// @param to The target address receiving the ETH /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The deadline of this request /// @return amountOut The real amount of Token transferred out of pool function swapExactTokensForTokens( address[] calldata path, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable override ensure(deadline) returns (uint amountOut) { uint mined; if (path.length == 2) { address src = path[0]; address dest = path[1]; // 0. Get pool address for trade pair address pool = _pairFor(src, dest); // 1. Transfer token to the pool if (src != address(0)) { TransferHelper.safeTransferFrom(src, msg.sender, pool, amountIn); } // 2. Trade (amountOut, mined) = ICoFiXPool(pool).swap { value: msg.value } (src, dest, amountIn, to, to); } else { // 1. Trade (amountOut, mined) = _swap(path, amountIn, to); // 2. Any remaining ETH in the Router is considered to be the user's and is forwarded to // the address specified by the Router uint balance = address(this).balance; if (balance > 0) { payable(to).transfer(balance); } } // 3. amountOut must not less than expected require(amountOut >= amountOutMin, "CoFiXRouter: got less than expected"); // 4. Mining cofi for trade _mint(mined, rewardTo); } // Trade function _swap( address[] calldata path, uint amountIn, address to ) private returns ( uint amountOut, uint totalMined ) { // Initialize totalMined = 0; // Get the first pair address token0 = path[0]; address token1 = path[1]; address pool = _pairFor(token0, token1); // Transfer token to first pool if (token0 != address(0)) { TransferHelper.safeTransferFrom(token0, to, pool, amountIn); } uint mined; // Execute the exchange transaction according to the routing path for (uint i = 1; ; ) { // Address to receive funds for this transaction address recv = to; // Next token address. 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF means empty address next = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; if (++i < path.length) { next = path[i]; // While the next token address still exists, the fund receiving address is the next transaction pair recv = _pairFor(token1, next); } // Perform an exchange transaction. If token1 is ETH, the fund receiving address is address(this). // Q: The solution of openzeppelin-upgrades may cause transfer eth fail, // It needs to be validated and resolved // A: Since the execution entry is at CoFiXRouter, the proxy address of the CoFiXRouter has // already been read, which reduces the gas consumption for subsequent reads, So the gas // consumption of the later receive() transfer to CoFiXRouter is reduced without an error, // so OpenZeppelin is now available, The upgradable solution of does not cause the problem // of converting ETH from the capital pool to CoFixRouter to fail. (amountIn, mined) = ICoFiXPool(pool).swap { value: address(this).balance } (token0, token1, amountIn, token1 == address(0) ? address(this) : recv, address(this)); // Increase total mining totalMined += mined; // Record the amount of money exchanged this time //amounts[i - 1] = amountIn; // next equal to 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF means trade is over if (next == 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) { break; } // Switch to the next trade pair in the routing path token0 = token1; token1 = next; pool = recv; } amountOut = amountIn; } // Mint CoFi to target address, and increase for CNode function _mint(uint mined, address rewardTo) private { if (mined > 0) { uint cnodeReward = mined / 10; // The amount available to the trader CoFiToken(COFI_TOKEN_ADDRESS).mint(rewardTo, mined - cnodeReward); // Increase for CNode _cnodeReward += cnodeReward; } } /// @dev Acquire the transaction mining share of the target XToken /// @param xtoken The destination XToken address /// @return Target XToken's transaction mining share function getTradeReward(address xtoken) external view override returns (uint) { // Only CNode has a share of trading out, not market making if (xtoken == CNODE_TOKEN_ADDRESS) { return _cnodeReward; } return 0; } receive() external payable { } }
3. amountOut must not less than expected
require(amountOut >= amountOutMin, "CoFiXRouter: got less than expected");
2,185,567
[ 1, 23, 18, 3844, 1182, 1297, 486, 5242, 2353, 2665, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2583, 12, 8949, 1182, 1545, 3844, 1182, 2930, 16, 315, 4249, 42, 77, 60, 8259, 30, 2363, 5242, 2353, 2665, 8863, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /** * @title Token contract for Legends of Venari Alpha Passes * @dev This contract allows the distribution of * Legends of Venari Passes in the form of a presale and main sale. * * Users can mint from Talaw, Vestal, or Azule in either sales. * * * Smart contract work done by lenopix.eth */ contract LegendsOfVenariAlphaPass is ERC721Enumerable, Ownable, ReentrancyGuard { using ECDSA for bytes32; using Address for address; event Mint( address indexed to, uint256 indexed tokenId, uint256 indexed factionId ); // Faction Ids uint256 public constant TALAW_ID = 0; uint256 public constant VESTAL_ID = 1; uint256 public constant AZULE_ID = 2; // Minting constants uint256 public maxMintPerTransaction; uint256 public MINT_SUPPLY_PER_FACTION; uint256 public TEAM_SUPPLY_PER_FACTION; // Current price: 0.0011 uint256 public constant MINT_PRICE = 110000000000000000; // Keep track of supply uint256 public talawMintCount = 0; uint256 public vestalMintCount = 0; uint256 public azuleMintCount = 0; // Sale toggles bool private _isPresaleActive = false; bool private _isSaleActive = false; // Tracks the faction for a token mapping(uint256 => uint256) factionForToken; // Presale mapping(address => bool) private presaleClaimed; // Everyone who got in on the presale can only claim once. address private signVerifier = 0xf79e8a0d24cF91EE36c8a7e7dB8Aa95fbF7d6a8f; // Base URI string private _uri; // Merkle Root bytes32 immutable public root; // Last Token ID starts from the end of Gilded Pass ID uint256 lastTokenId = 600; constructor( uint256 mintSupply, uint256 teamSupply, uint256 maxMint, bytes32 merkleroot ) ERC721("Legends of Venari Alpha Pass", "LVP") { MINT_SUPPLY_PER_FACTION = mintSupply; TEAM_SUPPLY_PER_FACTION = teamSupply; maxMintPerTransaction = maxMint; root = merkleroot; } // @dev Returns the faction of the token id function getFaction(uint256 tokenId) external view returns (uint256) { require(_exists(tokenId), "Query for nonexistent token id"); return factionForToken[tokenId]; } // @dev Returns whether a user has claimed from presale function getPresaleClaimed(address user) external view returns (bool) { return presaleClaimed[user]; } // @dev Returns the enabled/disabled status for presale function getPreSaleState() external view returns (bool) { return _isPresaleActive; } // @dev Returns the enabled/disabled status for minting function getSaleState() external view returns (bool) { return _isSaleActive; } // @dev Returns the mint count of a specific faction function getMintCount(uint256 factionId) external view returns (uint256) { require(_isValidFactionId(factionId), "Faction is not valid"); if (factionId == TALAW_ID) { return talawMintCount; } else if (factionId == VESTAL_ID) { return vestalMintCount; } else if (factionId == AZULE_ID) { return azuleMintCount; } return 0; } // @dev Allows to set the baseURI dynamically // @param uri The base uri for the metadata store function setBaseURI(string memory uri) external onlyOwner { _uri = uri; } // @dev Sets a new signature verifier function setSignVerifier(address verifier) external onlyOwner { signVerifier = verifier; } // @dev Dynamically set the max mints a user can do in the main sale function setMaxMintPerTransaction(uint256 maxMint) external onlyOwner { maxMintPerTransaction = maxMint; } // Presale function presaleMint( uint256 tokenId, bytes32[] calldata proof, uint256 factionId ) external payable { require(_verify(_leaf(msg.sender, tokenId), proof), "Invalid merkle proof"); require(!presaleClaimed[msg.sender], "Already claimed with this address"); require(_isPresaleActive, "Presale not active"); require(!_isSaleActive, "Cannot mint while main sale is active"); require(_isValidFactionId(factionId), "Faction is not valid"); require(MINT_PRICE == msg.value, "ETH sent does not match required payment"); presaleClaimed[msg.sender] = true; _handleFactionMint(1, factionId, msg.sender, MINT_SUPPLY_PER_FACTION); } function _leaf(address account, uint256 tokenId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(tokenId, account)); } function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { return MerkleProof.verify(proof, root, leaf); } mapping(uint256 => bool) partnerNonceUsed; mapping(address => uint256) basePassNonce; // @dev Partner Mint - For partners who we allow to batch mint // @param factionIds The factions associated with the tokens // @param addresses The addresses that the tokens will be distributed to // @param sig Server side signature authorizing user to use the presale function partnerMint( uint256[] memory factionIds, uint256 nonce, bytes memory sig ) external payable nonReentrant { require(_isPresaleActive, "Presale not active"); require( (MINT_PRICE * factionIds.length) == msg.value, "ETH sent does not match required payment" ); require(!partnerNonceUsed[nonce], "Nonce already used."); // Verify signature bytes32 message = getPartnerSigningHash( msg.sender, factionIds, nonce ).toEthSignedMessageHash(); require( ECDSA.recover(message, sig) == signVerifier, "Permission to call this function failed" ); partnerNonceUsed[nonce] = true; // Mint for (uint256 i = 0; i < factionIds.length; i++) { uint256 factionId = factionIds[i]; require(_isValidFactionId(factionId), "Faction is not valid"); _handleFactionMint(1, factionId, msg.sender, MINT_SUPPLY_PER_FACTION); } } // @dev Main sale mint // @param tokensCount The tokens a user wants to purchase // @param factionId Talaw: 0, Vestal: 1, Azule: 2 function mint(uint256 tokenCount, uint256 factionId) external payable nonReentrant { require(_isValidFactionId(factionId), "Faction is not valid"); require(_isSaleActive, "Sale not active"); require(tokenCount > 0, "Must mint at least 1 token"); require(tokenCount <= maxMintPerTransaction, "Token count exceeds limit"); require( (MINT_PRICE * tokenCount) == msg.value, "ETH sent does not match required payment" ); _handleFactionMint(tokenCount, factionId, msg.sender, MINT_SUPPLY_PER_FACTION); } // @dev Private mint function reserved for company. // THIS SHOULD ONLY BE DONE AFTER THE MAIN SALE HAS FINISHED // 50 of each faction is reserved. // @param recipient The user receiving the tokens // @param tokenCount The number of tokens to distribute // @param factionId Talaw: 0, Vestal: 1, Azule: 2 function mintToAddress( address[] memory addresses, uint256[] memory factionIds ) external onlyOwner { require(factionIds.length == addresses.length, "Faction ids much have the same length as addresses"); // Mint for (uint256 i = 0; i < factionIds.length; i++) { uint256 factionId = factionIds[i]; require(_isValidFactionId(factionId), "Faction is not valid"); _handleFactionMint(1, factionId, addresses[i], MINT_SUPPLY_PER_FACTION + TEAM_SUPPLY_PER_FACTION); } } function redeemBasePass( uint256 factionId, bytes memory sig ) external { require(_isValidFactionId(factionId), "Faction does not exist"); // Verify signature bytes32 message = getBasePassSigningHash( msg.sender, factionId ).toEthSignedMessageHash(); require( ECDSA.recover(message, sig) == signVerifier, "Permission to call this function failed" ); basePassNonce[msg.sender]++; if (factionId == TALAW_ID) { talawMintCount++; } else if (factionId == VESTAL_ID) { vestalMintCount++; } else if (factionId == AZULE_ID) { azuleMintCount++; } _mint(msg.sender, 1, factionId); } // @dev Allows to enable/disable minting of presale function flipPresaleState() external onlyOwner { _isPresaleActive = !_isPresaleActive; } // @dev Allows to enable/disable minting of main sale function flipSaleState() external onlyOwner { _isSaleActive = !_isSaleActive; } function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function getPartnerSigningHash( address sender, uint256[] memory factionIds, uint256 nonce ) public pure returns (bytes32) { return keccak256( abi.encodePacked(sender, factionIds, nonce) ); } function getBasePassSigningHash( address sender, uint256 factionId ) public view returns (bytes32) { return keccak256( abi.encodePacked(sender, factionId, basePassNonce[sender]) ); } function _baseURI() internal view override returns (string memory) { return _uri; } function _handleFactionMint( uint256 tokenCount, uint256 factionId, address recipient, uint256 totalSupply ) private { if (factionId == TALAW_ID) { require(talawMintCount < totalSupply, "This faction has been fully minted"); require((talawMintCount + tokenCount) <= totalSupply, "Cannot purchase more than the available supply"); talawMintCount += tokenCount; } else if (factionId == VESTAL_ID) { require(vestalMintCount < totalSupply, "This faction has been fully minted"); require((vestalMintCount + tokenCount) <= totalSupply, "Cannot purchase more than the available supply"); vestalMintCount += tokenCount; } else if (factionId == AZULE_ID) { require(azuleMintCount < totalSupply, "This faction has been fully minted"); require((azuleMintCount + tokenCount) <= totalSupply, "Cannot purchase more than the available supply"); azuleMintCount += tokenCount; } _mint(recipient, tokenCount, factionId); } function _mint( address recipient, uint256 tokenCount, uint256 factionId ) private { for (uint256 i = 0; i < tokenCount; i++) { uint256 tokenId = lastTokenId + i; _mintWithTokenId(recipient, tokenId, factionId); } lastTokenId += tokenCount; } function _mintWithTokenId( address recipient, uint256 tokenId, uint256 factionId ) private { factionForToken[tokenId] = factionId; emit Mint(recipient, tokenId, factionId); _safeMint(recipient, tokenId); } function _isValidFactionId(uint256 factionId) private pure returns (bool) { return factionId == TALAW_ID || factionId == AZULE_ID || factionId == VESTAL_ID; } }
@dev Returns whether a user has claimed from presale
function getPresaleClaimed(address user) external view returns (bool) { return presaleClaimed[user]; }
15,826,200
[ 1, 1356, 2856, 279, 729, 711, 7516, 329, 628, 4075, 5349, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1689, 455, 5349, 9762, 329, 12, 2867, 729, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 4075, 5349, 9762, 329, 63, 1355, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract UserRegistryInterface { event AddAddress(address indexed who); event AddIdentity(address indexed who); function knownAddress(address _who) public constant returns(bool); function hasIdentity(address _who) public constant returns(bool); function systemAddresses(address _to, address _from) public constant returns(bool); } contract MultiOwners { event AccessGrant(address indexed owner); event AccessRevoke(address indexed owner); mapping(address => bool) owners; address public publisher; function MultiOwners() public { owners[msg.sender] = true; publisher = msg.sender; } modifier onlyOwner() { require(owners[msg.sender] == true); _; } function isOwner() public constant returns (bool) { return owners[msg.sender] ? true : false; } function checkOwner(address maybe_owner) public constant returns (bool) { return owners[maybe_owner] ? true : false; } function grant(address _owner) onlyOwner public { owners[_owner] = true; AccessGrant(_owner); } function revoke(address _owner) onlyOwner public { require(_owner != publisher); require(msg.sender != _owner); owners[_owner] = false; AccessRevoke(_owner); } } contract TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenInterface is ERC20 { string public name; string public symbol; uint public decimals; } contract MintableTokenInterface is TokenInterface { address public owner; function mint(address beneficiary, uint amount) public returns(bool); function transferOwnership(address nextOwner) public; } /** * Complex crowdsale with huge posibilities * Core features: * - Whitelisting * - Min\max invest amounts * - Only known users * - Buy with allowed tokens * - Oraclize based pairs (ETH to TOKEN) * - Revert\refund * - Personal bonuses * - Amount bonuses * - Total supply bonuses * - Early birds bonuses * - Extra distribution (team, foundation and also) * - Soft and hard caps * - Finalization logics **/ contract Crowdsale is MultiOwners, TokenRecipient { using SafeMath for uint; // ██████╗ ██████╗ ███╗ ██╗███████╗████████╗███████╗ // ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔════╝ // ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ███████╗ // ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ╚════██║ // ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ███████║ // ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚══════╝ uint public constant VERSION = 0x1; enum State { Setup, // Non active yet (require to be setuped) Active, // Crowdsale in a live Claim, // Claim funds by owner Refund, // Unsucceseful crowdsale (refund ether) History // Close and store only historical fact of existence } struct PersonalBonusRecord { uint bonus; address refererAddress; uint refererBonus; } struct WhitelistRecord { bool allow; uint min; uint max; } // ██████╗ ██████╗ ███╗ ██╗███████╗██╗███╗ ██╗ ██████╗ // ██╔════╝██╔═══██╗████╗ ██║██╔════╝██║████╗ ██║██╔════╝ // ██║ ██║ ██║██╔██╗ ██║█████╗ ██║██╔██╗ ██║██║ ███╗ // ██║ ██║ ██║██║╚██╗██║██╔══╝ ██║██║╚██╗██║██║ ██║ // ╚██████╗╚██████╔╝██║ ╚████║██║ ██║██║ ╚████║╚██████╔╝ // ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ bool public isWhitelisted; // Should be whitelisted to buy tokens bool public isKnownOnly; // Should be known user to buy tokens bool public isAmountBonus; // Enable amount bonuses in crowdsale? bool public isEarlyBonus; // Enable early bird bonus in crowdsale? bool public isTokenExchange; // Allow to buy tokens for another tokens? bool public isAllowToIssue; // Allow to issue tokens with tx hash (ex bitcoin) bool public isDisableEther; // Disable purchase with the Ether bool public isExtraDistribution; // Should distribute extra tokens to special contract? bool public isTransferShipment; // Will ship token via minting? bool public isCappedInEther; // Should be capped in Ether bool public isPersonalBonuses; // Should check personal beneficiary bonus? bool public isAllowClaimBeforeFinalization; // Should allow to claim funds before finalization? bool public isMinimumValue; // Validate minimum amount to purchase bool public isMinimumInEther; // Is minimum amount setuped in Ether or Tokens? uint public minimumPurchaseValue; // How less buyer could to purchase // List of allowed beneficiaries mapping (address => WhitelistRecord) public whitelist; // Known users registry (required to known rules) UserRegistryInterface public userRegistry; mapping (uint => uint) public amountBonuses; // Amount bonuses uint[] public amountSlices; // Key is min amount of buy uint public amountSlicesCount; // 10000 - 100.00% bonus over base pricetotaly free // 5000 - 50.00% bonus // 0 - no bonus at all mapping (uint => uint) public timeBonuses; // Time bonuses uint[] public timeSlices; // Same as amount but key is seconds after start uint public timeSlicesCount; mapping (address => PersonalBonusRecord) public personalBonuses; // personal bonuses MintableTokenInterface public token; // The token being sold uint public tokenDecimals; // Token decimals mapping (address => TokenInterface) public allowedTokens; // allowed tokens list mapping (address => uint) public tokensValues; // TOKEN to ETH conversion rate (oraclized) uint public startTime; // start and end timestamps where uint public endTime; // investments are allowed (both inclusive) address public wallet; // address where funds are collected uint public price; // how many token (1 * 10 ** decimals) a buyer gets per wei uint public hardCap; uint public softCap; address public extraTokensHolder; // address to mint/transfer extra tokens (0 – 0%, 1000 - 100.0%) uint public extraDistributionPart; // % of extra distribution // ███████╗████████╗ █████╗ ████████╗███████╗ // ██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██╔════╝ // ███████╗ ██║ ███████║ ██║ █████╗ // ╚════██║ ██║ ██╔══██║ ██║ ██╔══╝ // ███████║ ██║ ██║ ██║ ██║ ███████╗ // ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // amount of raised money in wei uint public weiRaised; // Current crowdsale state State public state; // Temporal balances to pull tokens after token sale // requires to ship required balance to smart contract mapping (address => uint) public beneficiaryInvest; uint public soldTokens; mapping (address => uint) public weiDeposit; mapping (address => mapping(address => uint)) public altDeposit; modifier inState(State _target) { require(state == _target); _; } // ███████╗██╗ ██╗███████╗███╗ ██╗████████╗███████╗ // ██╔════╝██║ ██║██╔════╝████╗ ██║╚══██╔══╝██╔════╝ // █████╗ ██║ ██║█████╗ ██╔██╗ ██║ ██║ ███████╗ // ██╔══╝ ╚██╗ ██╔╝██╔══╝ ██║╚██╗██║ ██║ ╚════██║ // ███████╗ ╚████╔╝ ███████╗██║ ╚████║ ██║ ███████║ // ╚══════╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝ event EthBuy( address indexed purchaser, address indexed beneficiary, uint value, uint amount); event HashBuy( address indexed beneficiary, uint value, uint amount, uint timestamp, bytes32 indexed bitcoinHash); event AltBuy( address indexed beneficiary, address indexed allowedToken, uint allowedTokenValue, uint ethValue, uint shipAmount); event ShipTokens(address indexed owner, uint amount); event Sanetize(); event Finalize(); event Whitelisted(address indexed beneficiary, uint min, uint max); event PersonalBonus(address indexed beneficiary, address indexed referer, uint bonus, uint refererBonus); event FundsClaimed(address indexed owner, uint amount); // ███████╗███████╗████████╗██╗ ██╗██████╗ ███╗ ███╗███████╗████████╗██╗ ██╗ ██████╗ ██████╗ ███████╗ // ██╔════╝██╔════╝╚══██╔══╝██║ ██║██╔══██╗ ████╗ ████║██╔════╝╚══██╔══╝██║ ██║██╔═══██╗██╔══██╗██╔════╝ // ███████╗█████╗ ██║ ██║ ██║██████╔╝ ██╔████╔██║█████╗ ██║ ███████║██║ ██║██║ ██║███████╗ // ╚════██║██╔══╝ ██║ ██║ ██║██╔═══╝ ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██║██║ ██║╚════██║ // ███████║███████╗ ██║ ╚██████╔╝██║ ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║╚██████╔╝██████╔╝███████║ // ╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝ function setFlags( // Should be whitelisted to buy tokens bool _isWhitelisted, // Should be known user to buy tokens bool _isKnownOnly, // Enable amount bonuses in crowdsale? bool _isAmountBonus, // Enable early bird bonus in crowdsale? bool _isEarlyBonus, // Allow to buy tokens for another tokens? bool _isTokenExchange, // Allow to issue tokens with tx hash (ex bitcoin) bool _isAllowToIssue, // Should reject purchases with Ether? bool _isDisableEther, // Should mint extra tokens for future distribution? bool _isExtraDistribution, // Will ship token via minting? bool _isTransferShipment, // Should be capped in ether bool _isCappedInEther, // Should beneficiaries pull their tokens? bool _isPersonalBonuses, // Should allow to claim funds before finalization? bool _isAllowClaimBeforeFinalization) inState(State.Setup) onlyOwner public { isWhitelisted = _isWhitelisted; isKnownOnly = _isKnownOnly; isAmountBonus = _isAmountBonus; isEarlyBonus = _isEarlyBonus; isTokenExchange = _isTokenExchange; isAllowToIssue = _isAllowToIssue; isDisableEther = _isDisableEther; isExtraDistribution = _isExtraDistribution; isTransferShipment = _isTransferShipment; isCappedInEther = _isCappedInEther; isPersonalBonuses = _isPersonalBonuses; isAllowClaimBeforeFinalization = _isAllowClaimBeforeFinalization; } // ! Could be changed in process of sale (since 02.2018) function setMinimum(uint _amount, bool _inToken) onlyOwner public { if (_amount == 0) { isMinimumValue = false; minimumPurchaseValue = 0; } else { isMinimumValue = true; isMinimumInEther = !_inToken; minimumPurchaseValue = _amount; } } function setPrice(uint _price) inState(State.Setup) onlyOwner public { require(_price > 0); // SetPrice(msg.sender, price, _price); price = _price; } function setSoftHardCaps(uint _softCap, uint _hardCap) inState(State.Setup) onlyOwner public { // SetSoftCap(msg.sender, softCap, _softCap); // SetHardCap(msg.sender, hardCap, _hardCap); hardCap = _hardCap; softCap = _softCap; } function setTime(uint _start, uint _end) inState(State.Setup) onlyOwner public { require(_start < _end); require(_end > block.timestamp); // SetStartTime(msg.sender, startTime, _start); // SetEndTime(msg.sender, endTime, _end); startTime = _start; endTime = _end; } function setToken(address _tokenAddress) inState(State.Setup) onlyOwner public { token = MintableTokenInterface(_tokenAddress); tokenDecimals = token.decimals(); } function setWallet(address _wallet) inState(State.Setup) onlyOwner public { require(_wallet != address(0)); // SetWallet(msg.sender, wallet, _wallet); wallet = _wallet; } function setRegistry(address _registry) inState(State.Setup) onlyOwner public { require(_registry != address(0)); // SetRegistry(msg.sender, userRegistry, _registry); userRegistry = UserRegistryInterface(_registry); } function setExtraDistribution(address _holder, uint _extraPart) inState(State.Setup) onlyOwner public { require(_holder != address(0)); // SetExtraTokensHolder(msg.sender, extraTokensHolder, _holder); // SetExtraTokensPart(msg.sender, extraDistributionPart, _extraPart); extraTokensHolder = _holder; extraDistributionPart = _extraPart; } function setAmountBonuses(uint[] _amountSlices, uint[] _bonuses) inState(State.Setup) onlyOwner public { require(_amountSlices.length > 1); require(_bonuses.length == _amountSlices.length); uint lastSlice = 0; for (uint index = 0; index < _amountSlices.length; index++) { require(_amountSlices[index] > lastSlice); lastSlice = _amountSlices[index]; amountSlices.push(lastSlice); amountBonuses[lastSlice] = _bonuses[index]; // AddAmountSlice(msg.sender, _amountSlices[index], _bonuses[index]); } amountSlicesCount = amountSlices.length; } function setTimeBonuses(uint[] _timeSlices, uint[] _bonuses) // ! Not need to check state since changes at 02.2018 // inState(State.Setup) onlyOwner public { // Only once in life time // ! Time bonuses is changable after 02.2018 // require(timeSlicesCount == 0); require(_timeSlices.length > 0); require(_bonuses.length == _timeSlices.length); uint lastSlice = 0; uint lastBonus = 10000; if (timeSlicesCount > 0) { // ! Since time bonuses is changable we should take latest first lastSlice = timeSlices[timeSlicesCount - 1]; lastBonus = timeBonuses[lastSlice]; } for (uint index = 0; index < _timeSlices.length; index++) { require(_timeSlices[index] > lastSlice); // ! Add check for next bonus is equal or less than previous require(_bonuses[index] <= lastBonus); // ? Should we check bonus in a future lastSlice = _timeSlices[index]; timeSlices.push(lastSlice); timeBonuses[lastSlice] = _bonuses[index]; } timeSlicesCount = timeSlices.length; } function setTokenExcange(address _token, uint _value) inState(State.Setup) onlyOwner public { allowedTokens[_token] = TokenInterface(_token); updateTokenValue(_token, _value); } function saneIt() inState(State.Setup) onlyOwner public { require(startTime < endTime); require(endTime > now); require(price > 0); require(wallet != address(0)); require(token != address(0)); if (isKnownOnly) { require(userRegistry != address(0)); } if (isAmountBonus) { require(amountSlicesCount > 0); } // ! not needed anymore (since 02.2018 time bonuses isn't constant) // if (isEarlyBonus) { // require(timeSlicesCount > 0); // } if (isExtraDistribution) { require(extraTokensHolder != address(0)); } if (isTransferShipment) { require(token.balanceOf(address(this)) >= hardCap); } else { require(token.owner() == address(this)); } state = State.Active; } function finalizeIt(address _futureOwner) inState(State.Active) onlyOwner public { require(ended()); token.transferOwnership(_futureOwner); if (success()) { state = State.Claim; } else { state = State.Refund; } } function historyIt() inState(State.Claim) onlyOwner public { require(address(this).balance == 0); state = State.History; } // ███████╗██╗ ██╗███████╗ ██████╗██╗ ██╗████████╗███████╗ // ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║ ██║╚══██╔══╝██╔════╝ // █████╗ ╚███╔╝ █████╗ ██║ ██║ ██║ ██║ █████╗ // ██╔══╝ ██╔██╗ ██╔══╝ ██║ ██║ ██║ ██║ ██╔══╝ // ███████╗██╔╝ ██╗███████╗╚██████╗╚██████╔╝ ██║ ███████╗ // ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝ function calculateEthAmount( address _beneficiary, uint _weiAmount, uint _time, uint _totalSupply ) public constant returns( uint calculatedTotal, uint calculatedBeneficiary, uint calculatedExtra, uint calculatedreferer, address refererAddress) { _totalSupply; uint bonus = 0; if (isAmountBonus) { bonus = bonus.add(calculateAmountBonus(_weiAmount)); } if (isEarlyBonus) { bonus = bonus.add(calculateTimeBonus(_time.sub(startTime))); } if (isPersonalBonuses && personalBonuses[_beneficiary].bonus > 0) { bonus = bonus.add(personalBonuses[_beneficiary].bonus); } calculatedBeneficiary = _weiAmount.mul(10 ** tokenDecimals).div(price); if (bonus > 0) { calculatedBeneficiary = calculatedBeneficiary.add(calculatedBeneficiary.mul(bonus).div(10000)); } if (isExtraDistribution) { calculatedExtra = calculatedBeneficiary.mul(extraDistributionPart).div(10000); } if (isPersonalBonuses && personalBonuses[_beneficiary].refererAddress != address(0) && personalBonuses[_beneficiary].refererBonus > 0) { calculatedreferer = calculatedBeneficiary.mul(personalBonuses[_beneficiary].refererBonus).div(10000); refererAddress = personalBonuses[_beneficiary].refererAddress; } calculatedTotal = calculatedBeneficiary.add(calculatedExtra).add(calculatedreferer); } function calculateAmountBonus(uint _changeAmount) public constant returns(uint) { uint bonus = 0; for (uint index = 0; index < amountSlices.length; index++) { if(amountSlices[index] > _changeAmount) { break; } bonus = amountBonuses[amountSlices[index]]; } return bonus; } function calculateTimeBonus(uint _at) public constant returns(uint) { uint bonus = 0; for (uint index = timeSlices.length; index > 0; index--) { if(timeSlices[index - 1] < _at) { break; } bonus = timeBonuses[timeSlices[index - 1]]; } return bonus; } function validPurchase( address _beneficiary, uint _weiAmount, uint _tokenAmount, uint _extraAmount, uint _totalAmount, uint _time) public constant returns(bool) { _tokenAmount; _extraAmount; // ! Check min purchase value (since 02.2018) if (isMinimumValue) { // ! Check min purchase value in ether (since 02.2018) if (isMinimumInEther && _weiAmount < minimumPurchaseValue) { return false; } // ! Check min purchase value in tokens (since 02.2018) if (!isMinimumInEther && _tokenAmount < minimumPurchaseValue) { return false; } } if (_time < startTime || _time > endTime) { return false; } if (isKnownOnly && !userRegistry.knownAddress(_beneficiary)) { return false; } uint finalBeneficiaryInvest = beneficiaryInvest[_beneficiary].add(_weiAmount); uint finalTotalSupply = soldTokens.add(_totalAmount); if (isWhitelisted) { WhitelistRecord storage record = whitelist[_beneficiary]; if (!record.allow || record.min > finalBeneficiaryInvest || record.max < finalBeneficiaryInvest) { return false; } } if (isCappedInEther) { if (weiRaised.add(_weiAmount) > hardCap) { return false; } } else { if (finalTotalSupply > hardCap) { return false; } } return true; } function updateTokenValue(address _token, uint _value) onlyOwner public { require(address(allowedTokens[_token]) != address(0x0)); tokensValues[_token] = _value; } // ██████╗ ███████╗ █████╗ ██████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ // ██████╔╝█████╗ ███████║██║ ██║ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ // ██║ ██║███████╗██║ ██║██████╔╝ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ function success() public constant returns(bool) { if (isCappedInEther) { return weiRaised >= softCap; } else { return token.totalSupply() >= softCap; } } function capped() public constant returns(bool) { if (isCappedInEther) { return weiRaised >= hardCap; } else { return token.totalSupply() >= hardCap; } } function ended() public constant returns(bool) { return capped() || block.timestamp >= endTime; } // ██████╗ ██╗ ██╗████████╗███████╗██╗██████╗ ███████╗ // ██╔═══██╗██║ ██║╚══██╔══╝██╔════╝██║██╔══██╗██╔════╝ // ██║ ██║██║ ██║ ██║ ███████╗██║██║ ██║█████╗ // ██║ ██║██║ ██║ ██║ ╚════██║██║██║ ██║██╔══╝ // ╚██████╔╝╚██████╔╝ ██║ ███████║██║██████╔╝███████╗ // ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝╚═════╝ ╚══════╝ // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) inState(State.Active) public payable { require(!isDisableEther); uint shipAmount = sellTokens(_beneficiary, msg.value, block.timestamp); require(shipAmount > 0); forwardEther(); } function buyWithHash(address _beneficiary, uint _value, uint _timestamp, bytes32 _hash) inState(State.Active) onlyOwner public { require(isAllowToIssue); uint shipAmount = sellTokens(_beneficiary, _value, _timestamp); require(shipAmount > 0); HashBuy(_beneficiary, _value, shipAmount, _timestamp, _hash); } function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public { if (_token == address(token)) { TokenInterface(_token).transferFrom(_from, address(this), _value); return; } require(isTokenExchange); // Debug(msg.sender, appendUintToString("Should be equal: ", toUint(_extraData))); // Debug(msg.sender, appendUintToString("and: ", tokensValues[_token])); require(toUint(_extraData) == tokensValues[_token]); require(tokensValues[_token] > 0); require(forwardTokens(_from, _token, _value)); uint weiValue = _value.mul(tokensValues[_token]).div(10 ** allowedTokens[_token].decimals()); require(weiValue > 0); Debug(msg.sender, appendUintToString("Token to wei: ", weiValue)); uint shipAmount = sellTokens(_from, weiValue, block.timestamp); require(shipAmount > 0); AltBuy(_from, _token, _value, weiValue, shipAmount); } function claimFunds() onlyOwner public returns(bool) { require(state == State.Claim || (isAllowClaimBeforeFinalization && success())); wallet.transfer(address(this).balance); return true; } function claimTokenFunds(address _token) onlyOwner public returns(bool) { require(state == State.Claim || (isAllowClaimBeforeFinalization && success())); uint balance = allowedTokens[_token].balanceOf(address(this)); require(balance > 0); require(allowedTokens[_token].transfer(wallet, balance)); return true; } function claimRefundEther(address _beneficiary) inState(State.Refund) public returns(bool) { require(weiDeposit[_beneficiary] > 0); _beneficiary.transfer(weiDeposit[_beneficiary]); return true; } function claimRefundTokens(address _beneficiary, address _token) inState(State.Refund) public returns(bool) { require(altDeposit[_token][_beneficiary] > 0); require(allowedTokens[_token].transfer(_beneficiary, altDeposit[_token][_beneficiary])); return true; } function addToWhitelist(address _beneficiary, uint _min, uint _max) onlyOwner public { require(_beneficiary != address(0)); require(_min <= _max); if (_max == 0) { _max = 10 ** 40; // should be huge enough? :0 } whitelist[_beneficiary] = WhitelistRecord(true, _min, _max); Whitelisted(_beneficiary, _min, _max); } function setPersonalBonus( address _beneficiary, uint _bonus, address _refererAddress, uint _refererBonus) onlyOwner public { personalBonuses[_beneficiary] = PersonalBonusRecord( _bonus, _refererAddress, _refererBonus ); PersonalBonus(_beneficiary, _refererAddress, _bonus, _refererBonus); } // ██╗███╗ ██╗████████╗███████╗██████╗ ███╗ ██╗ █████╗ ██╗ ███████╗ // ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗████╗ ██║██╔══██╗██║ ██╔════╝ // ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝██╔██╗ ██║███████║██║ ███████╗ // ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗██║╚██╗██║██╔══██║██║ ╚════██║ // ██║██║ ╚████║ ██║ ███████╗██║ ██║██║ ╚████║██║ ██║███████╗███████║ // ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚══════╝ // low level token purchase function function sellTokens(address _beneficiary, uint _weiAmount, uint timestamp) inState(State.Active) internal returns(uint) { uint beneficiaryTokens; uint extraTokens; uint totalTokens; uint refererTokens; address refererAddress; (totalTokens, beneficiaryTokens, extraTokens, refererTokens, refererAddress) = calculateEthAmount( _beneficiary, _weiAmount, timestamp, token.totalSupply()); require(validPurchase(_beneficiary, // Check if current purchase is valid _weiAmount, beneficiaryTokens, extraTokens, totalTokens, timestamp)); weiRaised = weiRaised.add(_weiAmount); // update state (wei amount) beneficiaryInvest[_beneficiary] = beneficiaryInvest[_beneficiary].add(_weiAmount); shipTokens(_beneficiary, beneficiaryTokens); // ship tokens to beneficiary // soldTokens = soldTokens.add(beneficiaryTokens); EthBuy(msg.sender, // Fire purchase event _beneficiary, _weiAmount, beneficiaryTokens); ShipTokens(_beneficiary, beneficiaryTokens); if (isExtraDistribution) { // calculate and //! Ship to crowdsale itself to transfer it against minting shipTokens(address(this), extraTokens); token.transfer(extraTokensHolder, extraTokens); // soldTokens = soldTokens.add(extraTokens); ShipTokens(extraTokensHolder, extraTokens); } if (isPersonalBonuses) { PersonalBonusRecord storage record = personalBonuses[_beneficiary]; if (record.refererAddress != address(0) && record.refererBonus > 0) { shipTokens(record.refererAddress, refererTokens); // soldTokens = soldTokens.add(_amount); ShipTokens(record.refererAddress, refererTokens); } } soldTokens = soldTokens.add(totalTokens); return beneficiaryTokens; } function shipTokens(address _beneficiary, uint _amount) inState(State.Active) internal { if (isTransferShipment) { token.transfer(_beneficiary, _amount); } else { token.mint(_beneficiary, _amount); } } function forwardEther() internal returns (bool) { weiDeposit[msg.sender] = msg.value; return true; } function forwardTokens(address _beneficiary, address _tokenAddress, uint _amount) internal returns (bool) { TokenInterface allowedToken = allowedTokens[_tokenAddress]; allowedToken.transferFrom(_beneficiary, address(this), _amount); altDeposit[_tokenAddress][_beneficiary] = _amount; return true; } // ██╗ ██╗████████╗██╗██╗ ███████╗ // ██║ ██║╚══██╔══╝██║██║ ██╔════╝ // ██║ ██║ ██║ ██║██║ ███████╗ // ██║ ██║ ██║ ██║██║ ╚════██║ // ╚██████╔╝ ██║ ██║███████╗███████║ // ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ function toUint(bytes left) public pure returns (uint) { uint out; for (uint i = 0; i < 32; i++) { out |= uint(left[i]) << (31 * 8 - i * 8); } return out; } // ██████╗ ███████╗██████╗ ██╗ ██╗ ██████╗ // ██╔══██╗██╔════╝██╔══██╗██║ ██║██╔════╝ // ██║ ██║█████╗ ██████╔╝██║ ██║██║ ███╗ // ██║ ██║██╔══╝ ██╔══██╗██║ ██║██║ ██║ // ██████╔╝███████╗██████╔╝╚██████╔╝╚██████╔╝ // ╚═════╝ ╚══════╝╚═════╝ ╚═════╝ ╚═════╝ event Debug(address indexed sender, string message); function uintToString(uint v) public pure returns (string str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(48 + remainder); } bytes memory s = new bytes(i); for (uint j = 0; j < i; j++) { s[j] = reversed[i - 1 - j]; } str = string(s); } function addressToString(address x) public pure returns (string) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { byte b = byte(uint8(uint(x) / (2**(8*(19 - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(byte b) public pure returns (byte c) { if (b < 10) return byte(uint8(b) + 0x30); else return byte(uint8(b) + 0x57); } function appendUintToString(string inStr, uint v) public pure returns (string str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(48 + remainder); } bytes memory inStrb = bytes(inStr); bytes memory s = new bytes(inStrb.length + i); uint j; for (j = 0; j < inStrb.length; j++) { s[j] = inStrb[j]; } for (j = 0; j < i; j++) { s[j + inStrb.length] = reversed[i - 1 - j]; } str = string(s); } } contract BaseSqmCrowdsale is Crowdsale { function BaseSqmCrowdsale( address _registry, address _token, address _wallet, address _altToken, uint _price, uint _start, uint _end, uint _softCap, uint _hardCap ) public { setFlags( // Should be whitelisted to buy tokens // _isWhitelisted, false, // Should be known user to buy tokens // _isKnownOnly, true, // Enable amount bonuses in crowdsale? // _isAmountBonus, false, // Enable early bird bonus in crowdsale? // _isEarlyBonus, false, // Allow to buy tokens for another tokens? // _isTokenExcange, true, // Allow to issue tokens with tx hash (ex bitcoin) // _isAllowToIssue, false, // Should reject purchases with Ether? // _isDisableEther, true, // Should mint extra tokens for future distribution? // _isExtraDistribution, false, // Will ship token via minting? // _isTransferShipment, true, // Should be capped in ether // bool _isCappedInEther, false, // Should check personal bonuses? // _isPersonalBonuses false, // Should allow to claimFunds before finalizations? false ); setToken(_token); setTime(_start, _end); setRegistry(_registry); setWallet(_wallet); setSoftHardCaps( _softCap, // soft _hardCap // hard ); setPrice(_price); setTokenExcange(_altToken, 6 finney); } } contract SQM1Crowdsale is BaseSqmCrowdsale { function SQM1Crowdsale( address _registry, address _token, address _wallet, address _altToken ) BaseSqmCrowdsale( _registry, _token, _wallet, _altToken, // price 1 ETH -> 1 SQM 450 ether, // from now block.timestamp, // to 90 days in future block.timestamp + 90 days, // soft cap ERC20Basic(_token).totalSupply(), // hard cap ERC20Basic(_token).totalSupply() ) public { } } contract SQM2Crowdsale is BaseSqmCrowdsale { function SQM2Crowdsale( address _registry, address _token, address _wallet, address _altToken ) BaseSqmCrowdsale( _registry, _token, _wallet, _altToken, // price 1 ETH -> 1 SQM 1800 ether, // from now block.timestamp, // to 90 days in future block.timestamp + 90 days, // soft cap ERC20Basic(_token).totalSupply(), // hard cap ERC20Basic(_token).totalSupply() ) public { } } contract SQM3Crowdsale is BaseSqmCrowdsale { function SQM3Crowdsale( address _registry, address _token, address _wallet, address _altToken ) BaseSqmCrowdsale( _registry, _token, _wallet, _altToken, // price 1 ETH -> 1 SQM 5000 ether, // from now block.timestamp, // to 90 days in future block.timestamp + 90 days, // soft cap ERC20Basic(_token).totalSupply(), // hard cap ERC20Basic(_token).totalSupply() ) public { } }
SetRegistry(msg.sender, userRegistry, _registry);
function setRegistry(address _registry) inState(State.Setup) onlyOwner public { require(_registry != address(0)); userRegistry = UserRegistryInterface(_registry); }
979,516
[ 1, 694, 4243, 12, 3576, 18, 15330, 16, 729, 4243, 16, 389, 9893, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 4243, 12, 2867, 389, 9893, 13, 7010, 565, 316, 1119, 12, 1119, 18, 7365, 13, 1338, 5541, 1071, 7010, 225, 288, 203, 565, 2583, 24899, 9893, 480, 1758, 12, 20, 10019, 203, 565, 729, 4243, 273, 2177, 4243, 1358, 24899, 9893, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier:MIT // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (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 = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: contracts/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: contracts/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: contracts/IERC165.sol pragma solidity ^0.8.0; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } // File: contracts/ERC165.sol pragma solidity ^0.8.0; contract ERC165 is IERC165 { mapping(bytes4 => bool) private _supportedInterfaces; constructor() { _registerInterface(bytes4(keccak256('supportsInterface(bytes4)'))); } function supportsInterface(bytes4 interfaceID) external view override virtual returns (bool) { return _supportedInterfaces[interfaceID]; } function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, 'Invalid interface request'); _supportedInterfaces[interfaceId] = true; } } // File: contracts/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: contracts/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: contracts/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/ReentrancyGuard.sol pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and 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: contracts/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: contracts/ERC721A.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * uint128 is a number with a maximum value of 2^127-1 or 340,282,366,920,938,463,463,374,607,431,768,211,455. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165,ERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId ; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require( owner != address(0), "ERC721A: balance query for the zero address" ); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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(),'.json')) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require( _exists(tokenId), "ERC721A: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721A: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/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/CryptoBeauties.sol //\_________ __ __________ __ .__ //\_ ___ \ _______ ___.__.______ _/ |_ ____ \______ \ ____ _____ __ __ _/ |_ |__| ____ ______ /// \ \/ \_ __ \< | |\____ \ \ __\ / _ \ | | _/_/ __ \ \__ \ | | \\ __\| |_/ __ \ / ___/ //\ \____ | | \/ \___ || |_> > | | ( <_> ) | | \\ ___/ / __ \_| | / | | | |\ ___/ \___ \ // \______ / |__| / ____|| __/ |__| \____/ |______ / \___ >(____ /|____/ |__| |__| \___ >/____ > // \/ \/ |__| \/ \/ \/ \/ \/ pragma solidity ^0.8.0; contract CryptoBeauties is Ownable, ERC721A, ReentrancyGuard { uint256 public amountForDevsRemaining; uint256 public freeRemaining; uint256 public constant mintPrice = 0.029 ether; bytes32 private _freeMintRoot = "INSERT ROOT HERE"; bytes32 private _whitelistRoot = "INSERT ROOT HERE"; address public Promoter = 0x414508c939B0B78347a22d1F2dE5A7747C1426A5; address public Developer = 0x64d556cAae3eD6Df460F9CA7A93470722D04bE05; address public DAO = 0x402881BAd73d3932C2472Ab0453E0b03B32C52F0; address public Project = 0x421b0B0603fD45719B480CF71670EC00aE64b309; mapping(address => bool) public freeMintUsed; mapping(address => uint256) public whitelistMintsUsed; constructor( uint256 maxBatchSize_, uint256 collectionSize_, uint256 amountForFreeList_, uint256 amountForDevs_ ) ERC721A("CryptoBeauties", "CRYPTOBEAUTIES", maxBatchSize_, collectionSize_) { freeRemaining = amountForFreeList_; amountForDevsRemaining = amountForDevs_; require( amountForFreeList_ <= collectionSize_, "Collection is not large enough." ); } modifier callerIsUser() { require(tx.origin == msg.sender, "Caller is another contract."); _; } //Status of Sale that is going on. enum SaleState { Paused, // 0 Presale, // 1 Public // 2 } SaleState public saleState; //Merkle Implementation for ease of access function _verifyFreeMintStatus(address _account, bytes32[] calldata _merkleProof) private view returns (bool){ bytes32 node = keccak256(abi.encodePacked(_account)); return MerkleProof.verify(_merkleProof, _freeMintRoot, node); } function _verifyWhitelistStatus(address _account, bytes32[] calldata _merkleProof) private view returns (bool) { bytes32 node = keccak256(abi.encodePacked(_account)); return MerkleProof.verify(_merkleProof, _whitelistRoot, node); } // Start of whitelist and free mint implementation function FreeWhitelistMint (uint256 _beautyAmount, bytes32[] calldata _merkleProof) external payable callerIsUser { require(_beautyAmount > 0); require(saleState == SaleState.Presale, "Presale has not begun yet!"); require(whitelistMintsUsed[msg.sender] + _beautyAmount < 6, "Amount exceeds your allocation."); require(totalSupply() + _beautyAmount + amountForDevsRemaining <= collectionSize, "Exceeds max supply."); require(_verifyFreeMintStatus(msg.sender, _merkleProof), "Address not on Whitelist."); if (freeMintUsed[msg.sender] == false && freeRemaining != 0) { require(msg.value == mintPrice * (_beautyAmount - 1), "Incorrect ETH amount."); freeMintUsed[msg.sender] = true; freeRemaining -= 1; } else { require(msg.value == mintPrice * _beautyAmount, "Incorrect ETH amount."); } whitelistMintsUsed[msg.sender] += _beautyAmount; _safeMint(msg.sender, _beautyAmount); } function WhiteListMint(uint256 _beautyAmount, bytes32[] calldata _merkleProof) external payable callerIsUser { require(_beautyAmount > 0); require(saleState == SaleState.Presale, "Presale has not begun yet!"); require(whitelistMintsUsed[msg.sender] + _beautyAmount < 6, "Amount exceeds your allocation."); require(totalSupply() + _beautyAmount + amountForDevsRemaining <= collectionSize, "Exceeds max supply."); require(_verifyWhitelistStatus(msg.sender, _merkleProof), "Address not on Whitelist."); require(msg.value == mintPrice * _beautyAmount, "Incorrect ETH amount."); whitelistMintsUsed[msg.sender] += _beautyAmount; _safeMint(msg.sender, _beautyAmount); } //Owner Mint function function AllowOwnerMint(uint256 _beautyAmount) external onlyOwner { require(_beautyAmount > 0); require(_beautyAmount <= amountForDevsRemaining, "Not Enough Dev Tokens left"); amountForDevsRemaining -= _beautyAmount; require(totalSupply() + _beautyAmount <= collectionSize, "Reached Max Supply."); _safeMint(msg.sender, _beautyAmount); } function publicSaleMint(uint256 _beautyAmount) external payable callerIsUser { require(_beautyAmount > 0); require(saleState == SaleState.Public, "Presale is still active!"); require(msg.value == mintPrice * _beautyAmount, "Please send more ETH!"); require(totalSupply() + _beautyAmount + amountForDevsRemaining <= collectionSize, "Reached Max Supply."); _safeMint(msg.sender, _beautyAmount); } function setRootFreeList(bytes32 _freeRoot) external onlyOwner { _freeMintRoot = _freeRoot; } function setRootWL(bytes32 _rootWL) external onlyOwner { _whitelistRoot = _rootWL; } function setSaleState(SaleState _newState) external onlyOwner { saleState = _newState; } //Metadata URI string private _baseTokenURI = "https://ipfs.cryptobeauties.io/metadata/"; function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setupBaseURI(string calldata _baseURIz) external onlyOwner { _baseTokenURI = _baseURIz; } // Withdrawal functions function setWithdrawAddress(address _DAO, address _Promoter, address _Developer, address _Project ) external onlyOwner { DAO = _DAO; Promoter = _Promoter; Developer = _Developer; Project = _Project; } function withdrawMoney() external onlyOwner nonReentrant { uint256 balance = address(this).balance; uint256 toPartner = 405*balance/1000; uint256 toDAO = 14*balance/100; uint256 toProject = 4*balance/100; (bool sent1,) = payable(Promoter).call{value: toPartner}(""); (bool sent2,) = payable(Developer).call{value: toPartner}(""); (bool sent3,) = payable(DAO).call{value: toDAO}(""); (bool sent4,) = payable(Project).call{value: toProject}(""); require(sent1 && sent2 && sent3 && sent4, "Failed to send Ether"); } function withdrawFinal() external onlyOwner nonReentrant { uint256 balance = address(this).balance; uint256 toPartner = 405*balance/1000; uint256 toDAO = 14*balance/100; uint256 toOwner = balance - 2*toPartner - toDAO; (bool pt, ) = payable(Promoter).call{value: toPartner}(""); (bool dv, ) = payable(Developer).call{value: toPartner}(""); (bool da, ) = payable(DAO).call{value: toDAO}(""); (bool os, ) = payable(msg.sender).call{value: toOwner}(""); require(pt && dv && da && os, "Failed to send Ether"); } function setOwnersExplicit(uint256 quantity) external onlyOwner { _setOwnersExplicit(quantity); } function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } }
* @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(),'.json')) : ""; }
1,531,611
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 2277, 17, 2316, 3098, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 389, 1808, 12, 2316, 548, 3631, 203, 5411, 315, 654, 39, 27, 5340, 2277, 30, 3699, 843, 364, 1661, 19041, 1147, 6, 203, 3639, 11272, 203, 203, 3639, 533, 3778, 1026, 3098, 273, 389, 1969, 3098, 5621, 203, 3639, 327, 203, 5411, 1731, 12, 1969, 3098, 2934, 2469, 405, 374, 203, 7734, 692, 533, 12, 21457, 18, 3015, 4420, 329, 12, 1969, 3098, 16, 1147, 548, 18, 10492, 9334, 10332, 1977, 26112, 203, 7734, 294, 1408, 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 ]
// full contract sources : https://github.com/DigixGlobal/dao-contracts pragma solidity ^0.4.25; contract ContractResolver { bool public locked_forever; function get_contract(bytes32) public view returns (address); function init_register_contract(bytes32, address) public returns (bool); } contract ResolverClient { /// The address of the resolver contract for this project address public resolver; bytes32 public key; /// Make our own address available to us as a constant address public CONTRACT_ADDRESS; /// Function modifier to check if msg.sender corresponds to the resolved address of a given key /// @param _contract The resolver key modifier if_sender_is(bytes32 _contract) { require(sender_is(_contract)); _; } function sender_is(bytes32 _contract) internal view returns (bool _isFrom) { _isFrom = msg.sender == ContractResolver(resolver).get_contract(_contract); } modifier if_sender_is_from(bytes32[3] _contracts) { require(sender_is_from(_contracts)); _; } function sender_is_from(bytes32[3] _contracts) internal view returns (bool _isFrom) { uint256 _n = _contracts.length; for (uint256 i = 0; i < _n; i++) { if (_contracts[i] == bytes32(0x0)) continue; if (msg.sender == ContractResolver(resolver).get_contract(_contracts[i])) { _isFrom = true; break; } } } /// Function modifier to check resolver's locking status. modifier unless_resolver_is_locked() { require(is_locked() == false); _; } /// @dev Initialize new contract /// @param _key the resolver key for this contract /// @return _success if the initialization is successful function init(bytes32 _key, address _resolver) internal returns (bool _success) { bool _is_locked = ContractResolver(_resolver).locked_forever(); if (_is_locked == false) { CONTRACT_ADDRESS = address(this); resolver = _resolver; key = _key; require(ContractResolver(resolver).init_register_contract(key, CONTRACT_ADDRESS)); _success = true; } else { _success = false; } } /// @dev Check if resolver is locked /// @return _locked if the resolver is currently locked function is_locked() private view returns (bool _locked) { _locked = ContractResolver(resolver).locked_forever(); } /// @dev Get the address of a contract /// @param _key the resolver key to look up /// @return _contract the address of the contract function get_contract(bytes32 _key) public view returns (address _contract) { _contract = ContractResolver(resolver).get_contract(_key); } } 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 DaoConstants { using SafeMath for uint256; bytes32 EMPTY_BYTES = bytes32(0x0); address EMPTY_ADDRESS = address(0x0); bytes32 PROPOSAL_STATE_PREPROPOSAL = "proposal_state_preproposal"; bytes32 PROPOSAL_STATE_DRAFT = "proposal_state_draft"; bytes32 PROPOSAL_STATE_MODERATED = "proposal_state_moderated"; bytes32 PROPOSAL_STATE_ONGOING = "proposal_state_ongoing"; bytes32 PROPOSAL_STATE_CLOSED = "proposal_state_closed"; bytes32 PROPOSAL_STATE_ARCHIVED = "proposal_state_archived"; uint256 PRL_ACTION_STOP = 1; uint256 PRL_ACTION_PAUSE = 2; uint256 PRL_ACTION_UNPAUSE = 3; uint256 COLLATERAL_STATUS_UNLOCKED = 1; uint256 COLLATERAL_STATUS_LOCKED = 2; uint256 COLLATERAL_STATUS_CLAIMED = 3; bytes32 INTERMEDIATE_DGD_IDENTIFIER = "inter_dgd_id"; bytes32 INTERMEDIATE_MODERATOR_DGD_IDENTIFIER = "inter_mod_dgd_id"; bytes32 INTERMEDIATE_BONUS_CALCULATION_IDENTIFIER = "inter_bonus_calculation_id"; // interactive contracts bytes32 CONTRACT_DAO = "dao"; bytes32 CONTRACT_DAO_SPECIAL_PROPOSAL = "dao:special:proposal"; bytes32 CONTRACT_DAO_STAKE_LOCKING = "dao:stake-locking"; bytes32 CONTRACT_DAO_VOTING = "dao:voting"; bytes32 CONTRACT_DAO_VOTING_CLAIMS = "dao:voting:claims"; bytes32 CONTRACT_DAO_SPECIAL_VOTING_CLAIMS = "dao:svoting:claims"; bytes32 CONTRACT_DAO_IDENTITY = "dao:identity"; bytes32 CONTRACT_DAO_REWARDS_MANAGER = "dao:rewards-manager"; bytes32 CONTRACT_DAO_REWARDS_MANAGER_EXTRAS = "dao:rewards-extras"; bytes32 CONTRACT_DAO_ROLES = "dao:roles"; bytes32 CONTRACT_DAO_FUNDING_MANAGER = "dao:funding-manager"; bytes32 CONTRACT_DAO_WHITELISTING = "dao:whitelisting"; bytes32 CONTRACT_DAO_INFORMATION = "dao:information"; // service contracts bytes32 CONTRACT_SERVICE_ROLE = "service:role"; bytes32 CONTRACT_SERVICE_DAO_INFO = "service:dao:info"; bytes32 CONTRACT_SERVICE_DAO_LISTING = "service:dao:listing"; bytes32 CONTRACT_SERVICE_DAO_CALCULATOR = "service:dao:calculator"; // storage contracts bytes32 CONTRACT_STORAGE_DAO = "storage:dao"; bytes32 CONTRACT_STORAGE_DAO_COUNTER = "storage:dao:counter"; bytes32 CONTRACT_STORAGE_DAO_UPGRADE = "storage:dao:upgrade"; bytes32 CONTRACT_STORAGE_DAO_IDENTITY = "storage:dao:identity"; bytes32 CONTRACT_STORAGE_DAO_POINTS = "storage:dao:points"; bytes32 CONTRACT_STORAGE_DAO_SPECIAL = "storage:dao:special"; bytes32 CONTRACT_STORAGE_DAO_CONFIG = "storage:dao:config"; bytes32 CONTRACT_STORAGE_DAO_STAKE = "storage:dao:stake"; bytes32 CONTRACT_STORAGE_DAO_REWARDS = "storage:dao:rewards"; bytes32 CONTRACT_STORAGE_DAO_WHITELISTING = "storage:dao:whitelisting"; bytes32 CONTRACT_STORAGE_INTERMEDIATE_RESULTS = "storage:intermediate:results"; bytes32 CONTRACT_DGD_TOKEN = "t:dgd"; bytes32 CONTRACT_DGX_TOKEN = "t:dgx"; bytes32 CONTRACT_BADGE_TOKEN = "t:badge"; uint8 ROLES_ROOT = 1; uint8 ROLES_FOUNDERS = 2; uint8 ROLES_PRLS = 3; uint8 ROLES_KYC_ADMINS = 4; uint256 QUARTER_DURATION = 90 days; bytes32 CONFIG_MINIMUM_LOCKED_DGD = "min_dgd_participant"; bytes32 CONFIG_MINIMUM_DGD_FOR_MODERATOR = "min_dgd_moderator"; bytes32 CONFIG_MINIMUM_REPUTATION_FOR_MODERATOR = "min_reputation_moderator"; bytes32 CONFIG_LOCKING_PHASE_DURATION = "locking_phase_duration"; bytes32 CONFIG_QUARTER_DURATION = "quarter_duration"; bytes32 CONFIG_VOTING_COMMIT_PHASE = "voting_commit_phase"; bytes32 CONFIG_VOTING_PHASE_TOTAL = "voting_phase_total"; bytes32 CONFIG_INTERIM_COMMIT_PHASE = "interim_voting_commit_phase"; bytes32 CONFIG_INTERIM_PHASE_TOTAL = "interim_voting_phase_total"; bytes32 CONFIG_DRAFT_QUORUM_FIXED_PORTION_NUMERATOR = "draft_quorum_fixed_numerator"; bytes32 CONFIG_DRAFT_QUORUM_FIXED_PORTION_DENOMINATOR = "draft_quorum_fixed_denominator"; bytes32 CONFIG_DRAFT_QUORUM_SCALING_FACTOR_NUMERATOR = "draft_quorum_sfactor_numerator"; bytes32 CONFIG_DRAFT_QUORUM_SCALING_FACTOR_DENOMINATOR = "draft_quorum_sfactor_denominator"; bytes32 CONFIG_VOTING_QUORUM_FIXED_PORTION_NUMERATOR = "vote_quorum_fixed_numerator"; bytes32 CONFIG_VOTING_QUORUM_FIXED_PORTION_DENOMINATOR = "vote_quorum_fixed_denominator"; bytes32 CONFIG_VOTING_QUORUM_SCALING_FACTOR_NUMERATOR = "vote_quorum_sfactor_numerator"; bytes32 CONFIG_VOTING_QUORUM_SCALING_FACTOR_DENOMINATOR = "vote_quorum_sfactor_denominator"; bytes32 CONFIG_FINAL_REWARD_SCALING_FACTOR_NUMERATOR = "final_reward_sfactor_numerator"; bytes32 CONFIG_FINAL_REWARD_SCALING_FACTOR_DENOMINATOR = "final_reward_sfactor_denominator"; bytes32 CONFIG_DRAFT_QUOTA_NUMERATOR = "draft_quota_numerator"; bytes32 CONFIG_DRAFT_QUOTA_DENOMINATOR = "draft_quota_denominator"; bytes32 CONFIG_VOTING_QUOTA_NUMERATOR = "voting_quota_numerator"; bytes32 CONFIG_VOTING_QUOTA_DENOMINATOR = "voting_quota_denominator"; bytes32 CONFIG_MINIMAL_QUARTER_POINT = "minimal_qp"; bytes32 CONFIG_QUARTER_POINT_SCALING_FACTOR = "quarter_point_scaling_factor"; bytes32 CONFIG_REPUTATION_POINT_SCALING_FACTOR = "rep_point_scaling_factor"; bytes32 CONFIG_MODERATOR_MINIMAL_QUARTER_POINT = "minimal_mod_qp"; bytes32 CONFIG_MODERATOR_QUARTER_POINT_SCALING_FACTOR = "mod_qp_scaling_factor"; bytes32 CONFIG_MODERATOR_REPUTATION_POINT_SCALING_FACTOR = "mod_rep_point_scaling_factor"; bytes32 CONFIG_QUARTER_POINT_DRAFT_VOTE = "quarter_point_draft_vote"; bytes32 CONFIG_QUARTER_POINT_VOTE = "quarter_point_vote"; bytes32 CONFIG_QUARTER_POINT_INTERIM_VOTE = "quarter_point_interim_vote"; /// this is per 10000 ETHs bytes32 CONFIG_QUARTER_POINT_MILESTONE_COMPLETION_PER_10000ETH = "q_p_milestone_completion"; bytes32 CONFIG_BONUS_REPUTATION_NUMERATOR = "bonus_reputation_numerator"; bytes32 CONFIG_BONUS_REPUTATION_DENOMINATOR = "bonus_reputation_denominator"; bytes32 CONFIG_SPECIAL_PROPOSAL_COMMIT_PHASE = "special_proposal_commit_phase"; bytes32 CONFIG_SPECIAL_PROPOSAL_PHASE_TOTAL = "special_proposal_phase_total"; bytes32 CONFIG_SPECIAL_QUOTA_NUMERATOR = "config_special_quota_numerator"; bytes32 CONFIG_SPECIAL_QUOTA_DENOMINATOR = "config_special_quota_denominator"; bytes32 CONFIG_SPECIAL_PROPOSAL_QUORUM_NUMERATOR = "special_quorum_numerator"; bytes32 CONFIG_SPECIAL_PROPOSAL_QUORUM_DENOMINATOR = "special_quorum_denominator"; bytes32 CONFIG_MAXIMUM_REPUTATION_DEDUCTION = "config_max_reputation_deduction"; bytes32 CONFIG_PUNISHMENT_FOR_NOT_LOCKING = "config_punishment_not_locking"; bytes32 CONFIG_REPUTATION_PER_EXTRA_QP_NUM = "config_rep_per_extra_qp_num"; bytes32 CONFIG_REPUTATION_PER_EXTRA_QP_DEN = "config_rep_per_extra_qp_den"; bytes32 CONFIG_MAXIMUM_MODERATOR_REPUTATION_DEDUCTION = "config_max_m_rp_deduction"; bytes32 CONFIG_REPUTATION_PER_EXTRA_MODERATOR_QP_NUM = "config_rep_per_extra_m_qp_num"; bytes32 CONFIG_REPUTATION_PER_EXTRA_MODERATOR_QP_DEN = "config_rep_per_extra_m_qp_den"; bytes32 CONFIG_PORTION_TO_MODERATORS_NUM = "config_mod_portion_num"; bytes32 CONFIG_PORTION_TO_MODERATORS_DEN = "config_mod_portion_den"; bytes32 CONFIG_DRAFT_VOTING_PHASE = "config_draft_voting_phase"; bytes32 CONFIG_REPUTATION_POINT_BOOST_FOR_BADGE = "config_rp_boost_per_badge"; bytes32 CONFIG_VOTE_CLAIMING_DEADLINE = "config_claiming_deadline"; bytes32 CONFIG_PREPROPOSAL_COLLATERAL = "config_preproposal_collateral"; bytes32 CONFIG_MAX_FUNDING_FOR_NON_DIGIX = "config_max_funding_nonDigix"; bytes32 CONFIG_MAX_MILESTONES_FOR_NON_DIGIX = "config_max_milestones_nonDigix"; bytes32 CONFIG_NON_DIGIX_PROPOSAL_CAP_PER_QUARTER = "config_nonDigix_proposal_cap"; bytes32 CONFIG_PROPOSAL_DEAD_DURATION = "config_dead_duration"; bytes32 CONFIG_CARBON_VOTE_REPUTATION_BONUS = "config_cv_reputation"; } contract DaoWhitelistingStorage is ResolverClient, DaoConstants { mapping (address => bool) public whitelist; } contract DaoWhitelistingCommon is ResolverClient, DaoConstants { function daoWhitelistingStorage() internal view returns (DaoWhitelistingStorage _contract) { _contract = DaoWhitelistingStorage(get_contract(CONTRACT_STORAGE_DAO_WHITELISTING)); } /** @notice Check if a certain address is whitelisted to read sensitive information in the storage layer @dev if the address is an account, it is allowed to read. If the address is a contract, it has to be in the whitelist */ function senderIsAllowedToRead() internal view returns (bool _senderIsAllowedToRead) { // msg.sender is allowed to read only if its an EOA or a whitelisted contract _senderIsAllowedToRead = (msg.sender == tx.origin) || daoWhitelistingStorage().whitelist(msg.sender); } } contract DaoIdentityStorage { function read_user_role_id(address) constant public returns (uint256); function is_kyc_approved(address) public view returns (bool); } contract IdentityCommon is DaoWhitelistingCommon { modifier if_root() { require(identity_storage().read_user_role_id(msg.sender) == ROLES_ROOT); _; } modifier if_founder() { require(is_founder()); _; } function is_founder() internal view returns (bool _isFounder) { _isFounder = identity_storage().read_user_role_id(msg.sender) == ROLES_FOUNDERS; } modifier if_prl() { require(identity_storage().read_user_role_id(msg.sender) == ROLES_PRLS); _; } modifier if_kyc_admin() { require(identity_storage().read_user_role_id(msg.sender) == ROLES_KYC_ADMINS); _; } function identity_storage() internal view returns (DaoIdentityStorage _contract) { _contract = DaoIdentityStorage(get_contract(CONTRACT_STORAGE_DAO_IDENTITY)); } } library MathHelper { using SafeMath for uint256; function max(uint256 a, uint256 b) internal pure returns (uint256 _max){ _max = b; if (a > b) { _max = a; } } function min(uint256 a, uint256 b) internal pure returns (uint256 _min){ _min = b; if (a < b) { _min = a; } } function sumNumbers(uint256[] _numbers) internal pure returns (uint256 _sum) { for (uint256 i=0;i<_numbers.length;i++) { _sum = _sum.add(_numbers[i]); } } } contract DaoListingService { function listParticipants(uint256, bool) public view returns (address[]); function listParticipantsFrom( address, uint256, bool ) public view returns (address[]); } contract DaoConfigsStorage { mapping (bytes32 => uint256) public uintConfigs; mapping (bytes32 => address) public addressConfigs; mapping (bytes32 => bytes32) public bytesConfigs; function updateUintConfigs(uint256[]) external; function readUintConfigs() public view returns (uint256[]); } contract DaoStakeStorage { mapping (address => uint256) public lockedDGDStake; function readLastModerator() public view returns (address); function readLastParticipant() public view returns (address); } contract DaoProposalCounterStorage { mapping (uint256 => uint256) public proposalCountByQuarter; } contract DaoStorage { function readProposal(bytes32) public view returns (bytes32, address, address, bytes32, uint256, uint256, bytes32, bytes32, bool, bool); function readProposalProposer(bytes32) public view returns (address); function readProposalDraftVotingResult(bytes32) public view returns (bool); function readProposalVotingResult(bytes32, uint256) public view returns (bool); function readProposalDraftVotingTime(bytes32) public view returns (uint256); function readProposalVotingTime(bytes32, uint256) public view returns (uint256); function readVote(bytes32, uint256, address) public view returns (bool, uint256); function isDraftClaimed(bytes32) public view returns (bool); function isClaimed(bytes32, uint256) public view returns (bool); } contract DaoUpgradeStorage { uint256 public startOfFirstQuarter; bool public isReplacedByNewDao; } contract DaoSpecialStorage { function readProposalProposer(bytes32) public view returns (address); function readConfigs(bytes32) public view returns (uint256[] memory, address[] memory, bytes32[] memory); function readVotingCount(bytes32, address[]) external view returns (uint256, uint256); function readVotingTime(bytes32) public view returns (uint256); function setPass(bytes32, bool) public; function setVotingClaim(bytes32, bool) public; function isClaimed(bytes32) public view returns (bool); function readVote(bytes32, address) public view returns (bool, uint256); } contract DaoPointsStorage { function getReputation(address) public view returns (uint256); } contract DaoRewardsStorage { mapping (address => uint256) public lastParticipatedQuarter; function readDgxDistributionDay(uint256) public view returns (uint256); } contract IntermediateResultsStorage { function getIntermediateResults(bytes32) public view returns (address, uint256, uint256, uint256); function setIntermediateResults(bytes32, address, uint256, uint256, uint256) public; } contract DaoCommonMini is IdentityCommon { using MathHelper for MathHelper; /** @notice Check if the DAO contracts have been replaced by a new set of contracts @return _isNotReplaced true if it is not replaced, false if it has already been replaced */ function isDaoNotReplaced() public view returns (bool _isNotReplaced) { _isNotReplaced = !daoUpgradeStorage().isReplacedByNewDao(); } /** @notice Check if it is currently in the locking phase @dev No governance activities can happen in the locking phase. The locking phase is from t=0 to t=CONFIG_LOCKING_PHASE_DURATION-1 @return _isLockingPhase true if it is in the locking phase */ function isLockingPhase() public view returns (bool _isLockingPhase) { _isLockingPhase = currentTimeInQuarter() < getUintConfig(CONFIG_LOCKING_PHASE_DURATION); } /** @notice Check if it is currently in a main phase. @dev The main phase is where all the governance activities could take plase. If the DAO is replaced, there can never be any more main phase. @return _isMainPhase true if it is in a main phase */ function isMainPhase() public view returns (bool _isMainPhase) { _isMainPhase = isDaoNotReplaced() && currentTimeInQuarter() >= getUintConfig(CONFIG_LOCKING_PHASE_DURATION); } /** @notice Check if the calculateGlobalRewardsBeforeNewQuarter function has been done for a certain quarter @dev However, there is no need to run calculateGlobalRewardsBeforeNewQuarter for the first quarter */ modifier ifGlobalRewardsSet(uint256 _quarterNumber) { if (_quarterNumber > 1) { require(daoRewardsStorage().readDgxDistributionDay(_quarterNumber) > 0); } _; } /** @notice require that it is currently during a phase, which is within _relativePhaseStart and _relativePhaseEnd seconds, after the _startingPoint */ function requireInPhase(uint256 _startingPoint, uint256 _relativePhaseStart, uint256 _relativePhaseEnd) internal view { require(_startingPoint > 0); require(now < _startingPoint.add(_relativePhaseEnd)); require(now >= _startingPoint.add(_relativePhaseStart)); } /** @notice Get the current quarter index @dev Quarter indexes starts from 1 @return _quarterNumber the current quarter index */ function currentQuarterNumber() public view returns(uint256 _quarterNumber) { _quarterNumber = getQuarterNumber(now); } /** @notice Get the quarter index of a timestamp @dev Quarter indexes starts from 1 @return _index the quarter index */ function getQuarterNumber(uint256 _time) internal view returns (uint256 _index) { require(startOfFirstQuarterIsSet()); _index = _time.sub(daoUpgradeStorage().startOfFirstQuarter()) .div(getUintConfig(CONFIG_QUARTER_DURATION)) .add(1); } /** @notice Get the relative time in quarter of a timestamp @dev For example, the timeInQuarter of the first second of any quarter n-th is always 1 */ function timeInQuarter(uint256 _time) internal view returns (uint256 _timeInQuarter) { require(startOfFirstQuarterIsSet()); // must be already set _timeInQuarter = _time.sub(daoUpgradeStorage().startOfFirstQuarter()) % getUintConfig(CONFIG_QUARTER_DURATION); } /** @notice Check if the start of first quarter is already set @return _isSet true if start of first quarter is already set */ function startOfFirstQuarterIsSet() internal view returns (bool _isSet) { _isSet = daoUpgradeStorage().startOfFirstQuarter() != 0; } /** @notice Get the current relative time in the quarter @dev For example: the currentTimeInQuarter of the first second of any quarter is 1 @return _currentT the current relative time in the quarter */ function currentTimeInQuarter() public view returns (uint256 _currentT) { _currentT = timeInQuarter(now); } /** @notice Get the time remaining in the quarter */ function getTimeLeftInQuarter(uint256 _time) internal view returns (uint256 _timeLeftInQuarter) { _timeLeftInQuarter = getUintConfig(CONFIG_QUARTER_DURATION).sub(timeInQuarter(_time)); } function daoListingService() internal view returns (DaoListingService _contract) { _contract = DaoListingService(get_contract(CONTRACT_SERVICE_DAO_LISTING)); } function daoConfigsStorage() internal view returns (DaoConfigsStorage _contract) { _contract = DaoConfigsStorage(get_contract(CONTRACT_STORAGE_DAO_CONFIG)); } function daoStakeStorage() internal view returns (DaoStakeStorage _contract) { _contract = DaoStakeStorage(get_contract(CONTRACT_STORAGE_DAO_STAKE)); } function daoStorage() internal view returns (DaoStorage _contract) { _contract = DaoStorage(get_contract(CONTRACT_STORAGE_DAO)); } function daoProposalCounterStorage() internal view returns (DaoProposalCounterStorage _contract) { _contract = DaoProposalCounterStorage(get_contract(CONTRACT_STORAGE_DAO_COUNTER)); } function daoUpgradeStorage() internal view returns (DaoUpgradeStorage _contract) { _contract = DaoUpgradeStorage(get_contract(CONTRACT_STORAGE_DAO_UPGRADE)); } function daoSpecialStorage() internal view returns (DaoSpecialStorage _contract) { _contract = DaoSpecialStorage(get_contract(CONTRACT_STORAGE_DAO_SPECIAL)); } function daoPointsStorage() internal view returns (DaoPointsStorage _contract) { _contract = DaoPointsStorage(get_contract(CONTRACT_STORAGE_DAO_POINTS)); } function daoRewardsStorage() internal view returns (DaoRewardsStorage _contract) { _contract = DaoRewardsStorage(get_contract(CONTRACT_STORAGE_DAO_REWARDS)); } function intermediateResultsStorage() internal view returns (IntermediateResultsStorage _contract) { _contract = IntermediateResultsStorage(get_contract(CONTRACT_STORAGE_INTERMEDIATE_RESULTS)); } function getUintConfig(bytes32 _configKey) public view returns (uint256 _configValue) { _configValue = daoConfigsStorage().uintConfigs(_configKey); } } contract DaoCommon is DaoCommonMini { using MathHelper for MathHelper; /** @notice Check if the transaction is called by the proposer of a proposal @return _isFromProposer true if the caller is the proposer */ function isFromProposer(bytes32 _proposalId) internal view returns (bool _isFromProposer) { _isFromProposer = msg.sender == daoStorage().readProposalProposer(_proposalId); } /** @notice Check if the proposal can still be "editted", or in other words, added more versions @dev Once the proposal is finalized, it can no longer be editted. The proposer will still be able to add docs and change fundings though. @return _isEditable true if the proposal is editable */ function isEditable(bytes32 _proposalId) internal view returns (bool _isEditable) { bytes32 _finalVersion; (,,,,,,,_finalVersion,,) = daoStorage().readProposal(_proposalId); _isEditable = _finalVersion == EMPTY_BYTES; } /** @notice returns the balance of DaoFundingManager, which is the wei in DigixDAO */ function weiInDao() internal view returns (uint256 _wei) { _wei = get_contract(CONTRACT_DAO_FUNDING_MANAGER).balance; } /** @notice Check if it is after the draft voting phase of the proposal */ modifier ifAfterDraftVotingPhase(bytes32 _proposalId) { uint256 _start = daoStorage().readProposalDraftVotingTime(_proposalId); require(_start > 0); // Draft voting must have started. In other words, proposer must have finalized the proposal require(now >= _start.add(getUintConfig(CONFIG_DRAFT_VOTING_PHASE))); _; } modifier ifCommitPhase(bytes32 _proposalId, uint8 _index) { requireInPhase( daoStorage().readProposalVotingTime(_proposalId, _index), 0, getUintConfig(_index == 0 ? CONFIG_VOTING_COMMIT_PHASE : CONFIG_INTERIM_COMMIT_PHASE) ); _; } modifier ifRevealPhase(bytes32 _proposalId, uint256 _index) { requireInPhase( daoStorage().readProposalVotingTime(_proposalId, _index), getUintConfig(_index == 0 ? CONFIG_VOTING_COMMIT_PHASE : CONFIG_INTERIM_COMMIT_PHASE), getUintConfig(_index == 0 ? CONFIG_VOTING_PHASE_TOTAL : CONFIG_INTERIM_PHASE_TOTAL) ); _; } modifier ifAfterProposalRevealPhase(bytes32 _proposalId, uint256 _index) { uint256 _start = daoStorage().readProposalVotingTime(_proposalId, _index); require(_start > 0); require(now >= _start.add(getUintConfig(_index == 0 ? CONFIG_VOTING_PHASE_TOTAL : CONFIG_INTERIM_PHASE_TOTAL))); _; } modifier ifDraftVotingPhase(bytes32 _proposalId) { requireInPhase( daoStorage().readProposalDraftVotingTime(_proposalId), 0, getUintConfig(CONFIG_DRAFT_VOTING_PHASE) ); _; } modifier isProposalState(bytes32 _proposalId, bytes32 _STATE) { bytes32 _currentState; (,,,_currentState,,,,,,) = daoStorage().readProposal(_proposalId); require(_currentState == _STATE); _; } /** @notice Check if the DAO has enough ETHs for a particular funding request */ modifier ifFundingPossible(uint256[] _fundings, uint256 _finalReward) { require(MathHelper.sumNumbers(_fundings).add(_finalReward) <= weiInDao()); _; } modifier ifDraftNotClaimed(bytes32 _proposalId) { require(daoStorage().isDraftClaimed(_proposalId) == false); _; } modifier ifNotClaimed(bytes32 _proposalId, uint256 _index) { require(daoStorage().isClaimed(_proposalId, _index) == false); _; } modifier ifNotClaimedSpecial(bytes32 _proposalId) { require(daoSpecialStorage().isClaimed(_proposalId) == false); _; } modifier hasNotRevealed(bytes32 _proposalId, uint256 _index) { uint256 _voteWeight; (, _voteWeight) = daoStorage().readVote(_proposalId, _index, msg.sender); require(_voteWeight == uint(0)); _; } modifier hasNotRevealedSpecial(bytes32 _proposalId) { uint256 _weight; (,_weight) = daoSpecialStorage().readVote(_proposalId, msg.sender); require(_weight == uint256(0)); _; } modifier ifAfterRevealPhaseSpecial(bytes32 _proposalId) { uint256 _start = daoSpecialStorage().readVotingTime(_proposalId); require(_start > 0); require(now.sub(_start) >= getUintConfig(CONFIG_SPECIAL_PROPOSAL_PHASE_TOTAL)); _; } modifier ifCommitPhaseSpecial(bytes32 _proposalId) { requireInPhase( daoSpecialStorage().readVotingTime(_proposalId), 0, getUintConfig(CONFIG_SPECIAL_PROPOSAL_COMMIT_PHASE) ); _; } modifier ifRevealPhaseSpecial(bytes32 _proposalId) { requireInPhase( daoSpecialStorage().readVotingTime(_proposalId), getUintConfig(CONFIG_SPECIAL_PROPOSAL_COMMIT_PHASE), getUintConfig(CONFIG_SPECIAL_PROPOSAL_PHASE_TOTAL) ); _; } function daoWhitelistingStorage() internal view returns (DaoWhitelistingStorage _contract) { _contract = DaoWhitelistingStorage(get_contract(CONTRACT_STORAGE_DAO_WHITELISTING)); } function getAddressConfig(bytes32 _configKey) public view returns (address _configValue) { _configValue = daoConfigsStorage().addressConfigs(_configKey); } function getBytesConfig(bytes32 _configKey) public view returns (bytes32 _configValue) { _configValue = daoConfigsStorage().bytesConfigs(_configKey); } /** @notice Check if a user is a participant in the current quarter */ function isParticipant(address _user) public view returns (bool _is) { _is = (daoRewardsStorage().lastParticipatedQuarter(_user) == currentQuarterNumber()) && (daoStakeStorage().lockedDGDStake(_user) >= getUintConfig(CONFIG_MINIMUM_LOCKED_DGD)); } /** @notice Check if a user is a moderator in the current quarter */ function isModerator(address _user) public view returns (bool _is) { _is = (daoRewardsStorage().lastParticipatedQuarter(_user) == currentQuarterNumber()) && (daoStakeStorage().lockedDGDStake(_user) >= getUintConfig(CONFIG_MINIMUM_DGD_FOR_MODERATOR)) && (daoPointsStorage().getReputation(_user) >= getUintConfig(CONFIG_MINIMUM_REPUTATION_FOR_MODERATOR)); } /** @notice Calculate the start of a specific milestone of a specific proposal. @dev This is calculated from the voting start of the voting round preceding the milestone This would throw if the voting start is 0 (the voting round has not started yet) Note that if the milestoneIndex is exactly the same as the number of milestones, This will just return the end of the last voting round. */ function startOfMilestone(bytes32 _proposalId, uint256 _milestoneIndex) internal view returns (uint256 _milestoneStart) { uint256 _startOfPrecedingVotingRound = daoStorage().readProposalVotingTime(_proposalId, _milestoneIndex); require(_startOfPrecedingVotingRound > 0); // the preceding voting round must have started if (_milestoneIndex == 0) { // This is the 1st milestone, which starts after voting round 0 _milestoneStart = _startOfPrecedingVotingRound .add(getUintConfig(CONFIG_VOTING_PHASE_TOTAL)); } else { // if its the n-th milestone, it starts after voting round n-th _milestoneStart = _startOfPrecedingVotingRound .add(getUintConfig(CONFIG_INTERIM_PHASE_TOTAL)); } } /** @notice Calculate the actual voting start for a voting round, given the tentative start @dev The tentative start is the ideal start. For example, when a proposer finish a milestone, it should be now However, sometimes the tentative start is too close to the end of the quarter, hence, the actual voting start should be pushed to the next quarter */ function getTimelineForNextVote( uint256 _index, uint256 _tentativeVotingStart ) internal view returns (uint256 _actualVotingStart) { uint256 _timeLeftInQuarter = getTimeLeftInQuarter(_tentativeVotingStart); uint256 _votingDuration = getUintConfig(_index == 0 ? CONFIG_VOTING_PHASE_TOTAL : CONFIG_INTERIM_PHASE_TOTAL); _actualVotingStart = _tentativeVotingStart; if (timeInQuarter(_tentativeVotingStart) < getUintConfig(CONFIG_LOCKING_PHASE_DURATION)) { // if the tentative start is during a locking phase _actualVotingStart = _tentativeVotingStart.add( getUintConfig(CONFIG_LOCKING_PHASE_DURATION).sub(timeInQuarter(_tentativeVotingStart)) ); } else if (_timeLeftInQuarter < _votingDuration.add(getUintConfig(CONFIG_VOTE_CLAIMING_DEADLINE))) { // if the time left in quarter is not enough to vote and claim voting _actualVotingStart = _tentativeVotingStart.add( _timeLeftInQuarter.add(getUintConfig(CONFIG_LOCKING_PHASE_DURATION)).add(1) ); } } /** @notice Check if we can add another non-Digix proposal in this quarter @dev There is a max cap to the number of non-Digix proposals CONFIG_NON_DIGIX_PROPOSAL_CAP_PER_QUARTER */ function checkNonDigixProposalLimit(bytes32 _proposalId) internal view { require(isNonDigixProposalsWithinLimit(_proposalId)); } function isNonDigixProposalsWithinLimit(bytes32 _proposalId) internal view returns (bool _withinLimit) { bool _isDigixProposal; (,,,,,,,,,_isDigixProposal) = daoStorage().readProposal(_proposalId); _withinLimit = true; if (!_isDigixProposal) { _withinLimit = daoProposalCounterStorage().proposalCountByQuarter(currentQuarterNumber()) < getUintConfig(CONFIG_NON_DIGIX_PROPOSAL_CAP_PER_QUARTER); } } /** @notice If its a non-Digix proposal, check if the fundings are within limit @dev There is a max cap to the fundings and number of milestones for non-Digix proposals */ function checkNonDigixFundings(uint256[] _milestonesFundings, uint256 _finalReward) internal view { if (!is_founder()) { require(_milestonesFundings.length <= getUintConfig(CONFIG_MAX_MILESTONES_FOR_NON_DIGIX)); require(MathHelper.sumNumbers(_milestonesFundings).add(_finalReward) <= getUintConfig(CONFIG_MAX_FUNDING_FOR_NON_DIGIX)); } } /** @notice Check if msg.sender can do operations as a proposer @dev Note that this function does not check if he is the proposer of the proposal */ function senderCanDoProposerOperations() internal view { require(isMainPhase()); require(isParticipant(msg.sender)); require(identity_storage().is_kyc_approved(msg.sender)); } } library DaoIntermediateStructs { struct VotingCount { // weight of votes "FOR" the voting round uint256 forCount; // weight of votes "AGAINST" the voting round uint256 againstCount; } } library DaoStructs { struct IntermediateResults { // weight of "FOR" votes counted up until the current calculation step uint256 currentForCount; // weight of "AGAINST" votes counted up until the current calculation step uint256 currentAgainstCount; // summation of effectiveDGDs up until the iteration of calculation uint256 currentSumOfEffectiveBalance; // Address of user until which the calculation has been done address countedUntil; } } contract DaoCalculatorService { function minimumVotingQuorumForSpecial() public view returns (uint256); function votingQuotaForSpecialPass(uint256, uint256) public view returns (bool); } contract DaoFundingManager { } contract DaoRewardsManager { } /** @title Contract to claim voting results @author Digix Holdings */ contract DaoSpecialVotingClaims is DaoCommon { using DaoIntermediateStructs for DaoIntermediateStructs.VotingCount; using DaoStructs for DaoStructs.IntermediateResults; event SpecialProposalClaim(bytes32 indexed _proposalId, bool _result); function daoCalculatorService() internal view returns (DaoCalculatorService _contract) { _contract = DaoCalculatorService(get_contract(CONTRACT_SERVICE_DAO_CALCULATOR)); } function daoFundingManager() internal view returns (DaoFundingManager _contract) { _contract = DaoFundingManager(get_contract(CONTRACT_DAO_FUNDING_MANAGER)); } function daoRewardsManager() internal view returns (DaoRewardsManager _contract) { _contract = DaoRewardsManager(get_contract(CONTRACT_DAO_REWARDS_MANAGER)); } constructor(address _resolver) public { require(init(CONTRACT_DAO_SPECIAL_VOTING_CLAIMS, _resolver)); } /** @notice Function to claim the voting result on special proposal @param _proposalId ID of the special proposal @return { "_passed": "Boolean, true if voting passed, throw if failed, returns false if passed deadline" } */ function claimSpecialProposalVotingResult(bytes32 _proposalId, uint256 _operations) public ifNotClaimedSpecial(_proposalId) ifAfterRevealPhaseSpecial(_proposalId) returns (bool _passed) { require(isMainPhase()); if (now > daoSpecialStorage().readVotingTime(_proposalId) .add(getUintConfig(CONFIG_SPECIAL_PROPOSAL_PHASE_TOTAL)) .add(getUintConfig(CONFIG_VOTE_CLAIMING_DEADLINE))) { daoSpecialStorage().setPass(_proposalId, false); return false; } require(msg.sender == daoSpecialStorage().readProposalProposer(_proposalId)); if (_operations == 0) { // if no operations are passed, return false return (false); } DaoStructs.IntermediateResults memory _currentResults; ( _currentResults.countedUntil, _currentResults.currentForCount, _currentResults.currentAgainstCount, ) = intermediateResultsStorage().getIntermediateResults(_proposalId); address[] memory _voters; if (_currentResults.countedUntil == EMPTY_ADDRESS) { _voters = daoListingService().listParticipants( _operations, true ); } else { _voters = daoListingService().listParticipantsFrom( _currentResults.countedUntil, _operations, true ); } address _lastVoter = _voters[_voters.length - 1]; DaoIntermediateStructs.VotingCount memory _voteCount; (_voteCount.forCount, _voteCount.againstCount) = daoSpecialStorage().readVotingCount(_proposalId, _voters); _currentResults.countedUntil = _lastVoter; _currentResults.currentForCount = _currentResults.currentForCount.add(_voteCount.forCount); _currentResults.currentAgainstCount = _currentResults.currentAgainstCount.add(_voteCount.againstCount); if (_lastVoter == daoStakeStorage().readLastParticipant()) { // this is already the last transaction, we have counted all the votes if ( (_currentResults.currentForCount.add(_currentResults.currentAgainstCount) > daoCalculatorService().minimumVotingQuorumForSpecial()) && (daoCalculatorService().votingQuotaForSpecialPass(_currentResults.currentForCount, _currentResults.currentAgainstCount)) ) { _passed = true; setConfigs(_proposalId); } daoSpecialStorage().setPass(_proposalId, _passed); daoSpecialStorage().setVotingClaim(_proposalId, true); emit SpecialProposalClaim(_proposalId, _passed); } else { intermediateResultsStorage().setIntermediateResults( _proposalId, _currentResults.countedUntil, _currentResults.currentForCount, _currentResults.currentAgainstCount, 0 ); } } function setConfigs(bytes32 _proposalId) private { uint256[] memory _uintConfigs; address[] memory _addressConfigs; bytes32[] memory _bytesConfigs; ( _uintConfigs, _addressConfigs, _bytesConfigs ) = daoSpecialStorage().readConfigs(_proposalId); daoConfigsStorage().updateUintConfigs(_uintConfigs); } }
weight of votes "FOR" the voting round weight of votes "AGAINST" the voting round
@dev Note that this function does not check if he is the proposer of the proposal function senderCanDoProposerOperations() internal view } } struct VotingCount { uint256 forCount; uint256 againstCount; }
5,441,765
[ 1, 4865, 434, 19588, 315, 7473, 6, 326, 331, 17128, 3643, 3119, 434, 19588, 315, 1781, 6964, 882, 6, 326, 331, 17128, 3643, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 632, 5206, 3609, 716, 333, 445, 1552, 486, 866, 309, 3904, 353, 326, 450, 5607, 434, 326, 14708, 203, 565, 445, 5793, 2568, 3244, 626, 5607, 9343, 1435, 203, 3639, 2713, 203, 3639, 1476, 203, 565, 289, 203, 97, 203, 203, 565, 1958, 776, 17128, 1380, 288, 203, 3639, 2254, 5034, 364, 1380, 31, 203, 3639, 2254, 5034, 5314, 1380, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /* Internal Imports */ import {ExecutionManager} from "./ExecutionManager.sol"; /** * @title L2ExecutionManager * @notice This extension of ExecutionManager that should only run in L2 because it has optimistic execution details * that are unnecessary and inefficient to run in L1. */ contract L2ExecutionManager is ExecutionManager { mapping(bytes32 => bytes32) ovmHashToEvmHash; constructor( uint256 _opcodeWhitelistMask, address _owner, uint _gasLimit, bool _overridePurityChecker ) ExecutionManager(_opcodeWhitelistMask, _owner, _gasLimit, _overridePurityChecker) public {} /** @notice Associates the provided OVM transaction hash with the EVM transaction hash so that we can properly look up transaction receipts based on the OVM transaction hash. @param ovmTransactionHash The OVM transaction hash, used publicly as the reference to the transaction. @param internalTransactionHash The internal transaction hash of the transaction actually executed. */ function mapOvmTransactionHashToInternalTransactionHash(bytes32 ovmTransactionHash, bytes32 internalTransactionHash) public { ovmHashToEvmHash[ovmTransactionHash] = internalTransactionHash; } /** @notice Gets the EVM transaction hash associated with the provided OVM transaction hash. @param ovmTransactionHash The OVM transaction hash. @return The associated EVM transaction hash. */ function getInternalTransactionHash(bytes32 ovmTransactionHash) public view returns (bytes32) { return ovmHashToEvmHash[ovmTransactionHash]; } }
Internal Imports */
import {ExecutionManager} from "./ExecutionManager.sol";
5,508,730
[ 1, 3061, 2221, 4363, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5666, 288, 3210, 1318, 97, 628, 25165, 3210, 1318, 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, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2019-12-19 */ // hevm: flattened sources of src/Redeemer.sol pragma solidity =0.5.11 >0.4.13 >0.4.20 >=0.4.23 >=0.5.0 <0.6.0 >=0.5.5 <0.6.0 >=0.5.11 <0.6.0; ////// lib/dpass/lib/openzeppelin-contracts/src/GSN/Context.sol /* pragma solidity ^0.5.0; */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } ////// lib/dpass/lib/openzeppelin-contracts/src/math/SafeMath.sol /* pragma solidity ^0.5.0; */ /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } ////// lib/dpass/lib/openzeppelin-contracts/src/drafts/Counters.sol /* pragma solidity ^0.5.0; */ /* import "../math/SafeMath.sol"; */ /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/IERC165.sol /* pragma solidity ^0.5.0; */ /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/ERC165.sol /* pragma solidity ^0.5.0; */ /* import "./IERC165.sol"; */ /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../introspection/IERC165.sol"; */ /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Receiver.sol /* pragma solidity ^0.5.0; */ /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } ////// lib/dpass/lib/openzeppelin-contracts/src/utils/Address.sol /* pragma solidity ^0.5.5; */ /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721.sol"; */ /* import "./IERC721Receiver.sol"; */ /* import "../../math/SafeMath.sol"; */ /* import "../../utils/Address.sol"; */ /* import "../../drafts/Counters.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS _tokenApprovals[tokenId] = address(0); } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721Enumerable.sol"; */ /* import "./ERC721.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (block.gaslimit != lastTokenIndex) { //injected CONTRACT AFFECTED BY MINERS uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./ERC721.sol"; */ /* import "./IERC721Metadata.sol"; */ /* import "../../introspection/ERC165.sol"; */ contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (block.gaslimit != 0) { //injected CONTRACT AFFECTED BY MINERS delete _tokenURIs[tokenId]; } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Full.sol /* pragma solidity ^0.5.0; */ /* import "./ERC721.sol"; */ /* import "./ERC721Enumerable.sol"; */ /* import "./ERC721Metadata.sol"; */ /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } ////// lib/ds-auth/src/auth.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (block.coinbase == owner) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } ////// lib/dpass/src/Dpass.sol /* pragma solidity ^0.5.11; */ // /** // * How to use dapp and openzeppelin-solidity https://github.com/dapphub/dapp/issues/70 // * ERC-721 standart: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md // * // */ /* import "ds-auth/auth.sol"; */ /* import "openzeppelin-contracts/token/ERC721/ERC721Full.sol"; */ contract DpassEvents { event LogConfigChange(bytes32 what, bytes32 value1, bytes32 value2); event LogCustodianChanged(uint tokenId, address custodian); event LogDiamondAttributesHashChange(uint indexed tokenId, bytes8 hashAlgorithm); event LogDiamondMinted( address owner, uint indexed tokenId, bytes3 issuer, bytes16 report, bytes8 state ); event LogRedeem(uint indexed tokenId); event LogSale(uint indexed tokenId); event LogStateChanged(uint indexed tokenId, bytes32 state); } contract Dpass is DSAuth, ERC721Full, DpassEvents { string private _name = "Diamond Passport"; string private _symbol = "Dpass"; struct Diamond { bytes3 issuer; bytes16 report; bytes8 state; bytes20 cccc; uint24 carat; bytes8 currentHashingAlgorithm; // Current hashing algorithm to check in the proof mapping } Diamond[] diamonds; // List of Dpasses mapping(uint => address) public custodian; // custodian that holds a Dpass token mapping (uint => mapping(bytes32 => bytes32)) public proof; // Prof of attributes integrity [tokenId][hashingAlgorithm] => hash mapping (bytes32 => mapping (bytes32 => bool)) diamondIndex; // List of dpasses by issuer and report number [issuer][number] mapping (uint256 => uint256) public recreated; // List of recreated tokens. old tokenId => new tokenId mapping(bytes32 => mapping(bytes32 => bool)) public canTransit; // List of state transition rules in format from => to = true/false mapping(bytes32 => bool) public ccccs; constructor () public ERC721Full(_name, _symbol) { // Create dummy diamond to start real diamond minting from 1 Diamond memory _diamond = Diamond({ issuer: "Slf", report: "0", state: "invalid", cccc: "BR,IF,D,0001", carat: 1, currentHashingAlgorithm: "" }); diamonds.push(_diamond); _mint(address(this), 0); // Transition rules canTransit["valid"]["invalid"] = true; canTransit["valid"]["removed"] = true; canTransit["valid"]["sale"] = true; canTransit["valid"]["redeemed"] = true; canTransit["sale"]["valid"] = true; canTransit["sale"]["invalid"] = true; canTransit["sale"]["removed"] = true; } modifier onlyOwnerOf(uint _tokenId) { require(ownerOf(_tokenId) == msg.sender, "dpass-access-denied"); _; } modifier onlyApproved(uint _tokenId) { require( ownerOf(_tokenId) == msg.sender || isApprovedForAll(ownerOf(_tokenId), msg.sender) || getApproved(_tokenId) == msg.sender , "dpass-access-denied"); _; } modifier ifExist(uint _tokenId) { require(_exists(_tokenId), "dpass-diamond-does-not-exist"); _; } modifier onlyValid(uint _tokenId) { // TODO: DRY, _exists already check require(_exists(_tokenId), "dpass-diamond-does-not-exist"); Diamond storage _diamond = diamonds[_tokenId]; require(_diamond.state != "invalid", "dpass-invalid-diamond"); _; } /** * @dev Custom accessor to create a unique token * @param _to address of diamond owner * @param _issuer string the issuer agency name * @param _report string the issuer agency unique Nr. * @param _state diamond state, "sale" is the init state * @param _cccc bytes32 cut, clarity, color, and carat class of diamond * @param _carat uint24 carat of diamond with 2 decimals precision * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) * @param _custodian the custodian of minted dpass * @return Return Diamond tokenId of the diamonds list */ function mintDiamondTo( address _to, address _custodian, bytes3 _issuer, bytes16 _report, bytes8 _state, bytes20 _cccc, uint24 _carat, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth returns(uint) { require(ccccs[_cccc], "dpass-wrong-cccc"); _addToDiamondIndex(_issuer, _report); Diamond memory _diamond = Diamond({ issuer: _issuer, report: _report, state: _state, cccc: _cccc, carat: _carat, currentHashingAlgorithm: _currentHashingAlgorithm }); uint _tokenId = diamonds.push(_diamond) - 1; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; custodian[_tokenId] = _custodian; _mint(_to, _tokenId); emit LogDiamondMinted(_to, _tokenId, _issuer, _report, _state); return _tokenId; } /** * @dev Update _tokenId attributes * @param _attributesHash new attibutes hash value * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) */ function updateAttributesHash( uint _tokenId, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth onlyValid(_tokenId) { Diamond storage _diamond = diamonds[_tokenId]; _diamond.currentHashingAlgorithm = _currentHashingAlgorithm; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; emit LogDiamondAttributesHashChange(_tokenId, _currentHashingAlgorithm); } /** * @dev Link old and the same new dpass */ function linkOldToNewToken(uint _tokenId, uint _newTokenId) public auth { require(_exists(_tokenId), "dpass-old-diamond-doesnt-exist"); require(_exists(_newTokenId), "dpass-new-diamond-doesnt-exist"); recreated[_tokenId] = _newTokenId; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg.sender to be the owner, approved, or operator and not invalid token * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public onlyValid(_tokenId) { _checkTransfer(_tokenId); super.transferFrom(_from, _to, _tokenId); } /* * @dev Check if transferPossible */ function _checkTransfer(uint256 _tokenId) internal view { bytes32 state = diamonds[_tokenId].state; require(state != "removed", "dpass-token-removed"); require(state != "invalid", "dpass-token-deleted"); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { _checkTransfer(_tokenId); super.safeTransferFrom(_from, _to, _tokenId); } /* * @dev Returns the current state of diamond */ function getState(uint _tokenId) public view ifExist(_tokenId) returns (bytes32) { return diamonds[_tokenId].state; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamondInfo(uint _tokenId) public view ifExist(_tokenId) returns ( address[2] memory ownerCustodian, bytes32[6] memory attrs, uint24 carat_ ) { Diamond storage _diamond = diamonds[_tokenId]; bytes32 attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; ownerCustodian[0] = ownerOf(_tokenId); ownerCustodian[1] = custodian[_tokenId]; attrs[0] = _diamond.issuer; attrs[1] = _diamond.report; attrs[2] = _diamond.state; attrs[3] = _diamond.cccc; attrs[4] = attributesHash; attrs[5] = _diamond.currentHashingAlgorithm; carat_ = _diamond.carat; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamond(uint _tokenId) public view ifExist(_tokenId) returns ( bytes3 issuer, bytes16 report, bytes8 state, bytes20 cccc, uint24 carat, bytes32 attributesHash ) { Diamond storage _diamond = diamonds[_tokenId]; attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; return ( _diamond.issuer, _diamond.report, _diamond.state, _diamond.cccc, _diamond.carat, attributesHash ); } /** * @dev Gets the Diamond issuer and it unique nr at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Issuer and unique Nr. a specific diamond */ function getDiamondIssuerAndReport(uint _tokenId) public view ifExist(_tokenId) returns(bytes32, bytes32) { Diamond storage _diamond = diamonds[_tokenId]; return (_diamond.issuer, _diamond.report); } /** * @dev Set cccc values that are allowed to be entered for diamonds * @param _cccc bytes32 cccc value that will be enabled/disabled * @param _allowed bool allow or disallow cccc */ function setCccc(bytes32 _cccc, bool _allowed) public auth { ccccs[_cccc] = _allowed; emit LogConfigChange("cccc", _cccc, _allowed ? bytes32("1") : bytes32("0")); } /** * @dev Set new custodian for dpass */ function setCustodian(uint _tokenId, address _newCustodian) public auth { require(_newCustodian != address(0), "dpass-wrong-address"); custodian[_tokenId] = _newCustodian; emit LogCustodianChanged(_tokenId, _newCustodian); } /** * @dev Get the custodian of Dpass. */ function getCustodian(uint _tokenId) public view returns(address) { return custodian[_tokenId]; } /** * @dev Enable transition _from -> _to state */ function enableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = true; emit LogConfigChange("canTransit", _from, _to); } /** * @dev Disable transition _from -> _to state */ function disableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = false; emit LogConfigChange("canNotTransit", _from, _to); } /** * @dev Set Diamond sale state * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setSaleState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("sale", _tokenId); emit LogSale(_tokenId); } /** * @dev Set Diamond invalid state * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setInvalidState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("invalid", _tokenId); _removeDiamondFromIndex(_tokenId); } /** * @dev Make diamond state as redeemed, change owner to contract owner * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function redeem(uint _tokenId) public ifExist(_tokenId) onlyOwnerOf(_tokenId) { _setState("redeemed", _tokenId); _removeDiamondFromIndex(_tokenId); emit LogRedeem(_tokenId); } /** * @dev Change diamond state. * @param _newState new token state * @param _tokenId represent the index of diamond */ function setState(bytes8 _newState, uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState(_newState, _tokenId); } // Private functions /** * @dev Validate transiton from currentState to newState. Revert on invalid transition * @param _currentState current diamond state * @param _newState new diamond state */ function _validateStateTransitionTo(bytes8 _currentState, bytes8 _newState) internal view { require(_currentState != _newState, "dpass-already-in-that-state"); require(canTransit[_currentState][_newState], "dpass-transition-now-allowed"); } /** * @dev Add Issuer and report with validation to uniqueness. Revert on invalid existance * @param _issuer issuer like GIA * @param _report issuer unique nr. */ function _addToDiamondIndex(bytes32 _issuer, bytes32 _report) internal { require(!diamondIndex[_issuer][_report], "dpass-issuer-report-not-unique"); diamondIndex[_issuer][_report] = true; } function _removeDiamondFromIndex(uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; diamondIndex[_diamond.issuer][_diamond.report] = false; } /** * @dev Change diamond state with logging. Revert on invalid transition * @param _newState new token state * @param _tokenId represent the index of diamond */ function _setState(bytes8 _newState, uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; _validateStateTransitionTo(_diamond.state, _newState); _diamond.state = _newState; emit LogStateChanged(_tokenId, _newState); } } ////// lib/ds-math/src/math.sol /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >0.4.13; */ contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } ////// lib/ds-note/src/note.sol /// note.sol -- the `note' modifier, for logging calls as events // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue } emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); _; } } ////// lib/ds-stop/src/stop.sol /// stop.sol -- mixin for enable/disable functionality // Copyright (C) 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "ds-auth/auth.sol"; */ /* import "ds-note/note.sol"; */ contract DSStop is DSNote, DSAuth { bool public stopped; modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function stop() public auth note { stopped = true; } function start() public auth note { stopped = false; } } ////// lib/ds-token/lib/erc20/src/erc20.sol /// erc20.sol -- API for the ERC20 token standard // See <https://github.com/ethereum/EIPs/issues/20>. // This file likely does not meet the threshold of originality // required for copyright to apply. As a result, this is free and // unencumbered software belonging to the public domain. /* pragma solidity >0.4.20; */ contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } ////// lib/ds-token/src/base.sol /// base.sol -- basic ERC20 implementation // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "erc20/erc20.sol"; */ /* import "ds-math/math.sol"; */ contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } } ////// lib/ds-token/src/token.sol /// token.sol -- ERC20 implementation with minting and burning // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "ds-stop/stop.sol"; */ /* import "./base.sol"; */ contract DSToken is DSTokenBase(0), DSStop { bytes32 public symbol; uint256 public decimals = 18; // standard token precision. override to customize constructor(bytes32 symbol_) public { symbol = symbol_; } event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function push(address dst, uint wad) public { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) public { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) public { transferFrom(src, dst, wad); } function mint(uint wad) public { mint(msg.sender, wad); } function burn(uint wad) public { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { _balances[guy] = add(_balances[guy], wad); _supply = add(_supply, wad); emit Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) { require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad); } require(_balances[guy] >= wad, "ds-token-insufficient-balance"); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); } // Optional token name bytes32 public name = ""; function setName(bytes32 name_) public auth { name = name_; } } ////// src/Wallet.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /** * @dev Interface to ERC20 tokens. */ contract TrustedErc20Wallet { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } /** * @dev Interface to ERC721 tokens. */ contract TrustedErci721Wallet { function balanceOf(address guy) public view returns (uint); function ownerOf(uint256 tokenId) public view returns (address); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address); function setApprovalForAll(address to, bool approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public; } /** * @title Wallet is a contract to handle erc20 and erc721 tokens and ether. * @dev This token is used to store and transfer tokens that were paid as fee by users. */ contract Wallet is DSAuth, DSStop, DSMath { event LogTransferEth(address src, address dst, uint256 amount); address public eth = address(0xee); bytes32 public name = "Wal"; // set human readable name for contract bytes32 public symbol = "Wal"; // set human readable name for contract function () external payable { } function transfer(address token, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, address(this), dst, amt); } function transferFrom(address token, address src, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, src, dst, amt); } function totalSupply(address token) public view returns (uint){ if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-total-supply-for-ether"); } else { return TrustedErc20Wallet(token).totalSupply(); } } function balanceOf(address token, address src) public view returns (uint) { if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return src.balance; } else { return TrustedErc20Wallet(token).balanceOf(src); } } function allowance(address token, address src, address guy) public view returns (uint) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-allowance-for-ether"); } else { return TrustedErc20Wallet(token).allowance(src, guy); } } function approve(address token, address guy, uint wad) public auth returns (bool) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-can-not-approve-ether"); } else { return TrustedErc20Wallet(token).approve(guy, wad); } } function balanceOf721(address token, address guy) public view returns (uint) { return TrustedErci721Wallet(token).balanceOf(guy); } function ownerOf721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).ownerOf(tokenId); } function approve721(address token, address to, uint256 tokenId) public { TrustedErci721Wallet(token).approve(to, tokenId); } function getApproved721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).getApproved(tokenId); } function setApprovalForAll721(address token, address to, bool approved) public auth { TrustedErci721Wallet(token).setApprovalForAll(to, approved); } function isApprovedForAll721(address token, address owner, address operator) public view returns (bool) { return TrustedErci721Wallet(token).isApprovedForAll(owner, operator); } function transferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).transferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId, bytes memory _data) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId, _data); } function transfer721(address token, address to, uint tokenId) public auth { TrustedErci721Wallet(token).transferFrom(address(this), to, tokenId); } /** * @dev send token or ether to destination */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ TrustedErc20Wallet erc20 = TrustedErc20Wallet(token); if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.timestamp > 0) erc20.transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Liquidity.sol /* pragma solidity ^0.5.11; */ /* import "./Wallet.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ contract Liquidity is Wallet { bytes32 public name = "Liq"; // set human readable name for contract bytes32 public symbol = "Liq"; // set human readable name for contract function burn(address dpt, address burner, uint256 burnValue) public auth { transfer(dpt, address(uint160(address(burner))), burnValue); } } ////// src/SimpleAssetManagement.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "dpass/Dpass.sol"; */ /** * @dev Contract to get ETH/USD price */ contract TrustedFeedLike { function peek() external view returns (bytes32, bool); } /** * @dev ExchangeContract to get buyPrice from */ contract TrustedDiamondExchangeAsm { function buyPrice(address token_, address owner_, uint256 tokenId_) external view returns (uint); } /** * @title Contract to handle diamond assets */ contract SimpleAssetManagement is DSAuth { event LogAudit(address sender, address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterwal_); event LogConfigChange(address sender, bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 amount); event LogBasePrice(address sender_, address token_, uint256 tokenId_, uint256 price_); event LogCdcValue(uint256 totalCdcV, uint256 cdcValue, address token); event LogCdcPurchaseValue(uint256 totalCdcPurchaseV, uint256 cdcPurchaseValue, address token); event LogDcdcValue(uint256 totalDcdcV, uint256 ddcValue, address token); event LogDcdcCustodianValue(uint256 totalDcdcCustV, uint256 dcdcCustV, address dcdc, address custodian); event LogDcdcTotalCustodianValue(uint256 totalDcdcCustV, uint256 totalDcdcV, address custodian); event LogDpassValue(uint256 totalDpassCustV, uint256 totalDpassV, address custodian); event LogForceUpdateCollateralDpass(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); event LogForceUpdateCollateralDcdc(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); mapping( address => mapping( uint => uint)) public basePrice; // the base price used for collateral valuation mapping(address => bool) public custodians; // returns true for custodians mapping(address => uint) // total base currency value of custodians collaterals public totalDpassCustV; mapping(address => uint) private rate; // current rate of a token in base currency mapping(address => uint) public cdcV; // base currency value of cdc token mapping(address => uint) public dcdcV; // base currency value of dcdc token mapping(address => uint) public totalDcdcCustV; // total value of all dcdcs at custodian mapping( address => mapping( address => uint)) public dcdcCustV; // dcdcCustV[dcdc][custodian] value of dcdc at custodian mapping(address => bool) public payTokens; // returns true for tokens allowed to make payment to custodians with mapping(address => bool) public dpasses; // returns true for dpass tokens allowed in this contract mapping(address => bool) public dcdcs; // returns true for tokens representing cdc assets (without gia number) that are allowed in this contract mapping(address => bool) public cdcs; // returns true for cdc tokens allowed in this contract mapping(address => uint) public decimals; // stores decimals for each ERC20 token eg: 1000000000000000000 denotes 18 decimal precision mapping(address => bool) public decimalsSet; // stores decimals for each ERC20 token mapping(address => address) public priceFeed; // price feed address for token mapping(address => uint) public tokenPurchaseRate; // the average purchase rate of a token. This is the ... // ... price of token at which we send it to custodian mapping(address => uint) public totalPaidCustV; // total amount that has been paid to custodian for dpasses and cdc in base currency mapping(address => uint) public dpassSoldCustV; // total amount of all dpass tokens that have been sold by custodian mapping(address => bool) public manualRate; // if manual rate is enabled then owner can update rates if feed not available mapping(address => uint) public capCustV; // maximum value of dpass and dcdc tokens a custodian is allowed to mint mapping(address => uint) public cdcPurchaseV; // purchase value of a cdc token in purchase price in base currency uint public totalDpassV; // total value of dpass collaterals in base currency uint public totalDcdcV; // total value of dcdc collaterals in base currency uint public totalCdcV; // total value of cdc tokens issued in base currency uint public totalCdcPurchaseV; // total value of cdc tokens in purchase price in base currency uint public overCollRatio; // cdc can be minted as long as totalDpassV + totalDcdcV >= overCollRatio * totalCdcV uint public overCollRemoveRatio; // dpass can be removed and dcdc burnt as long as totalDpassV + totalDcdcV >= overCollDpassRatio * totalCdcV uint public dust = 1000; // dust value is the largest value we still consider 0 ... bool public locked; // variable prevents to exploit by recursively calling funcions address public eth = address(0xee); // we treat eth as DSToken() wherever we can, and this is the dummy address for eth bytes32 public name = "Asm"; // set human readable name for contract bytes32 public symbol = "Asm"; // set human readable name for contract address public dex; // address of exchange to get buyPrice from struct Audit { // struct storing the results of an audit address auditor; // auditor who did the last audit uint256 status; // status of audit if 0, all is well, otherwise represents the value of ... // diamonds that there are problems with bytes32 descriptionHash; // hash of the description file that describes the last audit in detail. ... // ... Auditors must have a detailed description of all the findings they had at ... // ... custodian, and are legally fully responsible for their documents. bytes32 descriptionUrl; // url of the description file that details the results of the audit. File should be digitally signed. And the files total content should be hashed with keccak256() to make sure unmutability. uint nextAuditBefore; // proposed time of next audit. The audit should be at least at every 3 months. } mapping(address => Audit) public audit; // containing the last audit reports for all custodians. uint32 public auditInterval = 1776000; // represents 3 months of audit interwal in which an audit is mandatory for custodian. /** * @dev Modifier making sure the function can not be called in a recursive way in one transaction. */ modifier nonReentrant { require(!locked, "asm-reentrancy-detected"); locked = true; _; locked = false; } //-----------included-from-ds-math---------------------------------begin uint constant WAD = 10 ** 18; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end /** * @dev Set configuration variables of asset managment contract. * @param what_ bytes32 tells to function what to set. * @param value_ bytes32 setter variable. Its meaning is dependent on what_. * @param value1_ bytes32 setter variable. Its meaning is dependent on what_. * @param value2_ bytes32 setter variable. Its meaning is dependent on what_. * */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require(payTokens[token] || cdcs[token] || dcdcs[token], "asm-token-not-allowed-rate"); require(value > 0, "asm-rate-must-be-gt-0"); rate[token] = value; } else if (blockhash(block.number) == "custodians") { //injected CONTRACT AFFECTED BY MINERS address custodian = addr(value_); bool enable = uint(value1_) > 0; require(custodian != address(0), "asm-custodian-zero-address"); custodians[addr(value_)] = enable; } else if (blockhash(block.number) == "overCollRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRatio = uint(value_); require(overCollRatio >= 1 ether, "asm-system-must-be-overcollaterized"); _requireSystemCollaterized(); } else if (blockhash(block.number) == "overCollRemoveRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRemoveRatio = uint(value_); require(overCollRemoveRatio >= 1 ether, "asm-must-be-gt-1-ether"); require(overCollRemoveRatio <= overCollRatio, "asm-must-be-lt-overcollratio"); _requireSystemRemoveCollaterized(); } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(addr(value1_) != address(address(0x0)), "asm-wrong-pricefeed-address"); require(addr(value_) != address(address(0x0)), "asm-wrong-token-address"); priceFeed[addr(value_)] = addr(value1_); } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint decimal = uint256(value1_); require(token != address(0x0), "asm-wrong-address"); decimals[token] = 10 ** decimal; decimalsSet[token] = true; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); bool enable = uint(value1_) > 0; require(token != address(address(0x0)), "asm-wrong-token-address"); require(priceFeed[token] != address(address(0x0)), "asm-priceFeed-first"); manualRate[token] = enable; } else if (blockhash(block.number) == "payTokens") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "asm-pay-token-address-no-zero"); payTokens[token] = uint(value1_) > 0; } else if (blockhash(block.number) == "dcdcs") { //injected CONTRACT AFFECTED BY MINERS address newDcdc = addr(value_); bool enable = uint(value1_) > 0; require(newDcdc != address(0), "asm-dcdc-address-zero"); require(priceFeed[newDcdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newDcdc],"asm-no-decimals-set-for-token"); dcdcs[newDcdc] = enable; _updateTotalDcdcV(newDcdc); } else if (blockhash(block.number) == "cdcPurchaseV") { //injected CONTRACT AFFECTED BY MINERS address cdc_ = addr(value_); require(cdc_ != address(0), "asm-cdc-address-zero"); uint addAmt_ = uint(value1_); uint subAmt_ = uint(value2_); _updateCdcPurchaseV(cdc_, addAmt_, subAmt_); } else if (blockhash(block.number) == "cdcs") { //injected CONTRACT AFFECTED BY MINERS address newCdc = addr(value_); bool enable = uint(value1_) > 0; require(priceFeed[newCdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newCdc], "asm-add-decimals-first"); require(newCdc != address(0), "asm-cdc-address-zero"); require( DSToken(newCdc).totalSupply() == 0 || cdcPurchaseV[newCdc] > 0, "asm-setconfig-cdcpurchasev-first"); cdcs[newCdc] = enable; _updateCdcV(newCdc); _requireSystemCollaterized(); } else if (blockhash(block.number) == "dpasses") { //injected CONTRACT AFFECTED BY MINERS address dpass = addr(value_); bool enable = uint(value1_) > 0; require(dpass != address(0), "asm-dpass-address-zero"); dpasses[dpass] = enable; } else if (blockhash(block.number) == "approve") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); uint value = uint(value2_); require(decimalsSet[token],"asm-no-decimals-set-for-token"); require(dst != address(0), "asm-dst-zero-address"); DSToken(token).approve(dst, value); } else if (blockhash(block.number) == "setApproveForAll") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); bool enable = uint(value2_) > 0; require(dpasses[token],"asm-not-a-dpass-token"); require(dst != address(0), "asm-dst-zero-address"); Dpass(token).setApprovalForAll(dst, enable); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS dex = addr(value_); } else if (blockhash(block.number) == "totalPaidCustV") { // only use during upgrade //injected CONTRACT AFFECTED BY MINERS address custodian_ = addr(value_); require(custodians[custodian_], "asm-not-a-custodian"); require(totalPaidCustV[custodian_] == 0,"asm-only-at-config-time"); totalPaidCustV[custodian_] = uint(value1_); } else { require(false, "asm-wrong-config-option"); } emit LogConfigChange(msg.sender, what_, value_, value1_); } /** * @dev Set rate (price in base currency) for token. * @param token_ address token to set bse currency rate for * @param value_ uint256 the rate in base currency to set */ function setRate(address token_, uint256 value_) public auth { setConfig("rate", bytes32(uint(token_)), bytes32(value_), ""); } /** * @dev Get newest rate in base currency from priceFeed for token. This function returns the newest token price in base currency. Burns more gas than getRate(). * @param token_ address token to get most up-to-date rates. */ function getRateNewest(address token_) public view auth returns (uint) { return _getNewRate(token_); } /** * @dev Get currently stored rate in base currency from priceFeed for token. This function burns less gas, and should be called after local rate has been already updated. * @param token_ address to get rate for. */ function getRate(address token_) public view auth returns (uint) { return rate[token_]; } /* * @dev Convert address to bytes32 * @param b_ bytes32 turn this value to address */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Set base price_ for a diamond. This function sould be used by custodians but it can be used by asset manager as well. * @param token_ address token for whom we set baseprice. * @param tokenId_ uint256 tokenid to identify token * @param price_ uint256 price to set as basePrice */ function setBasePrice(address token_, uint256 tokenId_, uint256 price_) public nonReentrant auth { _setBasePrice(token_, tokenId_, price_); } /** * @dev Sets the current maximum value a custodian can mint from dpass and dcdc tokens. * @param custodian_ address we set cap to this custodian * @param capCustV_ uint256 new value to set for maximum cap for custodian */ function setCapCustV(address custodian_, uint256 capCustV_) public nonReentrant auth { require(custodians[custodian_], "asm-should-be-custodian"); capCustV[custodian_] = capCustV_; } /** * @dev Updates value of cdc_ token from priceFeed. This function is called by oracles but can be executed by anyone wanting update cdc_ value in the system. This function should be called every time the price of cdc has been updated. * @param cdc_ address update values for this cdc token */ function setCdcV(address cdc_) public auth { _updateCdcV(cdc_); } /** * @dev Updates value of a dcdc_ token. This function should be called by oracles but anyone can call it. This should be called every time the price of dcdc token was updated. * @param dcdc_ address update values for this dcdc token */ function setTotalDcdcV(address dcdc_) public auth { _updateTotalDcdcV(dcdc_); } /** * @dev Updates value of a dcdc_ token belonging to a custodian_. This function should be called by oracles or custodians but anyone can call it. * @param dcdc_ address the dcdc_ token we want to update the value for * @param custodian_ address the custodian_ whose total dcdc_ values will be updated. */ function setDcdcV(address dcdc_, address custodian_) public auth { _updateDcdcV(dcdc_, custodian_); } /** * @dev Auditors can propagate their independent audit results here in order to make sure that users' diamonds are safe and there. * @param custodian_ address the custodian, who the audit was done for. * @param status_ uint the status of result. 0 means everything is fine, else should be the value of amount in geopardy or questionable. * @param descriptionHash_ bytes32 keccak256() hash of the full audit statement available at descriptionUrl_. In the document all parameters * should be described concerning the availability, and quality of collateral at custodian. * @param descriptionUrl_ bytes32 the url of the audit document. Whenever this is published the document must already be online to avoid fraud. * @param auditInterval_ uint the proposed time in seconds until next audit. If auditor thinks more frequent audits are required he can express his wish here. */ function setAudit( address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterval_ ) public nonReentrant auth { uint32 minInterval_; require(custodians[custodian_], "asm-audit-not-a-custodian"); require(auditInterval_ != 0, "asm-audit-interval-zero"); minInterval_ = uint32(min(auditInterval_, auditInterval)); Audit memory audit_ = Audit({ auditor: msg.sender, status: status_, descriptionHash: descriptionHash_, descriptionUrl: descriptionUrl_, nextAuditBefore: block.timestamp + minInterval_ }); audit[custodian_] = audit_; emit LogAudit(msg.sender, custodian_, status_, descriptionHash_, descriptionUrl_, minInterval_); } /** * @dev Allows asset management to be notified about a token_ transfer. If system would get undercollaterized because of transfer it will be reverted. * @param token_ address the token_ that has been sent during transaction * @param src_ address the source address the token_ has been sent from * @param dst_ address the destination address the token_ has been sent to * @param amtOrId_ uint the amount of tokens sent if token_ is a DSToken or the id of token_ if token_ is a Dpass token_. */ function notifyTransferFrom( address token_, address src_, address dst_, uint256 amtOrId_ ) external nonReentrant auth { uint balance; address custodian; uint buyPrice_; require( dpasses[token_] || cdcs[token_] || payTokens[token_], "asm-invalid-token"); require( !dpasses[token_] || Dpass(token_).getState(amtOrId_) == "sale", "asm-ntf-token-state-not-sale"); if(dpasses[token_] && src_ == address(this)) { // custodian sells dpass to user custodian = Dpass(token_).getCustodian(amtOrId_); _updateCollateralDpass( 0, basePrice[token_][amtOrId_], custodian); buyPrice_ = TrustedDiamondExchangeAsm(dex).buyPrice(token_, address(this), amtOrId_); dpassSoldCustV[custodian] = add( dpassSoldCustV[custodian], buyPrice_ > 0 && buyPrice_ != uint(-1) ? buyPrice_ : basePrice[token_][amtOrId_]); Dpass(token_).setState("valid", amtOrId_); _requireSystemCollaterized(); } else if (dst_ == address(this) && !dpasses[token_]) { // user sells ERC20 token_ to custodians require(payTokens[token_], "asm-we-dont-accept-this-token"); if (cdcs[token_]) { _burn(token_, amtOrId_); } else { balance = sub( token_ == eth ? address(this).balance : DSToken(token_).balanceOf(address(this)), amtOrId_); // this assumes that first tokens are sent, than ... // ... notifyTransferFrom is called, if it is the other way ... // ... around then amtOrId_ must not be subrtacted from current ... // ... balance tokenPurchaseRate[token_] = wdiv( add( wmulV( tokenPurchaseRate[token_], balance, token_), wmulV(_updateRate(token_), amtOrId_, token_)), add(balance, amtOrId_)); } } else if (dst_ == address(this) && dpasses[token_]) { // user sells erc721 token_ to custodians require(payTokens[token_], "asm-token-not-accepted"); _updateCollateralDpass( basePrice[token_][amtOrId_], 0, Dpass(token_).getCustodian(amtOrId_)); Dpass(token_).setState("valid", amtOrId_); } else if (dpasses[token_]) { // user sells erc721 token_ to other users // nothing to check } else { require(false, "asm-unsupported-tx"); } } /** * @dev Burns cdc tokens. Also updates system collaterization. Cdc tokens are burnt when users pay with cdc on exchange or when users redeem cdcs. * @param token_ address cdc token_ that needs to be burnt * @param amt_ uint the amount to burn. */ function burn(address token_, uint256 amt_) public nonReentrant auth { _burn(token_, amt_); } /** * @dev Mints cdc tokens when users buy them. Also updates system collaterization. * @param token_ address cdc token_ that needs to be minted * @param dst_ address the address for whom cdc token_ will be minted for. */ function mint(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, amt_, 0); _requireSystemCollaterized(); } /** * @dev Mints dcdc tokens for custodians. This function should only be run by custodians. * @param token_ address dcdc token_ that needs to be minted * @param dst_ address the address for whom dcdc token will be minted for. * @param amt_ uint amount to be minted */ function mintDcdc(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || dst_ == msg.sender, "asm-can-not-mint-for-dst"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateDcdcV(token_, dst_); _requireCapCustV(dst_); } /** * @dev Burns dcdc token. This function should be used by custodians. * @param token_ address dcdc token_ that needs to be burnt. * @param src_ address the address from whom dcdc token will be burned. * @param amt_ uint amount to be burnt. */ function burnDcdc(address token_, address src_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || src_ == msg.sender, "asm-can-not-burn-from-src"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(src_, amt_); _updateDcdcV(token_, src_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(src_, _getCustodianCdcV(src_)); } /** * @dev Mint dpass tokens and update collateral values. * @param token_ address that is to be minted. Must be a dpass token address. * @param custodian_ address this must be the custodian that we mint the token for. Parameter necessary only for future compatibility. * @param issuer_ bytes3 the issuer of the certificate for diamond * @param report_ bytes16 the report number of the certificate of the diamond. * @param state_ bytes the state of token. Should be "sale" if it is to be sold on market, and "valid" if it is not to be sold. * @param cccc_ bytes20 cut, clarity, color, and carat (carat range) values of the diamond. Only a specific values of cccc_ is accepted. * @param carat_ uint24 exact weight of diamond in carats with 2 decimal precision. * @param attributesHash_ bytes32 the hash of ALL the attributes that are not stored on blockckhain to make sure no one can change them later on. * @param currentHashingAlgorithm_ bytes8 the algorithm that is used to construct attributesHash_. Together these values make meddling with diamond data very hard. * @param price_ uint256 the base price of diamond (not per carat price) */ function mintDpass( address token_, address custodian_, bytes3 issuer_, bytes16 report_, bytes8 state_, bytes20 cccc_, uint24 carat_, bytes32 attributesHash_, bytes8 currentHashingAlgorithm_, uint256 price_ ) public nonReentrant auth returns (uint256 id_) { require(dpasses[token_], "asm-mnt-not-a-dpass-token"); require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || custodian_ == msg.sender, "asm-mnt-no-mint-to-others"); id_ = Dpass(token_).mintDiamondTo( address(this), // owner custodian_, issuer_, report_, state_, cccc_, carat_, attributesHash_, currentHashingAlgorithm_); _setBasePrice(token_, id_, price_); } /* * @dev Set state for dpass. Should be used primarily by custodians. * @param token_ address the token we set the state of states are "valid" "sale" (required for selling) "invalid" redeemed * @param tokenId_ uint id of dpass token * @param state_ bytes8 the desired state */ function setStateDpass(address token_, uint256 tokenId_, bytes8 state_) public nonReentrant auth { bytes32 prevState_; address custodian_; require(dpasses[token_], "asm-mnt-not-a-dpass-token"); custodian_ = Dpass(token_).getCustodian(tokenId_); require( !custodians[msg.sender] || msg.sender == custodian_, "asm-ssd-not-authorized"); prevState_ = Dpass(token_).getState(tokenId_); if( prevState_ != "invalid" && prevState_ != "removed" && ( state_ == "invalid" || state_ == "removed" ) ) { _updateCollateralDpass(0, basePrice[token_][tokenId_], custodian_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(custodian_, _getCustodianCdcV(custodian_)); } else if( prevState_ == "redeemed" || prevState_ == "invalid" || prevState_ == "removed" || ( state_ != "invalid" && state_ != "removed" && state_ != "redeemed" ) ) { _updateCollateralDpass(basePrice[token_][tokenId_], 0, custodian_); } Dpass(token_).setState(state_, tokenId_); } /* * @dev Withdraw tokens for selling dpass, and cdc. Custodians do not receive money directly from selling dpass, ot cdc, but * they must withdraw their tokens. * @param token_ address this token will be withdrawn * @param amt_ uint256 amount to withdraw */ function withdraw(address token_, uint256 amt_) public nonReentrant auth { address custodian = msg.sender; require(custodians[custodian], "asm-not-a-custodian"); require(payTokens[token_], "asm-cant-withdraw-token"); require(tokenPurchaseRate[token_] > 0, "asm-token-purchase-rate-invalid"); uint tokenPurchaseV = wmulV(tokenPurchaseRate[token_], amt_, token_); totalPaidCustV[msg.sender] = add(totalPaidCustV[msg.sender], tokenPurchaseV); _requirePaidLessThanSold(custodian, _getCustodianCdcV(custodian)); sendToken(token_, address(this), msg.sender, amt_); } /* * @dev Return how much cdc token can be minted based on current collaterization. * @param token_ address cdc token that we want to find out how much is mintable. */ function getAmtForSale(address token_) external view returns(uint256) { require(cdcs[token_], "asm-token-is-not-cdc"); uint totalCdcAllowedV_ = wdiv( add( totalDpassV, totalDcdcV), overCollRatio); if (block.timestamp < add(totalCdcV, dust)) //injected CONTRACT AFFECTED BY MINERS return 0; return wdivT( sub( totalCdcAllowedV_, totalCdcV), _getNewRate(token_), token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base * token Value * @param a_ uint256 number that will be multiplied with decimals considered * @param b_ uint256 number that will be multiplied with decimals considered * @param token_ address token whose decimals the result will have */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with the result's decimals adjusted to match to token's precision * @param a_ uint256 number that will be numerator with decimals considered * @param b_ uint256 number that will be denominator with decimals considered * @param token_ address token whose decimals the result will have */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dpass tokens at custodian. * @param positiveV_ uint256 this value will be added to custodian's total dpass collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dpass collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDpass(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDpass(msg.sender, positiveV_, negativeV_, custodian_); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dcdc tokens of custodian. * @param positiveV_ uint256 this value will be added to custodian's total dcdc collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dcdc collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDcdc(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDcdc(msg.sender, positiveV_, negativeV_, custodian_); } /** * @dev Set base price_ for a diamond. Base price is the total price of diamonds. */ function _setBasePrice(address token_, uint256 tokenId_, uint256 price_) internal { bytes32 state_; address custodian_; require(dpasses[token_], "asm-invalid-token-address"); state_ = Dpass(token_).getState(tokenId_); custodian_ = Dpass(token_).getCustodian(tokenId_); require(!custodians[msg.sender] || msg.sender == custodian_, "asm-not-authorized"); if(Dpass(token_).ownerOf(tokenId_) == address(this) && (state_ == "valid" || state_ == "sale")) { _updateCollateralDpass(price_, basePrice[token_][tokenId_], custodian_); if(block.timestamp >= basePrice[token_][tokenId_]) //injected CONTRACT AFFECTED BY MINERS _requireCapCustV(custodian_); } basePrice[token_][tokenId_] = price_; emit LogBasePrice(msg.sender, token_, tokenId_, price_); } /* * @dev Default function for eth payment. We accept ether as payment. */ function () external payable { require(msg.value > 0, "asm-check-the-function-signature"); } /* * @dev Burn cdc tokens and update cdc variables. */ function _burn(address token_, uint256 amt_) internal { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, 0, amt_); } /** * @dev Get exchange rate for a token, and store it. */ function _updateRate(address token_) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token_)) > 0, "asm-updateRate-rate-gt-zero"); rate[token_] = rate_; } /* * @dev updates totalCdcPurchaseV and cdcPurchaseV when addAmt_ is added, or when subAmt_ is removed from cdc_. */ function _updateCdcPurchaseV(address cdc_, uint256 addAmt_, uint256 subAmt_) internal { uint currSupply_; uint prevPurchaseV_; if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS uint currentAddV_ = wmulV(addAmt_, _updateRate(cdc_), cdc_); cdcPurchaseV[cdc_] = add(cdcPurchaseV[cdc_], currentAddV_); totalCdcPurchaseV = add(totalCdcPurchaseV, currentAddV_); } else if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS currSupply_ = DSToken(cdc_).totalSupply(); prevPurchaseV_ = cdcPurchaseV[cdc_]; cdcPurchaseV[cdc_] = currSupply_ > dust ? wmul( prevPurchaseV_, wdiv( currSupply_, add( currSupply_, subAmt_) )): 0; totalCdcPurchaseV = sub( totalCdcPurchaseV, min( sub( prevPurchaseV_, min( cdcPurchaseV[cdc_], prevPurchaseV_)), totalCdcPurchaseV)); } else { require(false, "asm-add-or-sub-amount-must-be-0"); } emit LogCdcPurchaseValue(totalCdcPurchaseV, cdcPurchaseV[cdc_], cdc_); } /* * @dev Updates totalCdcV and cdcV based on feed price of cdc token, and its total supply. */ function _updateCdcV(address cdc_) internal { require(cdcs[cdc_], "asm-not-a-cdc-token"); uint newValue = wmulV(DSToken(cdc_).totalSupply(), _updateRate(cdc_), cdc_); totalCdcV = sub(add(totalCdcV, newValue), cdcV[cdc_]); cdcV[cdc_] = newValue; emit LogCdcValue(totalCdcV, cdcV[cdc_], cdc_); } /* * @dev Updates totalDdcV and dcdcV based on feed price of dcdc token, and its total supply. */ function _updateTotalDcdcV(address dcdc_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); uint newValue = wmulV(DSToken(dcdc_).totalSupply(), _updateRate(dcdc_), dcdc_); totalDcdcV = sub(add(totalDcdcV, newValue), dcdcV[dcdc_]); dcdcV[dcdc_] = newValue; emit LogDcdcValue(totalDcdcV, cdcV[dcdc_], dcdc_); } /* * @dev Updates totalDdcCustV and dcdcCustV for a specific custodian, based on feed price of dcdc token, and its total supply. */ function _updateDcdcV(address dcdc_, address custodian_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); require(custodians[custodian_], "asm-not-a-custodian"); uint newValue = wmulV(DSToken(dcdc_).balanceOf(custodian_), _updateRate(dcdc_), dcdc_); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], newValue), dcdcCustV[dcdc_][custodian_]); dcdcCustV[dcdc_][custodian_] = newValue; emit LogDcdcCustodianValue(totalDcdcCustV[custodian_], dcdcCustV[dcdc_][custodian_], dcdc_, custodian_); _updateTotalDcdcV(dcdc_); } /** * @dev Get token_ base currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) private view returns (uint rate_) { bool feedValid; bytes32 usdRateBytes; require( address(0) != priceFeed[token_], // require token to have a price feed "asm-no-price-feed"); (usdRateBytes, feedValid) = TrustedFeedLike(priceFeed[token_]).peek(); // receive DPT/USD price if (feedValid) { // if feed is valid, load DPT/USD rate from it rate_ = uint(usdRateBytes); } else { require(manualRate[token_], "Manual rate not allowed"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } /* * @dev Get the total value share of custodian from the total cdc minted. */ function _getCustodianCdcV(address custodian_) internal view returns(uint) { uint totalDpassAndDcdcV_ = add(totalDpassV, totalDcdcV); return wmul( totalCdcPurchaseV, totalDpassAndDcdcV_ > 0 ? wdiv( add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), totalDpassAndDcdcV_): 1 ether); } /** * @dev System must be overcollaterized at all time. When it is not, then no cdc can be minted. */ function _requireSystemCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRatio, totalCdcV) , "asm-system-undercollaterized"); } /** * @dev System must be overcollaterized at all time. When total cdc value times overCollRatio is not greater but * equal to total dpass value plus total dcdc value: no more cdc can be minted, but since overCollRemoveRatio is * less than overCollRatio, diamonds still can be removed by custodians. This is very helpful for them if system * is low on collateral. */ function _requireSystemRemoveCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRemoveRatio, totalCdcV) , "asm-sys-remove-undercollaterized"); } /** * @dev The total value paid to custodian (using withdraw()) must be less then the total value of current cdc * share, and dpass sold. */ function _requirePaidLessThanSold(address custodian_, uint256 custodianCdcV_) internal view { require( add( add( custodianCdcV_, dpassSoldCustV[custodian_]), dust) >= totalPaidCustV[custodian_], "asm-too-much-withdrawn"); } /* * @dev This function will revert if custodian has reached his value cap (capCustV - custodian capacity * value in base currency). Asset management enables to limit how much total worth * of diamonds each custodian can mint. This helps to avoid overexposure to some custodians, and avoid some * custodian fraud cases. */ function _requireCapCustV(address custodian_) internal view { if(block.timestamp != uint(-1)) //injected CONTRACT AFFECTED BY MINERS require( add(capCustV[custodian_], dust) >= add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), "asm-custodian-reached-maximum-coll-value"); } /* * @dev Updates total dpass value of a custodian, and the total dpass value. */ function _updateCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDpassCustV[custodian_] = sub( add( totalDpassCustV[custodian_], positiveV_), negativeV_); totalDpassV = sub( add( totalDpassV, positiveV_), negativeV_); emit LogDpassValue(totalDpassCustV[custodian_], totalDpassV, custodian_); } /** * @dev Updates total dcdc customer value and total dcdc value based on custodian collateral change. */ function _updateCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], positiveV_), negativeV_); totalDcdcV = sub( add( totalDcdcV, positiveV_), negativeV_); emit LogDcdcTotalCustodianValue(totalDcdcCustV[custodian_], totalDcdcV, custodian_); } /** * @dev Send token or ether to destination. */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.gaslimit > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Redeemer.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /* import "./SimpleAssetManagement.sol"; */ /* import "./DiamondExchange.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Liquidity.sol"; */ contract Redeemer is DSAuth, DSStop, DSMath { event LogRedeem(uint256 redeemId, address sender, address redeemToken_,uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian); address public eth = address(0xee); event LogTransferEth(address src, address dst, uint256 amount); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1, bytes32 value2); mapping(address => address) public dcdc; // dcdc[cdc] returns the dcdc token associated (having the same values) as cdc token uint256 public fixFee; // Fixed part of fee charged by Cdiamondcoin from redeemToken_ in base currency uint256 public varFee; // Variable part of fee charged by Cdiamondcoin from redeemToken_ address public dpt; // dpt token address SimpleAssetManagement public asm; // asset management contract DiamondExchange public dex; address payable public liq; // liquidity providing contract address bool public liqBuysDpt; // true if liquidity contract buys dpt on the fly, false otherwise address payable public burner; // burner contract to take dpt owners' profit address payable wal; // wallet to receive the operational costs uint public profitRate; // profit that is sent from fees to dpt owners bool locked; // variable to avoid reentrancy attacks against this contract uint redeemId; // id of the redeem transaction user can refer to uint dust = 1000; // dust value to handle round-off errors bytes32 public name = "Red"; // set human readable name for contract bytes32 public symbol = "Red"; // set human readable name for contract bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens modifier nonReentrant { require(!locked, "red-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck(address sender) { require(!kycEnabled || kyc[sender], "red-you-are-not-on-kyc-list"); _; } function () external payable { } function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-asm-address"); asm = SimpleAssetManagement(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "red-var-fee-too-high"); } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "red-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-red-address"); dex = DiamondExchange(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "red-profit-rate-out-of-range"); } else if (blockhash(block.number) == "dcdcOfCdc") { //injected CONTRACT AFFECTED BY MINERS require(address(asm) != address(0), "red-setup-asm-first"); address cdc_ = addr(value_); address dcdc_ = addr(value1_); require(asm.cdcs(cdc_), "red-setup-cdc-in-asm-first"); require(asm.dcdcs(dcdc_), "red-setup-dcdc-in-asm-first"); dcdc[cdc_] = dcdc_; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "red-wrong-address"); } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "red-wrong-address"); Liquidity(address(uint160(liq))).burn(dpt, address(uint160(burner)), 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "red-wrong-address"); require(dpt != address(0), "red-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "red-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); require(dust <= 1 ether, "red-pls-decrease-dust"); } else { require(false, "red-invalid-option"); } emit LogConfigChange(what_, value_, value1_, value2_); } /* * @dev Convert address to bytes32 */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /* * @dev Pay redeem costs and redeem for diamond. Using this funcitn is non-reversible. * @param sender_ address ethereum account of user who wants to redeem * @param redeemToken_ address token address that user wants to redeem token can be both * dpass and cdc tokens * @param redeemAmtOrId_ uint256 if token is cdc then represents amount, and if dpass then id of diamond * @param feeToken_ address token to pay fee with. This token can only be erc20. * @param feeAmt_ uint256 amount of token to be paid as redeem fee. * @param custodian_ address custodian to get diamond from. If token is dpass, then custodian must match * the custodian of dpass token id, if cdc then any custodian can be who has enough matching dcdc tokens. */ function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant kycCheck(sender) returns (uint256) { require(feeToken_ != eth || feeAmt_ == msg.value, "red-eth-not-equal-feeamt"); if( asm.dpasses(redeemToken_) ) { Dpass(redeemToken_).redeem(redeemAmtOrId_); require(custodian_ == address(uint160(Dpass(redeemToken_).getCustodian(redeemAmtOrId_))), "red-wrong-custodian-provided"); } else if ( asm.cdcs(redeemToken_) ) { require( DSToken(dcdc[redeemToken_]) .balanceOf(custodian_) > redeemAmtOrId_, "red-custodian-has-not-enough-cdc"); require(redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); DSToken(redeemToken_).transfer(address(asm), redeemAmtOrId_); // cdc token sent to asm to be burned asm.notifyTransferFrom( // burn cdc token at asm redeemToken_, address(this), address(asm), redeemAmtOrId_); } else { require(false, "red-token-nor-cdc-nor-dpass"); } uint feeToCustodian_ = _sendFeeToCdiamondCoin(redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_); _sendToken(feeToken_, address(this), custodian_, feeToCustodian_); emit LogRedeem(++redeemId, sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); return redeemId; } /** * @dev Put user on whitelist to redeem diamonds. * @param user_ address the ethereum account to enable * @param enable_ bool if true enables, otherwise disables user to use redeem */ function setKyc(address user_, bool enable_) public auth { setConfig( "kyc", bytes32(uint(user_)), enable_ ? bytes32(uint(1)) : bytes32(uint(0)), ""); } /** * @dev send token or ether to destination */ function _sendFeeToCdiamondCoin( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_ ) internal returns (uint feeToCustodianT_){ uint profitV_; uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); uint feeT_ = _getFeeT(feeToken_, redeemTokenV_); uint profitT_ = wmul(profitRate, feeT_); if( block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS DSToken(feeToken_).transfer(burner, profitT_); DSToken(feeToken_).transfer(wal, sub(feeT_, profitT_)); } else { profitV_ = dex.wmulV(profitT_, dex.getLocalRate(feeToken_), feeToken_); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); } else { DSToken(dpt).transferFrom( liq, burner, dex.wdivT(profitV_, dex.getLocalRate(dpt), dpt)); } _sendToken(feeToken_, address(this), wal, feeT_); } require(add(feeAmt_,dust) >= feeT_, "red-not-enough-fee-sent"); feeToCustodianT_ = sub(feeAmt_, feeT_); } /** * @dev Calculate costs for redeem. These are only concerning the fees the system charges. * Delivery costs charged by custodians are additional to these and must be added to the i * cost returned here. * @param redeemToken_ address token that will be redeemed. Cdc or dpass token address required. * @param redeemAmtOrId_ uint256 amount of token to be redeemed * @param feeToken_ address token that will be used to pay fee. * @return amount of fee token that must be sent as fee to system. Above this value users must * add the handling fee of custodians to have a successfull redeem. */ function getRedeemCosts(address redeemToken_, uint256 redeemAmtOrId_, address feeToken_) public view returns(uint feeT_) { require(asm.dpasses(redeemToken_) || redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); feeT_ = _getFeeT(feeToken_, redeemTokenV_); } /** * @dev Calculdate the base currency value of redeem token if it is an erc20 or if it is an erc721 token. */ function _calcRedeemTokenV(address redeemToken_, uint256 redeemAmtOrId_) internal view returns(uint redeemTokenV_) { if(asm.dpasses(redeemToken_)) { redeemTokenV_ = asm.basePrice(redeemToken_, redeemAmtOrId_); } else { redeemTokenV_ = dex.wmulV( redeemAmtOrId_, dex.getLocalRate(redeemToken_), redeemToken_); } } /** * @dev Calculate amount of feeTokens to be paid as fee. */ function _getFeeT(address feeToken_, uint256 redeemTokenV_) internal view returns (uint) { return dex.wdivT( add( wmul( varFee, redeemTokenV_), fixFee), dex.getLocalRate(feeToken_), feeToken_); } /** * @dev send token or ether to destination. */ function _sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.number > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/DiamondExchange.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "./Liquidity.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Redeemer.sol"; */ /** * @dev Interface to get ETH/USD price */ contract TrustedFeedLikeDex { function peek() external view returns (bytes32, bool); } /** * @dev Interface to calculate user fee based on amount */ contract TrustedFeeCalculator { function calculateFee( address sender, uint256 value, address sellToken, uint256 sellAmtOrId, address buyToken, uint256 buyAmtOrId ) external view returns (uint); function getCosts( address user, // user for whom we want to check the costs for address sellToken_, uint256 sellId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256 sellAmtOrId_, uint256 feeDpt_, uint256 feeV_, uint256 feeSellT_) { // calculate expected sell amount when user wants to buy something anc only knows how much he wants to buy from a token and whishes to know how much it will cost. } } /** * @dev Interface to do redeeming of tokens */ contract TrustedRedeemer { function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable returns (uint256); } /** * @dev Interface for managing diamond assets */ contract TrustedAsm { function notifyTransferFrom(address token, address src, address dst, uint256 id721) external; function basePrice(address erc721, uint256 id721) external view returns(uint256); function getAmtForSale(address token) external view returns(uint256); function mint(address token, address dst, uint256 amt) external; } /** * @dev Interface ERC721 contract */ contract TrustedErc721 { function transferFrom(address src, address to, uint256 amt) external; function ownerOf(uint256 tokenId) external view returns (address); } /** * @dev Interface for managing diamond assets */ contract TrustedDSToken { function transferFrom(address src, address dst, uint wad) external returns (bool); function totalSupply() external view returns (uint); function balanceOf(address src) external view returns (uint); function allowance(address src, address guy) external view returns (uint); } /** * @dev Diamond Exchange contract for events. */ contract DiamondExchangeEvents { event LogBuyTokenWithFee( uint256 indexed txId, address indexed sender, address custodian20, address sellToken, uint256 sellAmountT, address buyToken, uint256 buyAmountT, uint256 feeValue ); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 val); } /** * @title Diamond Exchange contract * @dev This contract can exchange ERC721 tokens and ERC20 tokens as well. Primary * usage is to buy diamonds or buying diamond backed stablecoins. */ contract DiamondExchange is DSAuth, DSStop, DiamondExchangeEvents { TrustedDSToken public cdc; // CDC token contract address public dpt; // DPT token contract mapping(address => uint256) private rate; // exchange rate for a token mapping(address => uint256) public smallest; // set minimum amount of sellAmtOrId_ mapping(address => bool) public manualRate; // manualRate is allowed for a token (if feed invalid) mapping(address => TrustedFeedLikeDex) public priceFeed; // price feed address for token mapping(address => bool) public canBuyErc20; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc20; // stores allowed ERC20 tokens to sell mapping(address => bool) public canBuyErc721; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc721; // stores allowed ERC20 tokens to sell mapping(address => mapping(address => bool)) // stores tokens that seller does not accept, ... public denyToken; // ... and also token pairs that can not be traded mapping(address => uint) public decimals; // stores decimals for each ERC20 token mapping(address => bool) public decimalsSet; // stores if decimals were set for ERC20 token mapping(address => address payable) public custodian20; // custodian that holds an ERC20 token for Exchange mapping(address => bool) public handledByAsm; // defines if token is managed by Asset Management mapping( address => mapping( address => mapping( uint => uint))) public buyPrice; // buyPrice[token][owner][tokenId] price of dpass token ... // ... defined by owner of dpass token mapping(address => bool) redeemFeeToken; // tokens allowed to pay redeem fee with TrustedFeeCalculator public fca; // fee calculator contract address payable public liq; // contract providing DPT liquidity to pay for fee address payable public wal; // wallet address, where we keep all the tokens we received as fee address public burner; // contract where accured fee of DPT is stored before being burned TrustedAsm public asm; // Asset Management contract uint256 public fixFee; // Fixed part of fee charged for buying 18 decimals precision in base currency uint256 public varFee; // Variable part of fee charged for buying 18 decimals precision in base currency uint256 public profitRate; // the percentage of profit that is burned on all fees received. ... // ... 18 decimals precision uint256 public callGas = 2500; // using this much gas when Ether is transferred uint256 public txId; // Unique id of each transaction. bool public takeProfitOnlyInDpt = true; // If true, it takes cost + profit in DPT, if false only profit in DPT uint256 public dust = 10000; // Numbers below this amount are considered 0. Can only be used ... bytes32 public name = "Dex"; // set human readable name for contract bytes32 public symbol = "Dex"; // set human readable name for contract // ... along with 18 decimal precisions numbers. bool liqBuysDpt; // if true then liq contract is called directly to buy necessary dpt, otherwise we... // ... just send DPT from liq contracts address to burner. bool locked; // protect against reentrancy attacks address eth = address(0xee); // to handle ether the same way as tokens we associate a fake address to it bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens address payable public redeemer; // redeemer contract to handle physical diamond delivery to users //-----------included-from-ds-math---------------------------------begin uint constant WAD = 1 ether; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end modifier nonReentrant { require(!locked, "dex-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck { require(!kycEnabled || kyc[msg.sender], "dex-you-are-not-on-kyc-list"); _; } /** * @dev Fallback function to buy tokens. */ function () external payable { buyTokensWithFee(eth, msg.value, address(cdc), uint(-1)); } /** * @dev Set configuration values for contract. Instead of several small functions * that bloat the abi, this monolitic function can be used to configure Diamond i * Exchange contract. * @param what_ bytes32 determines what change the owner(contract) wants to make. * @param value_ bytes32 depending on what_ can be used to configure the system * @param value1_ bytes32 depending on what_ can be used to configure the system */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_) public auth { if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "dex-profit-rate-out-of-range"); } else if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-rate"); require(value > 0, "dex-rate-must-be-greater-than-0"); rate[token] = value; } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "dex-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "allowTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = false; } else if (blockhash(block.number) == "denyTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = true; } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "dex-var-fee-too-high"); } else if (blockhash(block.number) == "redeemFeeToken") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "dex-zero-address-redeemfee-token"); redeemFeeToken[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-manualrate"); manualRate[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(canSellErc20[addr(value_)] || canBuyErc20[addr(value_)], "dex-token-not-allowed-pricefeed"); require(addr(value1_) != address(address(0x0)), "dex-wrong-pricefeed-address"); priceFeed[addr(value_)] = TrustedFeedLikeDex(addr(value1_)); } else if (blockhash(block.number) == "takeProfitOnlyInDpt") { //injected CONTRACT AFFECTED BY MINERS takeProfitOnlyInDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "dex-wrong-address"); Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "dex-wrong-address"); require(dpt != address(0), "dex-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "dex-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "handledByAsm") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(canBuyErc20[token] || canBuyErc721[token], "dex-token-not-allowed-handledbyasm"); handledByAsm[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); asm = TrustedAsm(addr(value_)); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "cdc") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); cdc = TrustedDSToken(addr(value_)); } else if (blockhash(block.number) == "fca") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); fca = TrustedFeeCalculator(addr(value_)); } else if (blockhash(block.number) == "custodian20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); custodian20[addr(value_)] = address(uint160(addr(value1_))); } else if (blockhash(block.number) == "smallest") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-small"); smallest[token] = value; } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token_ = addr(value_); require(token_ != address(0x0), "dex-wrong-address"); uint decimal = uint256(value1_); decimals[token_] = 10 ** decimal; decimalsSet[token_] = true; } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "callGas") { //injected CONTRACT AFFECTED BY MINERS callGas = uint256(value_); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "canBuyErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-buytoken-decimals-not-set"); canBuyErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-selltoken-decimals-not-set"); canSellErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canBuyErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canBuyErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canSellErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "dex-wrong-address"); require(decimalsSet[dpt], "dex-dpt-decimals-not-set"); } else if (blockhash(block.number) == "redeemer") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-redeemer-address"); redeemer = address(uint160(addr(value_))); } else { value1_; require(false, "dex-no-such-option"); } emit LogConfigChange(what_, value_, value1_); } /** * @dev Redeem token and pay fee for redeem. * @param redeemToken_ address this is the token address user wants to redeem * @param redeemAmtOrId_ uint256 if redeemToken_ is erc20 token this is the amount to redeem, if erc721 then this is the id * @param feeToken_ address the token user wants to pay for redeem fee with * @param feeAmt_ address amount user pays for redeem (note there is no function to cancel this redeem) * @param custodian_ address the custodians address that user wants to get his diamonds from (if redeemToken_ is dpass, user must set the custodian of the token here) */ function redeem( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant returns(uint redeemId) { // kyc check will thake place on redeem contract. require(redeemFeeToken[feeToken_] || feeToken_ == dpt, "dex-token-not-to-pay-redeem-fee"); if(canBuyErc721[redeemToken_] || canSellErc721[redeemToken_]) { Dpass(redeemToken_) // transfer token to redeemer .transferFrom( msg.sender, redeemer, redeemAmtOrId_); } else if (canBuyErc20[redeemToken_] || canSellErc20[redeemToken_]) { _sendToken(redeemToken_, msg.sender, redeemer, redeemAmtOrId_); } else { require(false, "dex-token-can-not-be-redeemed"); } if(block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return TrustedRedeemer(redeemer) .redeem .value(msg.value) (msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } else { _sendToken(feeToken_, msg.sender, redeemer, feeAmt_); return TrustedRedeemer(redeemer) .redeem(msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } } /** * @dev 1oken purchase with fee. (If user has DPT he must approve this contract, * otherwise transaction will fail.) * @param sellToken_ address token user wants to sell * @param sellAmtOrId_ uint256 if sellToken_ is erc20 token then this is the amount (if set to highest possible, it means user wants to exchange all necessary tokens in his posession to buy the buyToken_), if token is Dpass(erc721) token, then this is the tokenId * @param buyToken_ address token user wants to buy * @param buyAmtOrId_ uint256 if buyToken_ is erc20, then this is the amount(setting highest integer will make buy as much buyTokens: as possible), and it is tokenId otherwise */ function buyTokensWithFee ( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public payable stoppable nonReentrant kycCheck { uint buyV_; uint sellV_; uint feeV_; uint sellT_; uint buyT_; require(!denyToken[sellToken_][buyToken_], "dex-cant-use-this-token-to-buy"); require(smallest[sellToken_] <= sellAmtOrId_, "dex-trade-value-too-small"); _updateRates(sellToken_, buyToken_); // update currency rates (buyV_, sellV_) = _getValues( // calculate highest possible buy and sell values (here they might not match) sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); feeV_ = calculateFee( // calculate fee user has to pay for exchange msg.sender, min(buyV_, sellV_), sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); (sellT_, buyT_) = _takeFee( // takes the calculated fee from user in DPT or sellToken_ ... feeV_, // ... calculates final sell and buy values (in base currency) sellV_, buyV_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); _transferTokens( // transfers tokens to user and seller sellT_, buyT_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_, feeV_); } /** * @dev Get sell and buy token values in base currency */ function _getValues( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns (uint256 buyV, uint256 sellV) { uint sellAmtT_ = sellAmtOrId_; uint buyAmtT_ = buyAmtOrId_; uint maxT_; require(buyToken_ != eth, "dex-we-do-not-sell-ether"); // we can not sell Ether with this smart contract currently require(sellToken_ == eth || msg.value == 0, // we don't accept ETH if user wants to sell other token "dex-do-not-send-ether"); if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token maxT_ = sellToken_ == eth ? msg.value : min( TrustedDSToken(sellToken_).balanceOf(msg.sender), TrustedDSToken(sellToken_).allowance( msg.sender, address(this))); require(maxT_ > 0, "dex-please-approve-us"); require( sellToken_ == eth || // disregard Ether sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= maxT_, // sellAmtOrId_ should be less then sellToken_ available to this contract "dex-sell-amount-exceeds-allowance"); require( sellToken_ != eth || // regard Ether only sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= msg.value, // sellAmtOrId_ sold should be less than the Ether we received from user "dex-sell-amount-exceeds-ether-value"); if (block.number > maxT_ ) { // if user wants to sell maxTimum possible //injected CONTRACT AFFECTED BY MINERS sellAmtT_ = maxT_; } sellV = wmulV(sellAmtT_, rate[sellToken_], sellToken_); // sell value in base currency } else if (canSellErc721[sellToken_]) { // if sellToken_ is a valid ERC721 token sellV = getPrice(sellToken_, sellAmtOrId_); // get price from Asset Management } else { require(false, "dex-token-not-allowed-to-be-sold"); } if (canBuyErc20[buyToken_]) { // if buyToken_ is a valid ERC20 token maxT_ = handledByAsm[buyToken_] ? // set buy amount to maxT_ possible asm.getAmtForSale(buyToken_) : // if managed by asset management get available min( // if not managed by asset management get maxT_ available TrustedDSToken(buyToken_).balanceOf( custodian20[buyToken_]), TrustedDSToken(buyToken_).allowance( custodian20[buyToken_], address(this))); require(maxT_ > 0, "dex-0-token-is-for-sale"); require( // require token's buy amount to be less or equal than available to us buyToken_ == eth || // disregard Ether buyAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning buyAmtOrId_ <= maxT_, // amount must be less or equal that maxT_ available "dex-buy-amount-exceeds-allowance"); if (block.number > maxT_) { // user wants to buy the maxTimum possible //injected CONTRACT AFFECTED BY MINERS buyAmtT_ = maxT_; } buyV = wmulV(buyAmtT_, rate[buyToken_], buyToken_); // final buy value in base currency } else if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token require(canSellErc20[sellToken_], // require that at least one of sell and buy token is ERC20 "dex-one-of-tokens-must-be-erc20"); buyV = getPrice( // calculate price with Asset Management contract buyToken_, buyAmtOrId_); } else { require(false, "dex-token-not-allowed-to-be-bought"); // token can not be bought here } } /** * @dev Calculate fee locally or using an external smart contract * @return the fee amount in base currency * @param sender_ address user we want to get the fee for * @param value_ uint256 base currency value of transaction for which the fee will be derermined * @param sellToken_ address token to be sold by user * @param sellAmtOrId_ uint256 amount or id of token * @param buyToken_ address token to be bought by user * @param buyAmtOrId_ uint256 amount or id of buytoken */ function calculateFee( address sender_, uint256 value_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256) { if (fca == TrustedFeeCalculator(0)) { return add(fixFee, wmul(varFee, value_)); // calculate proportional fee locally } else { return fca.calculateFee( // calculate fee using external smart contract sender_, value_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); } } /** * @dev Taking feeV_ from user. If user has DPT takes it, if there is none buys it for user. * @return the amount of remaining ETH after buying feeV_ if it was required */ function _takeFee( uint256 feeV_, uint256 sellV_, uint256 buyV_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns(uint256 sellT, uint256 buyT) { uint feeTakenV_; uint amtT_; address token_; address src_; uint restFeeV_; feeTakenV_ = sellToken_ != dpt ? // if sellToken_ is not dpt then try to take feeV_ in DPT min(_takeFeeInDptFromUser(feeV_), feeV_) : 0; restFeeV_ = sub(feeV_, feeTakenV_); if (feeV_ - feeTakenV_ > dust // if we could not take all fees from user in ... && feeV_ - feeTakenV_ <= feeV_) { // ... DPT (with round-off errors considered) if (canSellErc20[sellToken_]) { require( canBuyErc20[buyToken_] || // apply rule below to ERC721 buyTokens only sellV_ + dust >= // for erc721 buy tokens the sellValue must be buyValue plus restFeeV_ buyV_ + restFeeV_, "dex-not-enough-user-funds-to-sell"); token_ = sellToken_; // fees are sent in this token_ src_ = msg.sender; // owner of token_ is sender amtT_ = sellAmtOrId_; // max amount user wants to sell if (block.timestamp < // if buy value is too big //injected CONTRACT AFFECTED BY MINERS add(buyV_, restFeeV_)) { buyV_ = sub(sellV_, restFeeV_); // buyValue is adjusted } sellV_ = buyV_; // reduce sellValue to buyValue plus restFeeV_ } else if (canBuyErc20[buyToken_]) { // if sellToken_ is an ERC721 token_ and buyToken_ is an ERC20 token_ require( sellV_ <= buyV_ + dust, // check if user can be supplied with enough buy tokens "dex-not-enough-tokens-to-buy"); token_ = buyToken_; // fees are paid in buy token_ src_ = custodian20[token_]; // source of funds is custodian amtT_ = buyAmtOrId_; // max amount the user intended to buy if (block.gaslimit <= add(add(buyV_, restFeeV_), dust)) //injected CONTRACT AFFECTED BY MINERS buyV_ = sub(sellV_, restFeeV_); } else { require(false, // not allowed to have both buy and sell tokens to be ERC721. ... "dex-no-token-to-get-fee-from"); // ... We should never end up here since dex-one-of-tokens-must-be-erc20 ... // ... will be fired first. It is here for precaution. } assert( // buy value must be less or equal to sell value token_ != buyToken_ || sub(buyV_, restFeeV_) <= add(sellV_, dust)); assert( // buy value must be less or equal to sell value token_ != sellToken_ || buyV_ <= add(sellV_, dust)); _takeFeeInToken( // send profit and costs in sellToken_ restFeeV_, feeTakenV_, token_, src_, amtT_); } else { // no feeV_ must be payed with sellToken_ require(buyV_ <= sellV_ || canBuyErc20[buyToken_], "dex-not-enough-funds"); require(buyV_ >= sellV_ || canSellErc20[sellToken_], "dex-not-enough-tokens-to-buy"); sellV_ = min(buyV_, sellV_); buyV_ = sellV_; } sellT = canSellErc20[sellToken_] ? // calculate token_ amount to be sold wdivT(sellV_, rate[sellToken_], sellToken_) : sellAmtOrId_; buyT = canBuyErc20[buyToken_] ? wdivT(buyV_, rate[buyToken_], buyToken_) : buyAmtOrId_; if (block.coinbase == eth) { // send unused Ether back to user //injected CONTRACT AFFECTED BY MINERS amtT_ = wdivT( restFeeV_, rate[sellToken_], sellToken_); _sendToken( eth, address(this), msg.sender, sub(msg.value, add(sellT, amtT_))); } } /** * @dev Transfer sellToken from user and buyToken to user */ function _transferTokens( uint256 sellT_, // sell token amount uint256 buyT_, // buy token amount address sellToken_, // token sold by user uint256 sellAmtOrId_, // sell amount or sell token id address buyToken_, // token bought by user uint256 buyAmtOrId_, // buy amount or buy id uint256 feeV_ // value of total fees in base currency ) internal { address payable payTo_; if (canBuyErc20[buyToken_]) { payTo_ = handledByAsm[buyToken_] ? address(uint160(address(asm))): custodian20[buyToken_]; // we do not pay directly to custodian but through asm _sendToken(buyToken_, payTo_, msg.sender, buyT_); // send buyToken_ from custodian to user } if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token payTo_ = address(uint160(address( // we pay to owner Dpass(buyToken_).ownerOf(buyAmtOrId_)))); asm.notifyTransferFrom( // notify Asset management about the transfer buyToken_, payTo_, msg.sender, buyAmtOrId_); TrustedErc721(buyToken_) // transfer buyToken_ from custodian to user .transferFrom( payTo_, msg.sender, buyAmtOrId_); } _sendToken(sellToken_, msg.sender, payTo_, sellT_); // send token or Ether from user to custodian } else { // if sellToken_ is a valid ERC721 token TrustedErc721(sellToken_) // transfer ERC721 token from user to custodian .transferFrom( msg.sender, payTo_, sellAmtOrId_); sellT_ = sellAmtOrId_; } require(!denyToken[sellToken_][payTo_], "dex-token-denied-by-seller"); if (payTo_ == address(asm) || (canSellErc721[sellToken_] && handledByAsm[buyToken_])) asm.notifyTransferFrom( // notify Asset Management contract about transfer sellToken_, msg.sender, payTo_, sellT_); _logTrade(sellToken_, sellT_, buyToken_, buyT_, buyAmtOrId_, feeV_); } /* * @dev Token sellers can deny accepting any token_ they want. * @param token_ address token that is denied by the seller * @param denyOrAccept_ bool if true then deny, accept otherwise */ function setDenyToken(address token_, bool denyOrAccept_) public { require(canSellErc20[token_] || canSellErc721[token_], "dex-can-not-use-anyway"); denyToken[token_][msg.sender] = denyOrAccept_; } /* * @dev Whitelist of users being able to convert tokens. * @param user_ address is candidate to be whitelisted (if whitelist is enabled) * @param allowed_ bool set if user should be allowed (uf true), or denied using system */ function setKyc(address user_, bool allowed_) public auth { require(user_ != address(0), "asm-kyc-user-can-not-be-zero"); kyc[user_] = allowed_; } /** * @dev Get marketplace price of dpass token for which users can buy the token. * @param token_ address token to get the buyPrice for. * @param tokenId_ uint256 token id to get buy price for. */ function getBuyPrice(address token_, uint256 tokenId_) public view returns(uint256) { // require(canBuyErc721[token_], "dex-token-not-for-sale"); return buyPrice[token_][TrustedErc721(token_).ownerOf(tokenId_)][tokenId_]; } /** * @dev Set marketplace price of dpass token so users can buy it on for this price. * @param token_ address price is set for this token. * @param tokenId_ uint256 tokenid to set price for * @param price_ uint256 marketplace price to set */ function setBuyPrice(address token_, uint256 tokenId_, uint256 price_) public { address seller_ = msg.sender; require(canBuyErc721[token_], "dex-token-not-for-sale"); if ( msg.sender == Dpass(token_).getCustodian(tokenId_) && address(asm) == Dpass(token_).ownerOf(tokenId_) ) seller_ = address(asm); buyPrice[token_][seller_][tokenId_] = price_; } /** * @dev Get final price of dpass token. Function tries to get rpce from marketplace * price (buyPrice) and if that is zero, then from basePrice. * @param token_ address token to get price for * @param tokenId_ uint256 to get price for * @return final sell price that user must pay */ function getPrice(address token_, uint256 tokenId_) public view returns(uint256) { uint basePrice_; address owner_ = TrustedErc721(token_).ownerOf(tokenId_); uint buyPrice_ = buyPrice[token_][owner_][tokenId_]; require(canBuyErc721[token_], "dex-token-not-for-sale"); if( buyPrice_ == 0 || buyPrice_ == uint(-1)) { basePrice_ = asm.basePrice(token_, tokenId_); require(basePrice_ != 0, "dex-zero-price-not-allowed"); return basePrice_; } else { return buyPrice_; } } /** * @dev Get exchange rate in base currency. This function burns small amount of gas, because it returns the locally stored exchange rate for token_. It should only be used if user is sure that the rate was recently updated. * @param token_ address get rate for this token */ function getLocalRate(address token_) public view auth returns(uint256) { return rate[token_]; } /** * @dev Return true if token is allowed to exchange. * @param token_ the token_ addres in question * @param buy_ if true we ask if user can buy_ the token_ from exchange, * otherwise if user can sell to exchange. */ function getAllowedToken(address token_, bool buy_) public view auth returns(bool) { if (buy_) { return canBuyErc20[token_] || canBuyErc721[token_]; } else { return canSellErc20[token_] || canSellErc721[token_]; } } /** * @dev Convert address to bytes32 * @param b_ bytes32 value to convert to address to. */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Retrieve the decimals of a token. Decimals are stored in a special way internally to apply the least calculations to get precision adjusted results. * @param token_ address the decimals are calculated for this token */ function getDecimals(address token_) public view returns (uint8) { require(decimalsSet[token_], "dex-token-with-unset-decimals"); uint dec = 0; while(dec <= 77 && decimals[token_] % uint(10) ** dec == 0){ dec++; } dec--; return uint8(dec); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed * @param token_ address get rate for this token */ function getRate(address token_) public view auth returns (uint) { return _getNewRate(token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base token value. * @param a_ uint256 multiply this number * @param b_ uint256 multiply this number * @param token_ address get results with the precision of this token */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with decimals adjusted to match to tokens precision * @param a_ uint256 divide this number * @param b_ uint256 divide by this number * @param token_ address get result with the precision of this token */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) internal view returns (uint rate_) { bool feedValid_; bytes32 baseRateBytes_; require( TrustedFeedLikeDex(address(0x0)) != priceFeed[token_], // require token to have a price feed "dex-no-price-feed-for-token"); (baseRateBytes_, feedValid_) = priceFeed[token_].peek(); // receive DPT/USD price if (feedValid_) { // if feed is valid, load DPT/USD rate from it rate_ = uint(baseRateBytes_); } else { require(manualRate[token_], "dex-feed-provides-invalid-data"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } // // internal functions // /* * @dev updates locally stored rates of tokens from feeds */ function _updateRates(address sellToken_, address buyToken_) internal { if (canSellErc20[sellToken_]) { _updateRate(sellToken_); } if (canBuyErc20[buyToken_]){ _updateRate(buyToken_); } _updateRate(dpt); } /* * @dev log the trade event */ function _logTrade( address sellToken_, uint256 sellT_, address buyToken_, uint256 buyT_, uint256 buyAmtOrId_, uint256 feeV_ ) internal { address custodian_ = canBuyErc20[buyToken_] ? custodian20[buyToken_] : Dpass(buyToken_).getCustodian(buyAmtOrId_); txId++; emit LogBuyTokenWithFee( txId, msg.sender, custodian_, sellToken_, sellT_, buyToken_, buyT_, feeV_); } /** * @dev Get exchange rate for a token */ function _updateRate(address token) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token)) > 0, "dex-rate-must-be-greater-than-0"); rate[token] = rate_; } /** * @dev Calculate and send profit and cost */ function _takeFeeInToken( uint256 feeV_, // feeV_ that user still owes to CDiamondCoin after paying feeV_ in DPT uint256 feeTakenV_, // feeV_ already taken from user in DPT address token_, // token_ that must be sent as feeV_ address src_, // source of token_ sent uint256 amountT_ // total amount of tokens the user wanted to pay initially ) internal { uint profitV_; uint profitDpt_; uint feeT_; uint profitPaidV_; uint totalProfitV_; totalProfitV_ = wmul(add(feeV_, feeTakenV_), profitRate); profitPaidV_ = takeProfitOnlyInDpt ? // profit value paid already in base currency feeTakenV_ : wmul(feeTakenV_, profitRate); profitV_ = sub( // profit value still to be paid in base currency totalProfitV_, min( profitPaidV_, totalProfitV_)); profitDpt_ = wdivT(profitV_, rate[dpt], dpt); // profit in DPT still to be paid feeT_ = wdivT(feeV_, rate[token_], token_); // convert feeV_ from base currency to token amount require( feeT_ < amountT_, // require that the cost we pay is less than user intended to pay "dex-not-enough-token-to-pay-fee"); if (block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS _sendToken(dpt, src_, address(uint160(address(burner))), profitDpt_); _sendToken(dpt, src_, wal, sub(feeT_, profitDpt_)); } else { if (liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); // if liq contract buys DPT on the fly } else { _sendToken(dpt, // if liq contract stores DPT that can be sent to burner by us liq, address(uint160(address(burner))), profitDpt_); } _sendToken(token_, src_, wal, feeT_); // send user token_ to wallet } } /** * @dev Take fee in DPT from user if it has any * @param feeV_ the fee amount in base currency * @return the remaining fee amount in DPT */ function _takeFeeInDptFromUser( uint256 feeV_ // total feeV_ to be paid ) internal returns(uint256 feeTakenV_) { TrustedDSToken dpt20_ = TrustedDSToken(dpt); uint profitDpt_; uint costDpt_; uint feeTakenDpt_; uint dptUser = min( dpt20_.balanceOf(msg.sender), dpt20_.allowance(msg.sender, address(this)) ); if (block.gaslimit == 0) return 0; //injected CONTRACT AFFECTED BY MINERS uint feeDpt = wdivT(feeV_, rate[dpt], dpt); // feeV_ in DPT uint minDpt = min(feeDpt, dptUser); // get the maximum possible feeV_ amount if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS if (takeProfitOnlyInDpt) { // only profit is paid in dpt profitDpt_ = min(wmul(feeDpt, profitRate), minDpt); } else { profitDpt_ = wmul(minDpt, profitRate); costDpt_ = sub(minDpt, profitDpt_); _sendToken(dpt, msg.sender, wal, costDpt_); // send cost } _sendToken(dpt, // send profit to burner msg.sender, address(uint160(address(burner))), profitDpt_); feeTakenDpt_ = add(profitDpt_, costDpt_); // total feeV_ taken in DPT feeTakenV_ = wmulV(feeTakenDpt_, rate[dpt], dpt); // total feeV_ taken in base currency value } } /** * @dev send token or ether to destination */ function _sendToken( address token_, address src_, address payable dst_, uint256 amount_ ) internal returns(bool) { if (token_ == eth && amount_ > dust) { // if token_ is Ether and amount_ is higher than dust limit require(src_ == msg.sender || src_ == address(this), "dex-wrong-src-address-provided"); dst_.transfer(amount_); emit LogTransferEth(src_, dst_, amount_); } else { if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS if( handledByAsm[token_] && src_ == address(asm)) { // if token_ is handled by asm (so it is minted and burnt) and we have to mint it asm.mint(token_, dst_, amount_); } else { TrustedDSToken(token_).transferFrom(src_, dst_, amount_); // transfer all of token_ to dst_ } } } return true; } }
fee calculator contract
TrustedFeeCalculator public fca;
13,091,009
[ 1, 21386, 15497, 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, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 30645, 14667, 19278, 1071, 284, 5353, 31, 7682, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./ERC20.sol"; import "./ERC918.sol"; import "./Owned.sol"; import "./ApproveAndCallFallBack.sol"; // ---------------------------------------------------------------------------- // 'Spring Token' contract // ERC20 & ERC918 Mineable Token using Proof Of Work // Symbol : SPRING // Name : Spring Token // Total supply: 33,112,800.00 // Decimals : 18 // Initial mining reward: 168 // Fraction of total supply released before first halving: 1/5 // ---------------------------------------------------------------------------- contract SpringToken is ERC20Interface, ERC918, Owned { string private constant SYMBOL = "SPRING"; string private constant NAME = "Spring Token"; uint256 public constant TOKEN_IDENTIFIER = 1; uint8 public constant DECIMALS = 18; uint256 public constant TOTAL_SUPPLY = 33112800 * 10**18; uint256 public constant INITIAL_REWARD = 168 * 10**18; uint256 public constant MAX_REWARDS_AVAILABLE = 72; // no more than 72 rewards per mint uint256 public constant REWARD_INTERVAL = 600; // rewards every ten minutes on average uint256 public constant DURATION_OF_FIRST_ERA = (365 * 24 * 60 * 60 * 3) / 4; // 9 months uint256 public constant DURATION_OF_ERA = 3 * 365 * 24 * 60 * 60; // three years uint256 public constant MINIMUM_TARGET = 2**16; uint256 public constant MAXIMUM_TARGET = 2**234; uint256 public immutable contractCreationTime; uint256 public lastRewardBlockTime; uint256 public maxNumberOfRewardsPerMint; bytes32 private challengeNumber; uint256 private miningTarget; uint256 public tokensMinted; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; constructor() { miningTarget = MAXIMUM_TARGET / 2**19; contractCreationTime = block.timestamp; lastRewardBlockTime = block.timestamp; maxNumberOfRewardsPerMint = 1; challengeNumber = _getNewChallengeNumber(0); } function name() public pure returns (string memory) { return NAME; } function symbol() public pure returns (string memory) { return SYMBOL; } function mint(uint256 nonce) override public returns (bool success) { uint256 _lastRewardBlockTime = lastRewardBlockTime; uint256 singleRewardAmount = _getMiningReward(_lastRewardBlockTime); // no more minting when reward reaches zero if (singleRewardAmount == 0) revert("Reward has reached zero"); // the PoW must contain work that includes the challenge number and the msg.sender's address bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce)); uint256 _miningTarget = miningTarget; // the digest must be smaller than the target if (uint256(digest) > _miningTarget) revert("Digest is larger than mining target"); uint256 _previousMaxNumberOfRewards = maxNumberOfRewardsPerMint; uint256 numberOfRewardsToGive = _numberOfRewardsToGive(_miningTarget / uint256(digest), _lastRewardBlockTime, _previousMaxNumberOfRewards, block.timestamp); uint256 totalRewardAmount = singleRewardAmount * numberOfRewardsToGive; uint256 _tokensMinted = _giveRewards(totalRewardAmount); _setNextMaxNumberOfRewards(numberOfRewardsToGive, _previousMaxNumberOfRewards); miningTarget = _adjustDifficulty(_miningTarget, _lastRewardBlockTime, numberOfRewardsToGive, block.timestamp); bytes32 newChallengeNumber = _getNewChallengeNumber(_tokensMinted); challengeNumber = newChallengeNumber; lastRewardBlockTime = block.timestamp; emit Mint(msg.sender, totalRewardAmount, _scheduledNumberOfRewards(block.timestamp), newChallengeNumber); return true; } function _numberOfRewardsAvailable(uint256 _lastRewardBlockTime, uint256 _previousMaxNumberOfRewards, uint256 currentTime) internal pure returns (uint256) { uint256 numberAvailable = _previousMaxNumberOfRewards; uint256 intervalsSinceLastReward = (currentTime - _lastRewardBlockTime) / REWARD_INTERVAL; if (intervalsSinceLastReward > numberAvailable) numberAvailable = intervalsSinceLastReward; if (numberAvailable > MAX_REWARDS_AVAILABLE) numberAvailable = MAX_REWARDS_AVAILABLE; return numberAvailable; } function _numberOfRewardsToGive(uint256 numberEarned, uint256 _lastRewardBlockTime, uint256 _previousMaxNumberOfRewards, uint256 currentTime) internal pure returns (uint256) { uint256 numberAvailable = _numberOfRewardsAvailable(_lastRewardBlockTime, _previousMaxNumberOfRewards, currentTime); if (numberEarned < numberAvailable) return numberEarned; return numberAvailable; } function _giveRewards(uint256 totalReward) internal returns (uint256) { balances[msg.sender] += totalReward; uint256 _tokensMinted = tokensMinted + totalReward; tokensMinted = _tokensMinted; return _tokensMinted; } function _setNextMaxNumberOfRewards(uint256 numberOfRewardsGivenNow, uint256 _previousMaxNumberOfRewards) internal { // the value of the rewards given to this miner presumably exceed the gas costs // for processing the transaction. the next miner can submit a proof of enough work // to claim up to the same number of rewards immediately, or, if gas costs have increased, // wait until the maximum number of rewards claimable has increased enough to overcome // the costs. if (numberOfRewardsGivenNow != _previousMaxNumberOfRewards) maxNumberOfRewardsPerMint = numberOfRewardsGivenNow; } // backwards compatible mint function function mint(uint256 _nonce, bytes32 _challengeDigest) external returns (bool) { bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, _nonce)); require(digest == _challengeDigest, "Challenge digest does not match expected digest on token contract"); return mint(_nonce); } function _getNewChallengeNumber(uint256 _tokensMinted) internal view returns (bytes32) { // make the latest ethereum block hash a part of the next challenge // xor with a number unique to this token to avoid merged mining // xor with the number of tokens minted to ensure that the challenge changes // even if there are multiple mints in the same ethereum block return bytes32(uint256(blockhash(block.number - 1)) ^ _tokensMinted ^ TOKEN_IDENTIFIER); } function _scheduledNumberOfRewards(uint256 currentTime) internal view returns (uint256) { return (currentTime - contractCreationTime) / REWARD_INTERVAL; } function _adjustDifficulty(uint256 _miningTarget, uint256 _lastRewardBlockTime, uint256 rewardsGivenNow, uint256 currentTime) internal pure returns (uint256){ uint256 timeSinceLastReward = currentTime - _lastRewardBlockTime; // we target a median interval of 10 minutes multiplied by log(2) ~ 61/88 // this gives a mean interval of 10 minutes per reward if (timeSinceLastReward * 88 < rewardsGivenNow * REWARD_INTERVAL * 61) _miningTarget = (_miningTarget * 99) / 100; // slow down else _miningTarget = (_miningTarget * 100) / 99; // speed up if (_miningTarget < MINIMUM_TARGET) _miningTarget = MINIMUM_TARGET; if (_miningTarget > MAXIMUM_TARGET) _miningTarget = MAXIMUM_TARGET; return _miningTarget; } function rewardEra(uint256 _time) public view returns (uint256) { uint256 timeSinceContractCreation = _time - contractCreationTime; if (timeSinceContractCreation < DURATION_OF_FIRST_ERA) return 0; else return 1 + (timeSinceContractCreation - DURATION_OF_FIRST_ERA) / DURATION_OF_ERA; } function getAdjustmentInterval() public view override returns (uint256) { return REWARD_INTERVAL * maxNumberOfRewardsPerMint; } function getChallengeNumber() public view override returns (bytes32) { return challengeNumber; } function getMiningDifficulty() public view override returns (uint256) { // 64 f's: 1234567890123456789012345678901234567890123456789012345678901234 uint256 maxInt = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; return maxInt / miningTarget; } function getMiningTarget() public view override returns (uint256) { return miningTarget; } function getMiningReward() public view override returns (uint256) { // use the timestamp of the ethereum block that gave the last reward // because ethereum miners can manipulate the value of block.timestamp return _getMiningReward(lastRewardBlockTime); } function _getMiningReward(uint256 _time) internal view returns (uint256) { return INITIAL_REWARD / 2**rewardEra(_time); } function getNumberOfRewardsAvailable(uint256 currentTime) external view returns (uint256) { return _numberOfRewardsAvailable(lastRewardBlockTime, maxNumberOfRewardsPerMint, currentTime); } function getRewardAmountForAchievingTarget(uint256 targetAchieved, uint256 currentTime) external view returns (uint256) { uint256 numberOfRewardsToGive = _numberOfRewardsToGive(miningTarget / targetAchieved, lastRewardBlockTime, maxNumberOfRewardsPerMint, currentTime); return _getMiningReward(currentTime) * numberOfRewardsToGive; } function decimals() public pure override returns (uint8) { return DECIMALS; } function totalSupply() public view override returns (uint256) { return tokensMinted; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view override 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) { require(to != address(0) && to != address(this), "Invalid address"); balances[msg.sender] = balances[msg.sender] - tokens; balances[to] = balances[to] + tokens; emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // Warning: This function is vulnerable to double-spend attacks and is // included for backwards compatibility. Use safeApprove instead. // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success) { require(spender != address(0) && spender != address(this), "Invalid address"); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Allow token owner to cancel the approval if the approved amount changes from its last // known value before this transaction is processed. This allows the owner to avoid // unintentionally re-approving funds that have already been spent. // ------------------------------------------------------------------------ function safeApprove(address spender, uint256 previousAllowance, uint256 newAllowance) external returns (bool success) { require(allowed[msg.sender][spender] == previousAllowance, "Current spender allowance does not match specified value"); return approve(spender, newAllowance); } // ------------------------------------------------------------------------ // 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(to != address(0) && to != address(this), "Invalid address"); balances[from] = balances[from] - tokens; allowed[from][msg.sender] = allowed[from][msg.sender] - tokens; balances[to] = balances[to] + tokens; emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view override returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed. This is vulnerable to double-spend attacks // when called directly, so it is declared internal and called by safeApproveAndCall // ------------------------------------------------------------------------ function approveAndCall(address spender, uint256 tokens, bytes memory data) internal returns (bool success) { require(spender != address(0) && spender != address(this), "Invalid address"); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Allow safe approvals with calls to receiving contract // ------------------------------------------------------------------------ function safeApproveAndCall(address spender, uint256 previousAllowance, uint256 newAllowance, bytes memory data) external returns (bool success) { require(allowed[msg.sender][spender] == previousAllowance, "Current spender allowance does not match specified value"); return approveAndCall(spender, newAllowance, data); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint256 tokens) external onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
use the timestamp of the ethereum block that gave the last reward because ethereum miners can manipulate the value of block.timestamp
function getMiningReward() public view override returns (uint256) { return _getMiningReward(lastRewardBlockTime); }
1,151,043
[ 1, 1202, 326, 2858, 434, 326, 13750, 822, 379, 1203, 716, 314, 836, 326, 1142, 19890, 2724, 13750, 822, 379, 1131, 414, 848, 28286, 326, 460, 434, 1203, 18, 5508, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9555, 310, 17631, 1060, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 203, 3639, 327, 389, 588, 2930, 310, 17631, 1060, 12, 2722, 17631, 1060, 1768, 950, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; contract BalanceHolder { mapping(address => uint256) public balanceOf; event LogWithdraw( address indexed user, uint256 amount ); function withdraw() public { uint256 bal = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; msg.sender.transfer(bal); emit LogWithdraw(msg.sender, bal); } } contract IBalanceHolder { mapping(address => uint256) public balanceOf; function withdraw() public { } } contract IRealitio is IBalanceHolder { struct Question { bytes32 content_hash; address arbitrator; uint32 opening_ts; uint32 timeout; uint32 finalize_ts; bool is_pending_arbitration; uint256 bounty; bytes32 best_answer; bytes32 history_hash; uint256 bond; } // Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond. struct Commitment { uint32 reveal_ts; bool is_revealed; bytes32 revealed_answer; } // Only used when claiming more bonds than fits into a transaction // Stored in a mapping indexed by question_id. struct Claim { address payee; uint256 last_bond; uint256 queued_funds; } uint256 nextTemplateID = 0; mapping(uint256 => uint256) public templates; mapping(uint256 => bytes32) public template_hashes; mapping(bytes32 => Question) public questions; mapping(bytes32 => Claim) public question_claims; mapping(bytes32 => Commitment) public commitments; mapping(address => uint256) public arbitrator_question_fees; /// @notice Function for arbitrator to set an optional per-question fee. /// @dev The per-question fee, charged when a question is asked, is intended as an anti-spam measure. /// @param fee The fee to be charged by the arbitrator when a question is asked function setQuestionFee(uint256 fee) external { } /// @notice Create a reusable template, which should be a JSON document. /// Placeholders should use gettext() syntax, eg %s. /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param content The template content /// @return The ID of the newly-created template, which is created sequentially. function createTemplate(string content) public returns (uint256) { } /// @notice Create a new reusable template and use it to ask a question /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param content The template content /// @param question A string containing the parameters that will be passed into the template to make the question /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer /// @param opening_ts If set, the earliest time it should be possible to answer the question. /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question. /// @return The ID of the newly-created template, which is created sequentially. function createTemplateAndAskQuestion( string content, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce ) // stateNotCreated is enforced by the internal _askQuestion public payable returns (bytes32) { } /// @notice Ask a new question and return the ID /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param template_id The ID number of the template the question will use /// @param question A string containing the parameters that will be passed into the template to make the question /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer /// @param opening_ts If set, the earliest time it should be possible to answer the question. /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question. /// @return The ID of the newly-created question, created deterministically. function askQuestion(uint256 template_id, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce) // stateNotCreated is enforced by the internal _askQuestion public payable returns (bytes32) { } /// @notice Add funds to the bounty for a question /// @dev Add bounty funds after the initial question creation. Can be done any time until the question is finalized. /// @param question_id The ID of the question you wish to fund function fundAnswerBounty(bytes32 question_id) external payable { } /// @notice Submit an answer for a question. /// @dev Adds the answer to the history and updates the current "best" answer. /// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them. /// @param question_id The ID of the question /// @param answer The answer, encoded into bytes32 /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. function submitAnswer(bytes32 question_id, bytes32 answer, uint256 max_previous) external payable { } /// @notice Submit the hash of an answer, laying your claim to that answer if you reveal it in a subsequent transaction. /// @dev Creates a hash, commitment_id, uniquely identifying this answer, to this question, with this bond. /// The commitment_id is stored in the answer history where the answer would normally go. /// Does not update the current best answer - this is left to the later submitAnswerReveal() transaction. /// @param question_id The ID of the question /// @param answer_hash The hash of your answer, plus a nonce that you will later reveal /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. /// @param _answerer If specified, the address to be given as the question answerer. Defaults to the sender. /// @dev Specifying the answerer is useful if you want to delegate the commit-and-reveal to a third-party. function submitAnswerCommitment(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer) external payable { } /// @notice Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction /// @dev Checks the parameters supplied recreate an existing commitment, and stores the revealed answer /// Updates the current answer unless someone has since supplied a new answer with a higher bond /// msg.sender is intentionally not restricted to the user who originally sent the commitment; /// For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx /// NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent /// @param question_id The ID of the question /// @param answer The answer, encoded as bytes32 /// @param nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment() /// @param bond The bond that you paid in your submitAnswerCommitment() transaction function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond) external { } /// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision. /// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them. /// @param question_id The ID of the question /// @param requester The account that requested arbitration /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous) external { } /// @notice Submit the answer for a question, for use by the arbitrator. /// @dev Doesn't require (or allow) a bond. /// If the current final answer is correct, the account should be whoever submitted it. /// If the current final answer is wrong, the account should be whoever paid for arbitration. /// However, the answerer stipulations are not enforced by the contract. /// @param question_id The ID of the question /// @param answer The answer, encoded into bytes32 /// @param answerer The account credited with this answer for the purpose of bond claims function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer) external { } /// @notice Report whether the answer to the specified question is finalized /// @param question_id The ID of the question /// @return Return true if finalized function isFinalized(bytes32 question_id) view public returns (bool) { } /// @notice (Deprecated) Return the final answer to the specified question, or revert if there isn't one /// @param question_id The ID of the question /// @return The answer formatted as a bytes32 function getFinalAnswer(bytes32 question_id) external view returns (bytes32) { } /// @notice Return the final answer to the specified question, or revert if there isn't one /// @param question_id The ID of the question /// @return The answer formatted as a bytes32 function resultFor(bytes32 question_id) external view returns (bytes32) { } /// @notice Return the final answer to the specified question, provided it matches the specified criteria. /// @dev Reverts if the question is not finalized, or if it does not match the specified criteria. /// @param question_id The ID of the question /// @param content_hash The hash of the question content (template ID + opening time + question parameter string) /// @param arbitrator The arbitrator chosen for the question (regardless of whether they are asked to arbitrate) /// @param min_timeout The timeout set in the initial question settings must be this high or higher /// @param min_bond The bond sent with the final answer must be this high or higher /// @return The answer formatted as a bytes32 function getFinalAnswerIfMatches( bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond ) external view returns (bytes32) { } /// @notice Assigns the winnings (bounty and bonds) to everyone who gave the accepted answer /// Caller must provide the answer history, in reverse order /// @dev Works up the chain and assign bonds to the person who gave the right answer /// If someone gave the winning answer earlier, they must get paid from the higher bond /// That means we can't pay out the bond added at n until we have looked at n-1 /// The first answer is authenticated by checking against the stored history_hash. /// One of the inputs to history_hash is the history_hash before it, so we use that to authenticate the next entry, etc /// Once we get to a null hash we'll know we're done and there are no more answers. /// Usually you would call the whole thing in a single transaction, but if not then the data is persisted to pick up later. /// @param question_id The ID of the question /// @param history_hashes Second-last-to-first, the hash of each history entry. (Final one should be empty). /// @param addrs Last-to-first, the address of each answerer or commitment sender /// @param bonds Last-to-first, the bond supplied with each answer or commitment /// @param answers Last-to-first, each answer supplied, or commitment ID if the answer was supplied with commit->reveal function claimWinnings( bytes32 question_id, bytes32[] history_hashes, address[] addrs, uint256[] bonds, bytes32[] answers ) public { } /// @notice Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds. /// Caller must provide the answer history for each question, in reverse order /// @dev Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call. /// @param question_ids The IDs of the questions you want to claim for /// @param lengths The number of history entries you will supply for each question ID /// @param hist_hashes In a single list for all supplied questions, the hash of each history entry. /// @param addrs In a single list for all supplied questions, the address of each answerer or commitment sender /// @param bonds In a single list for all supplied questions, the bond supplied with each answer or commitment /// @param answers In a single list for all supplied questions, each answer supplied, or commitment ID function claimMultipleAndWithdrawBalance( bytes32[] question_ids, uint256[] lengths, bytes32[] hist_hashes, address[] addrs, uint256[] bonds, bytes32[] answers ) public { } /// @notice Returns the questions's content hash, identifying the question content /// @param question_id The ID of the question function getContentHash(bytes32 question_id) public view returns(bytes32) { } /// @notice Returns the arbitrator address for the question /// @param question_id The ID of the question function getArbitrator(bytes32 question_id) public view returns(address) { } /// @notice Returns the timestamp when the question can first be answered /// @param question_id The ID of the question function getOpeningTS(bytes32 question_id) public view returns(uint32) { } /// @notice Returns the timeout in seconds used after each answer /// @param question_id The ID of the question function getTimeout(bytes32 question_id) public view returns(uint32) { } /// @notice Returns the timestamp at which the question will be/was finalized /// @param question_id The ID of the question function getFinalizeTS(bytes32 question_id) public view returns(uint32) { } /// @notice Returns whether the question is pending arbitration /// @param question_id The ID of the question function isPendingArbitration(bytes32 question_id) public view returns(bool) { } /// @notice Returns the current total unclaimed bounty /// @dev Set back to zero once the bounty has been claimed /// @param question_id The ID of the question function getBounty(bytes32 question_id) public view returns(uint256) { } /// @notice Returns the current best answer /// @param question_id The ID of the question function getBestAnswer(bytes32 question_id) public view returns(bytes32) { } /// @notice Returns the history hash of the question /// @param question_id The ID of the question /// @dev Updated on each answer, then rewound as each is claimed function getHistoryHash(bytes32 question_id) public view returns(bytes32) { } /// @notice Returns the highest bond posted so far for a question /// @param question_id The ID of the question function getBond(bytes32 question_id) public view returns(uint256) { } } /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } contract ICash{} contract IMarket { function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256); function isFinalized() public view returns (bool); function isInvalid() public view returns (bool); } contract IUniverse { function getWinningChildUniverse() public view returns (IUniverse); function createYesNoMarket(uint256 _endTime, uint256 _feePerEthInWei, ICash _denominationToken, address _designatedReporterAddress, bytes32 _topic, string _description, string _extraInfo) public payable returns (IMarket _newMarket); } contract RealitioAugurArbitrator is BalanceHolder { using strings for *; IRealitio public realitio; uint256 public template_id; uint256 dispute_fee; ICash public market_token; IUniverse public latest_universe; bytes32 constant REALITIO_INVALID = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 constant REALITIO_YES = 0x0000000000000000000000000000000000000000000000000000000000000001; bytes32 constant REALITIO_NO = 0x0000000000000000000000000000000000000000000000000000000000000000; uint256 constant AUGUR_YES_INDEX = 1; uint256 constant AUGUR_NO_INDEX = 0; string constant REALITIO_DELIMITER = '␟'; event LogRequestArbitration( bytes32 indexed question_id, uint256 fee_paid, address requester, uint256 remaining ); struct RealitioQuestion { uint256 bounty; address disputer; IMarket augur_market; address owner; } mapping(bytes32 => RealitioQuestion) public realitio_questions; modifier onlyInitialized() { require(dispute_fee > 0, "The contract cannot be used until a dispute fee has been set"); _; } modifier onlyUninitialized() { require(dispute_fee == 0, "The contract can only be initialized once"); _; } /// @notice Initialize a new contract /// @param _realitio The address of the realitio contract you arbitrate for /// @param _template_id The ID of the realitio template we support. /// @param _dispute_fee The fee this contract will charge for resolution /// @param _genesis_universe The earliest supported Augur universe /// @param _market_token The token used by the market we create, typically Augur's wrapped ETH function initialize(IRealitio _realitio, uint256 _template_id, uint256 _dispute_fee, IUniverse _genesis_universe, ICash _market_token) onlyUninitialized external { require(_dispute_fee > 0, "You must provide a dispute fee"); require(_realitio != IRealitio(0x0), "You must provide a realitio address"); require(_genesis_universe != IUniverse(0x0), "You must provide a genesis universe"); require(_market_token != ICash(0x0), "You must provide an augur cash token"); dispute_fee = _dispute_fee; template_id = _template_id; realitio = _realitio; latest_universe = _genesis_universe; market_token = _market_token; } /// @notice Register a new child universe after a fork /// @dev Anyone can create Augur universes but the "correct" ones should be in a single line from the official genesis universe /// @dev If a universe goes into a forking state, someone will need to call this before you can create new markets. function addForkedUniverse() onlyInitialized external { IUniverse child_universe = IUniverse(latest_universe).getWinningChildUniverse(); latest_universe = child_universe; } /// @notice Trim the realitio question content to the part before the initial delimiter. /// @dev The Realitio question is a list of parameters for a template. /// @dev We throw away the subsequent parameters of the question. /// @dev The first item in the (supported) template must be the title. /// @dev Subsequent items (category, lang) aren't needed in Augur. /// @dev This does not support more complex templates, eg selects which also need a list of answrs. function _trimQuestion(string q) internal pure returns (string) { return q.toSlice().split(REALITIO_DELIMITER.toSlice()).toString(); } function _callAugurMarketCreate(bytes32 question_id, string question, address designated_reporter) internal { realitio_questions[question_id].augur_market = latest_universe.createYesNoMarket.value(msg.value)( now, 0, market_token, designated_reporter, 0x0, _trimQuestion(question), ""); realitio_questions[question_id].owner = msg.sender; } /// @notice Create a market in Augur and store the creator as its owner /// @dev Anyone can call this, and calling this will give them the rights to claim the bounty /// @dev They will need have sent this contract some REP for the no-show bond. /// @param question The question content (a delimited parameter list) /// @param timeout The timeout between rounds, set when the question was created /// @param opening_ts The opening timestamp for the question, set when the question was created /// @param asker The address that created the question, ie the msg.sender of the original realitio.askQuestion call /// @param nonce The nonce for the question, set when the question was created /// @param designated_reporter The Augur designated reporter. We let the market creator choose this, if it's bad the Augur dispute resolution should sort it out function createMarket( string question, uint32 timeout, uint32 opening_ts, address asker, uint256 nonce, address designated_reporter ) onlyInitialized external payable { // Reconstruct the question ID from the content bytes32 question_id = keccak256(keccak256(template_id, opening_ts, question), this, timeout, asker, nonce); require(realitio_questions[question_id].bounty > 0, "Arbitration must have been requested (paid for)"); require(realitio_questions[question_id].augur_market == IMarket(0x0), "The market must not have been created yet"); // Create a market in Augur _callAugurMarketCreate(question_id, question, designated_reporter); } /// @notice Return data needed to verify the last history item /// @dev Filters the question struct from Realitio to stuff we need /// @dev Broken out into its own function to avoid stack depth limitations /// @param question_id The realitio question /// @param last_history_hash The history hash when you gave your answer /// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment /// @param last_bond The bond paid in the last answer given /// @param last_answerer The account that submitted the last answer (or its commitment) /// @param is_commitment Whether the last answer was submitted with commit->reveal function _verifyInput( bytes32 question_id, bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment ) internal view returns (bool, bytes32) { require(realitio.isPendingArbitration(question_id), "The question must be pending arbitration in realitio"); bytes32 history_hash = realitio.getHistoryHash(question_id); require(history_hash == keccak256(last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment), "The history parameters supplied must match the history hash in the realitio contract"); } /// @notice Given the last history entry, get whether they had a valid answer if so what it was /// @dev These just need to be fetched from Realitio, but they can't be fetched directly because we don't store them to save gas /// @dev To get the final answer, we need to reconstruct the final answer using the history hash /// @dev TODO: This should probably be in a library offered by Realitio /// @param question_id The ID of the realitio question /// @param last_history_hash The history hash when you gave your answer /// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment /// @param last_bond The bond paid in the last answer given /// @param last_answerer The account that submitted the last answer (or its commitment) /// @param is_commitment Whether the last answer was submitted with commit->reveal function _answerData( bytes32 question_id, bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment ) internal view returns (bool, bytes32) { bool is_pending_arbitration; bytes32 history_hash; // If the question hasn't been answered, nobody is ever right if (last_bond == 0) { return (false, bytes32(0)); } bytes32 last_answer; bool is_answered; if (is_commitment) { uint256 reveal_ts; bool is_revealed; bytes32 revealed_answer; (reveal_ts, is_revealed, revealed_answer) = realitio.commitments(last_answer_or_commitment_id); if (is_revealed) { last_answer = revealed_answer; is_answered = true; } else { // Shouldn't normally happen, but if the last answerer might still reveal when we are called, bail out and wait for them. require(reveal_ts < uint32(now), "Arbitration cannot be done until the last answerer has had time to reveal their commitment"); is_answered = false; } } else { last_answer = last_answer_or_commitment_id; is_answered = true; } return (is_answered, last_answer); } /// @notice Get the answer from the Augur market and map it to a Realitio value /// @param market The Augur market function realitioAnswerFromAugurMarket( IMarket market ) onlyInitialized public view returns (bytes32) { bytes32 answer; if (market.isInvalid()) { answer = REALITIO_INVALID; } else { uint256 no_val = market.getWinningPayoutNumerator(AUGUR_NO_INDEX); uint256 yes_val = market.getWinningPayoutNumerator(AUGUR_YES_INDEX); if (yes_val == no_val) { answer = REALITIO_INVALID; } else { if (yes_val > no_val) { answer = REALITIO_YES; } else { answer = REALITIO_NO; } } } return answer; } /// @notice Report the answer from a finalized Augur market to a Realitio contract with a question awaiting arbitration /// @dev Pays the arbitration bounty to whoever created the Augur market. Probably the same person will call this function, but they don't have to. /// @dev We need to know who gave the final answer and what it was, as they need to be supplied as the arbitration winner if the last answer is right /// @dev These just need to be fetched from Realitio, but they can't be fetched directly because to save gas, Realitio doesn't store them /// @dev To get the final answer, we need to reconstruct the final answer using the history hash /// @param question_id The ID of the question you're reporting on /// @param last_history_hash The history hash when you gave your answer /// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment /// @param last_bond The bond paid in the last answer given /// @param last_answerer The account that submitted the last answer (or its commitment) /// @param is_commitment Whether the last answer was submitted with commit->reveal function reportAnswer( bytes32 question_id, bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment ) onlyInitialized public { IMarket market = realitio_questions[question_id].augur_market; // There must be an open bounty require(realitio_questions[question_id].bounty > 0, "Arbitration must have been requested for this question"); bool is_answered; // the answer was provided, not just left as an unrevealed commit bytes32 last_answer; _verifyInput(question_id, last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment); (is_answered, last_answer) = _answerData(question_id, last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment); require(market.isFinalized(), "The augur market must have been finalized"); bytes32 answer = realitioAnswerFromAugurMarket(market); address winner; if (is_answered && last_answer == answer) { winner = last_answerer; } else { // If the final answer is wrong, we assign the person who paid for arbitration. // See https://realitio.github.io/docs/html/arbitrators.html for why. winner = realitio_questions[question_id].disputer; } realitio.submitAnswerByArbitrator(question_id, answer, winner); address owner = realitio_questions[question_id].owner; balanceOf[owner] += realitio_questions[question_id].bounty; delete realitio_questions[question_id]; } /// @notice Return the dispute fee for the specified question. 0 indicates that we won't arbitrate it. /// @dev Uses a general default, but can be over-ridden on a question-by-question basis. function getDisputeFee(bytes32) external view returns (uint256) { return dispute_fee; } /// @notice Request arbitration, freezing the question until we send submitAnswerByArbitrator /// @dev The bounty can be paid only in part, in which case the last person to pay will be considered the payer /// @dev Will trigger an error if the notification fails, eg because the question has already been finalized /// @param question_id The question in question /// @param max_previous The highest bond level we should accept (used to check the state hasn't changed) function requestArbitration(bytes32 question_id, uint256 max_previous) onlyInitialized external payable returns (bool) { require(msg.value >= dispute_fee, "The payment must cover the fee"); realitio.notifyOfArbitrationRequest(question_id, msg.sender, max_previous); realitio_questions[question_id].bounty = msg.value; realitio_questions[question_id].disputer = msg.sender; LogRequestArbitration(question_id, msg.value, msg.sender, 0); } }
@notice Create a reusable template, which should be a JSON document. Placeholders should use gettext() syntax, eg %s. @dev Template data is only stored in the event logs, but its block number is kept in contract storage. @param content The template content @return The ID of the newly-created template, which is created sequentially.
function createTemplate(string content) public returns (uint256) { }
1,808,933
[ 1, 1684, 279, 283, 16665, 1542, 16, 1492, 1410, 506, 279, 1796, 1668, 18, 13022, 9000, 1410, 999, 24972, 1435, 6279, 16, 9130, 738, 87, 18, 225, 5035, 501, 353, 1338, 4041, 316, 326, 871, 5963, 16, 1496, 2097, 1203, 1300, 353, 16555, 316, 6835, 2502, 18, 225, 913, 1021, 1542, 913, 327, 1021, 1599, 434, 326, 10894, 17, 4824, 1542, 16, 1492, 353, 2522, 695, 6979, 6261, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 2283, 12, 1080, 913, 13, 7010, 565, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {SplitStorage} from "./SplitStorage.sol"; interface ISplitFactory { function splitter() external returns (address); function wethAddress() external returns (address); function merkleRoot() external returns (bytes32); } /** * @title SplitProxy * @author MirrorXYZ */ contract SplitProxy is SplitStorage { constructor() { _splitter = ISplitFactory(msg.sender).splitter(); wethAddress = ISplitFactory(msg.sender).wethAddress(); merkleRoot = ISplitFactory(msg.sender).merkleRoot(); } fallback() external payable { address _impl = splitter(); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } function splitter() public view returns (address) { return _splitter; } // Plain ETH transfers. receive() external payable { depositedInWindow += msg.value; } }
* @title SplitProxy @author MirrorXYZ/
contract SplitProxy is SplitStorage { constructor() { _splitter = ISplitFactory(msg.sender).splitter(); wethAddress = ISplitFactory(msg.sender).wethAddress(); merkleRoot = ISplitFactory(msg.sender).merkleRoot(); } fallback() external payable { address _impl = splitter(); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } fallback() external payable { address _impl = splitter(); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } fallback() external payable { address _impl = splitter(); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } fallback() external payable { address _impl = splitter(); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } function splitter() public view returns (address) { return _splitter; } receive() external payable { depositedInWindow += msg.value; } }
12,663,425
[ 1, 5521, 3886, 225, 490, 8299, 23479, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 5385, 3886, 353, 5385, 3245, 288, 203, 565, 3885, 1435, 288, 203, 3639, 389, 4939, 387, 273, 4437, 1127, 1733, 12, 3576, 18, 15330, 2934, 4939, 387, 5621, 203, 3639, 341, 546, 1887, 273, 4437, 1127, 1733, 12, 3576, 18, 15330, 2934, 91, 546, 1887, 5621, 203, 3639, 30235, 2375, 273, 4437, 1127, 1733, 12, 3576, 18, 15330, 2934, 6592, 15609, 2375, 5621, 203, 565, 289, 203, 203, 565, 5922, 1435, 3903, 8843, 429, 288, 203, 3639, 1758, 389, 11299, 273, 21553, 5621, 203, 3639, 19931, 288, 203, 5411, 2231, 6571, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 745, 892, 3530, 12, 6723, 16, 374, 16, 745, 13178, 554, 10756, 203, 5411, 2231, 563, 519, 7152, 1991, 12, 31604, 9334, 389, 11299, 16, 6571, 16, 745, 13178, 554, 9334, 374, 16, 374, 13, 203, 5411, 2231, 963, 519, 327, 13178, 554, 1435, 203, 5411, 327, 892, 3530, 12, 6723, 16, 374, 16, 963, 13, 203, 203, 5411, 1620, 563, 203, 7734, 648, 374, 288, 203, 10792, 15226, 12, 6723, 16, 963, 13, 203, 7734, 289, 203, 7734, 805, 288, 203, 10792, 327, 12, 6723, 16, 963, 13, 203, 7734, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 5922, 1435, 3903, 8843, 429, 288, 203, 3639, 1758, 389, 11299, 273, 21553, 5621, 203, 3639, 19931, 288, 203, 5411, 2231, 6571, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 745, 892, 3530, 12, 6723, 16, 374, 16, 745, 13178, 554, 10756, 203, 5411, 2231, 563, 519, 7152, 1991, 2 ]
./partial_match/4/0xd3ca97e823999D0592e267ca64fCa564178490e5/sources/etherATM.sol
* @title etherATM-DeFi/
contract etherATM is ERC20, Ownable { using SafeMath for uint256; using Address for address; event Reserved(address indexed from, uint256 value); uint256 private _currentSupply = 0; uint256 private _softLimit = 99999000000000000000000; uint256 private _hardLimit = 99999000000000000000000; uint256 private _baseSlab = 0; uint256 private _basePriceWei = 20000000000000000; uint256 private _incrementWei = 666700000000; uint256 private _buyFee = 50; uint256 private _buyCommission = 1000; uint256 private _sellCommission = 50; address payable _commissionReceiver; address payable _feeReceiver; constructor ( string memory name, string memory symbol, uint8 decimals, address payable commissionReceiver, address payable feeReceiver ) ERC20(name, symbol) payable { _setupDecimals(decimals); _commissionReceiver = commissionReceiver; _feeReceiver = feeReceiver; } function percent(uint numerator, uint denominator, uint precision) public pure returns(uint quotient) { uint _numerator = numerator * 10 ** (precision+1); uint _quotient = ((_numerator / denominator) + 5) / 10; return ( _quotient); } receive() external payable{ emit Reserved(msg.sender, msg.value); } function setIncrement(uint256 increment) external onlyOwner(){ _incrementWei = increment; } function getIncrement() public view returns (uint256){ return _incrementWei; } function getHardLimit() public view returns (uint256){ return _hardLimit; } function getSoftLimit() public view returns (uint256){ return _softLimit; } function setMaxHolding(uint256 limit) external onlyOwner(){ _maxHolding = limit; } function getMaxHolding() public view returns (uint256){ return _maxHolding; } function setMaxSellBatch(uint256 limit) external onlyOwner(){ _maxSellBatch = limit; } function getMaxSellBatch() public view returns (uint256){ return _maxSellBatch; } function setCommissionReceiver(address payable rec) external onlyOwner(){ _commissionReceiver = rec; } function getCommissionReceiver() public view returns (address){ return _commissionReceiver; } function setFeeReceiver(address payable rec) external onlyOwner(){ _feeReceiver = rec; } function getFeeReceiver() public view returns (address){ return _feeReceiver; } function getCurrentSupply() public view returns (uint256){ return _currentSupply; } function setCurrentSupply(uint256 cs) external onlyOwner(){ _currentSupply = cs * 1 ether; } function getBaseSlab() public view returns (uint256){ return _baseSlab; } function setBaseSlab(uint256 bs) external onlyOwner(){ _baseSlab = bs * 1 ether; } function getBasePrice() public view returns (uint256){ return _basePriceWei; } function getBuyFee() public view returns (uint256){ return _buyFee; } function getBuyCommission() public view returns (uint256){ return _buyCommission; } function getSellCommission() public view returns (uint256){ return _sellCommission; } function setBuyCommission(uint256 bc) external onlyOwner(){ _buyCommission = bc; } function setBuyFee(uint256 bf) external onlyOwner(){ _buyFee = bf; } function setSellCommission(uint256 sc) external onlyOwner(){ _sellCommission = sc; } function setBasePrice(uint256 bp) external onlyOwner(){ _basePriceWei = bp; } function updateSlabs(uint256 bs, uint256 bp, uint256 increment) external onlyOwner(){ _basePriceWei = bp; _baseSlab = bs * 1 ether; _incrementWei = increment; } function getCurrentPrice() public view returns (uint256){ uint256 additionalTokens = _currentSupply.sub( _baseSlab, "An error has occurred"); uint256 increment = ((additionalTokens * _incrementWei) / 1 ether); uint256 price = _basePriceWei.add(increment); return price; } function buyTokens() external payable{ uint256 value = msg.value; uint256 price = getCurrentPrice(); uint256 tokens = uint256(value.div(price)) ; uint256 token_wei = tokens * 1 ether; uint256 fee = uint256((token_wei * _buyFee ) / 10000 ); uint256 commission = uint256((token_wei * _buyCommission ) / 100000 ); token_wei = token_wei.sub((fee + commission), "Calculation error"); require(balanceOf(_msgSender()) + token_wei < _maxHolding, "etherATM: You cannot buy more tokens"); transferTo(_msgSender(), (token_wei / 1 ether)); transferTo(_commissionReceiver, commission , false); transferTo(_feeReceiver, fee, false); } function transferTo(address to, uint256 value, bool convert_to_wei) internal { require(to != address(0), "etherATM: transfer to zero address"); deploy(to, value, convert_to_wei); } function transferTo(address to, uint256 value) internal { require(to != address(0), "etherATM: transfer to zero address"); deploy(to, value); } function deploy(address to, uint256 value) internal { value = value * 1 ether; require((_currentSupply + value ) < _hardLimit , "Max supply reached"); require((balanceOf(to) + value ) < _maxHolding , "You cannot hold more DXT" ); _mint(to, value); _currentSupply = _currentSupply.add(value); } function deploy(address to, uint256 value, bool convert_to_wei) internal { if(convert_to_wei) value = value * 1 ether; require((_currentSupply + value ) < _hardLimit , "Max supply reached"); require((balanceOf(to) + value ) < _maxHolding , "You cannot hold more DXT" ); _mint(to, value); _currentSupply = _currentSupply.add(value); } function byebye() external onlyOwner() { selfdestruct(owner()); } function clean(uint256 _amount) external onlyOwner(){ require(address(this).balance > _amount, "Invalid digits"); owner().transfer(_amount); } function sellTokens(uint256 amount) external { amount = amount * 1 ether; require(balanceOf(_msgSender()) >= amount, "etherATM: recipient account doesn't have enough balance"); require(amount <= _maxSellBatch, "etherATM: invalid sell quantity" ); _currentSupply = _currentSupply.sub(amount, "Base reached"); uint256 commission = uint256((amount * _sellCommission ) / 100000 ); amount = amount.sub( commission, "Calculation error"); uint256 wei_value = ((getCurrentPrice() * amount) / 1 ether); require(address(this).balance >= wei_value, "etherATM: invalid digits"); _burn(_msgSender(), (amount + commission) ); transferTo(_commissionReceiver, commission, false); _msgSender().transfer(wei_value); } }
8,711,512
[ 1, 2437, 789, 49, 17, 758, 42, 77, 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, 225, 2437, 789, 49, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 203, 565, 871, 16237, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 565, 2254, 5034, 3238, 389, 2972, 3088, 1283, 273, 374, 31, 203, 203, 565, 2254, 5034, 3238, 389, 9269, 3039, 273, 23841, 12648, 2787, 9449, 31, 203, 565, 2254, 5034, 3238, 389, 20379, 3039, 273, 23841, 12648, 2787, 9449, 31, 203, 203, 565, 2254, 5034, 3238, 389, 1969, 3738, 378, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 1969, 5147, 3218, 77, 273, 576, 12648, 12648, 31, 203, 203, 565, 2254, 5034, 3238, 389, 15016, 3218, 77, 273, 1666, 6028, 27, 12648, 31, 203, 565, 2254, 5034, 3238, 389, 70, 9835, 14667, 273, 6437, 31, 203, 565, 2254, 5034, 3238, 389, 70, 9835, 799, 3951, 273, 4336, 31, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 799, 3951, 273, 6437, 31, 203, 203, 203, 565, 1758, 8843, 429, 389, 832, 3951, 12952, 31, 203, 565, 1758, 8843, 429, 389, 21386, 12952, 31, 203, 203, 565, 3885, 261, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 2254, 28, 15105, 16, 203, 3639, 1758, 8843, 429, 1543, 19710, 12952, 16, 203, 3639, 1758, 8843, 429, 14036, 12952, 203, 565, 262, 4232, 39, 3462, 12, 529, 16, 3273, 13, 8843, 429, 288, 203, 3639, 389, 8401, 31809, 12, 31734, 1769, 203, 203, 3639, 2 ]
./partial_match/1/0x790C95EF074B77A8F92A5163cC056F163A8631e6/sources/BancorConverter.sol
used to efficiently prevent increasing the total reserve ratio above 100%
uint32 private totalReserveRatio = 0;
3,918,107
[ 1, 3668, 358, 14382, 715, 5309, 21006, 326, 2078, 20501, 7169, 5721, 2130, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 1578, 3238, 2078, 607, 6527, 8541, 273, 374, 31, 7734, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./IERC20.sol"; import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; // TODO : add limit on each user (max number of floyx a user can buy) // min and max limit contract ICOTokenCrowdsale is ReentrancyGuard, Ownable { using SafeMath for uint256; IERC20 internal _token; IERC20 internal _usdc; IERC20 internal _usdt; bool public crowdsaleFinalized; // token sale status uint256 private _icoCap; // ico max limit uint256 public soldTokens; // Amount of tokens sold uint256 public weiRaised; // Amount of wei raised uint256 public usdRaised; // Amount of usd raised address payable private _wallet; // Address where funds are collected uint256 public weiRate; // wei rate of token uint256 public usdRate; // usd rate of token uint256 public lockPeriod; // token Lock period uint256 public userTokenLimit; // max tokens a user can buy mapping(address => uint256) public totalTokensPurchased; mapping(address => uint256) public claimCount; event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event paymentProccessed(address receiver, uint256 amount, bytes info); constructor (uint256 rate_,uint256 usdRate_ ,address token_, uint256 icocap_, address usdc, address usdt, address adminWallet, uint256 lockPeriod_, uint256 tokenLimit) Ownable() { weiRate = rate_; usdRate = usdRate_; _wallet = payable(adminWallet); _token = IERC20(token_); _usdc = IERC20(usdc); _usdt = IERC20(usdt); crowdsaleFinalized = false; _icoCap = icocap_; lockPeriod = lockPeriod_; userTokenLimit = tokenLimit; } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return bool after setting the address where funds are collected. */ function setWallet(address payable wallet_)public onlyOwner returns(bool) { require(wallet_ != address(0),"Invalid minter address!"); _wallet = wallet_; return true; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } function updateWeiRate(uint256 rate_)public onlyOwner{ weiRate = rate_; } function updateUsdRate(uint256 rate_)public onlyOwner{ usdRate = rate_; } function updateLockPeriod(uint256 lockPeriod_)public onlyOwner{ require(block.timestamp < lockPeriod, "Can not update lock period once it is passed"); lockPeriod = lockPeriod_; } function updateTokenLimit(uint256 tokenLimit_)public onlyOwner{ userTokenLimit = tokenLimit_ ; } /** * @dev 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 { require(!crowdsaleFinalized,"Crowdsale is finalized!"); require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(msg.value != 0, "Crowdsale: weiAmount is 0"); uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount, true); weiRaised = weiRaised.add(weiAmount); _processPayment(_wallet, msg.value); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); } /** * @dev This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase * @param usdAmount_ amount of usdc or usdt tokens used to buy floyx. * @param usdc boolean variable to check payment will be in usdc or usdt */ function buyTokenswithUsd(address beneficiary, uint256 usdAmount_,bool usdc, bool usdt) public nonReentrant { require(usdc != usdt , "Crowdsale: One of the value should be passed true"); require(usdAmount_ > 0 , "Crowdsale: UsdAmount is 0"); require(!crowdsaleFinalized,"Crowdsale is finalized!"); require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); uint256 tokens = _getTokenAmount(usdAmount_, false); usdRaised = usdRaised.add(usdAmount_); usdc ? _usdc.transferFrom(msg.sender, address(this), usdAmount_) : _usdt.transferFrom(msg.sender, address(this), usdAmount_); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, usdAmount_, tokens); } function claimTokens()public{ require(block.timestamp > lockPeriod, "Crowdsale: Can not claim during lock period"); require(claimCount[msg.sender] < 13, "Crowdsale: No more claims left"); uint256 monthDiff = (block.timestamp.sub(lockPeriod)).div(30 days); require(monthDiff > claimCount[msg.sender], "Crowdsale: Nothing to claim yet"); if (monthDiff > 12){ monthDiff = 12;} for(uint i = claimCount[msg.sender]; i < monthDiff; i ++){ claimCount[msg.sender] += 1; uint256 tokenAmount = (totalTokensPurchased[msg.sender].mul(6).div(100)); // release 6% of the tokens tokenAmount = tokenAmount.add(tokenAmount.mul(2).div(100)); // extra 2% reward on every claim _token.transfer(msg.sender, tokenAmount); } if (claimCount[msg.sender] == 12 && monthDiff == 12){ claimCount[msg.sender] += 1; uint256 tokenAmount = (totalTokensPurchased[msg.sender].mul(8).div(100)); // release 8% of the tokens tokenAmount = tokenAmount.add(tokenAmount.mul(2).div(100)); // extra 2% reward on every claim _token.transfer(msg.sender, tokenAmount); } } function finalizeCrowdsale() public onlyOwner{ require(!crowdsaleFinalized,"Crowdsale: Crowdsale is finalized!"); crowdsaleFinalized = true; } /** * @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 { require(soldTokens.add(tokenAmount) <= _icoCap , "ICO limit reached"); require(totalTokensPurchased[beneficiary].add(tokenAmount) <= userTokenLimit, "User max allocation limit reached"); soldTokens = soldTokens.add(tokenAmount); _token.transfer(beneficiary, (tokenAmount.mul(20).div(100))); totalTokensPurchased[beneficiary] = totalTokensPurchased[beneficiary].add(tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param amount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 amount, bool eth) internal view returns (uint256) { return eth ? (amount.mul(weiRate)).div(1e10) : (amount.mul(usdRate)); } /** * @dev Determines how MATIC is forwarded to admin. */ function adminMaticWithdrawal(uint256 amount_) public onlyOwner { _processPayment(_wallet, amount_); } function adminFloyxWithdrawal(uint256 _amount)public onlyOwner { require(_token.balanceOf(address(this)) >= _amount, "Contract does not have enough balance"); _token.transfer(msg.sender, _amount); } function adminUsdcWithdrawal(uint256 _amount)public onlyOwner { require(_usdc.balanceOf(address(this)) >= _amount, "Contract does not have enough balance"); _usdc.transfer(msg.sender, _amount); } function adminUsdtWithdrawal(uint256 _amount)public onlyOwner { require(_usdt.balanceOf(address(this)) >= _amount, "Contract does not have enough balance"); _usdt.transfer(msg.sender, _amount); } /** * @dev function to transfer matic to recepient account */ function _processPayment(address payable recepient, uint256 amount_)private{ (bool sent, bytes memory data) = recepient.call{value: amount_}(""); require(sent, "Failed to send Ether"); emit paymentProccessed(recepient, amount_, data); } }
* @return bool after setting the address where funds are collected./
function setWallet(address payable wallet_)public onlyOwner returns(bool) { require(wallet_ != address(0),"Invalid minter address!"); _wallet = wallet_; return true; }
14,042,903
[ 1, 2463, 1426, 1839, 3637, 326, 1758, 1625, 284, 19156, 854, 12230, 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, 444, 16936, 12, 2867, 8843, 429, 9230, 67, 13, 482, 1338, 5541, 1135, 12, 6430, 13, 288, 203, 3639, 2583, 12, 19177, 67, 480, 1758, 12, 20, 3631, 6, 1941, 1131, 387, 1758, 4442, 1769, 203, 3639, 389, 19177, 273, 9230, 67, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x545d99dC1CC6224EB7a6eCFA579a13c05FEE5E0C/sources/Mind/c1.sol
return; executeOperationTest(assets,amounts,amounts,address(this), _params);
function invokeAave(address _token, uint _amount, bytes memory _params) internal { ILendingPool lendingPool = getLendingPool(); address[] memory assets = new address[](1); uint256[] memory amounts = new uint256[](1); uint256[] memory modes = new uint256[](1); assets[0] = _token; amounts[0] = _amount; modes[0] = 0; lendingPool.flashLoan( assets, amounts, modes, _params, ); revert("TEST REVERT"); MyLogS("som tu "); }
16,259,983
[ 1, 2463, 31, 565, 1836, 2988, 4709, 12, 9971, 16, 8949, 87, 16, 8949, 87, 16, 2867, 12, 2211, 3631, 389, 2010, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4356, 37, 836, 12, 2867, 389, 2316, 16, 2254, 389, 8949, 16, 225, 1731, 3778, 389, 2010, 13, 2713, 288, 203, 540, 203, 3639, 467, 48, 2846, 2864, 328, 2846, 2864, 273, 9014, 2846, 2864, 5621, 203, 540, 203, 3639, 1758, 8526, 3778, 7176, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 2254, 5034, 8526, 3778, 30980, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 3639, 2254, 5034, 8526, 3778, 12382, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 203, 3639, 7176, 63, 20, 65, 273, 389, 2316, 31, 7010, 3639, 30980, 63, 20, 65, 273, 389, 8949, 31, 7010, 3639, 12382, 63, 20, 65, 273, 374, 31, 203, 1377, 203, 377, 203, 3639, 328, 2846, 2864, 18, 13440, 1504, 304, 12, 203, 5411, 7176, 16, 203, 5411, 30980, 16, 203, 5411, 12382, 16, 203, 5411, 389, 2010, 16, 203, 3639, 11272, 203, 540, 203, 3639, 15226, 2932, 16961, 2438, 21654, 8863, 203, 3639, 8005, 1343, 55, 2932, 87, 362, 28325, 315, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-05-22 */ pragma solidity 0.6.6; // ---------------------------------------------------------------------------- // 'ShitCoin' token contract // // Deployed to : 0x4e973a0C7E024a415e5A2B9bf1A6CaB6813B7636 // Symbol : SHT // Name : ShitCoin // Total supply: 69420000 // Decimals : 18 // // Enjoy. // // (c) by Jacob Robert Morales. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() virtual public view returns (uint); function balanceOf(address tokenOwner) virtual public view returns (uint balance); function allowance(address tokenOwner, address spender) virtual public view returns (uint remaining); function transfer(address to, uint tokens) virtual public returns (bool success); function approve(address spender, uint tokens) virtual public returns (bool success); function transferFrom(address from, address to, uint tokens) virtual public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- abstract contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) virtual public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract ShitCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "SHT"; name = "ShitCoin"; decimals = 18; _totalSupply = 69420000000000000000000000; balances[0x4e973a0C7E024a415e5A2B9bf1A6CaB6813B7636] = _totalSupply; emit Transfer(address(0), 0x4e973a0C7E024a415e5A2B9bf1A6CaB6813B7636, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public 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, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ // function () external payable { // revert(); // } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract ShitCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "SHT"; name = "ShitCoin"; decimals = 18; _totalSupply = 69420000000000000000000000; balances[0x4e973a0C7E024a415e5A2B9bf1A6CaB6813B7636] = _totalSupply; emit Transfer(address(0), 0x4e973a0C7E024a415e5A2B9bf1A6CaB6813B7636, _totalSupply); } function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
10,808,985
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2638, 305, 27055, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 2664, 56, 14432, 203, 3639, 508, 273, 315, 1555, 305, 27055, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 20963, 9452, 12648, 12648, 9449, 31, 203, 3639, 324, 26488, 63, 20, 92, 24, 73, 29, 9036, 69, 20, 39, 27, 41, 3103, 24, 69, 24, 3600, 73, 25, 37, 22, 38, 29, 17156, 21, 37, 26, 23508, 38, 9470, 3437, 38, 27, 4449, 26, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 24, 73, 29, 9036, 69, 20, 39, 27, 41, 3103, 24, 69, 24, 3600, 73, 25, 37, 22, 38, 29, 17156, 21, 37, 26, 23508, 38, 9470, 3437, 38, 27, 4449, 26, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Operator.sol"; contract Orchestrator is Operator { struct Transaction { bool enabled; address destination; bytes4 data; } event TransactionFailed(address indexed destination, uint index, bytes data); Transaction[] public transactions; /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, string memory data) external onlyOperator { Transaction memory tran = Transaction({ enabled: true, destination: destination, data: bytes4(keccak256(bytes(data))) }); transactions.push(tran); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyOperator { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.pop(); } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyOperator { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @return Number of transactions, both enabled and disabled, in transactions list. */ function transactionsSize() external view returns (uint256) { return transactions.length; } function externalCall() public { for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { _externalCall(t.destination,t.data); } } } /** * wrapper to call the encoded transactions on downstream consumers. * destination Address of destination contract. * data The encoded data payload. * True on success */ function _externalCall(address destination, bytes4 selector) internal { (bool success, bytes memory data) = destination.call(abi.encodeWithSelector(selector)); require(success && (data.length == 0 || abi.decode(data, (bool))), "Orchestrator: Transaction Failed"); } }
* @param index Index of transaction to remove. Transaction ordering may have changed since adding./
function removeTransaction(uint index) external onlyOperator { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.pop(); }
5,409,466
[ 1, 1615, 3340, 434, 2492, 358, 1206, 18, 2868, 5947, 9543, 2026, 1240, 3550, 3241, 6534, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 3342, 12, 11890, 770, 13, 203, 3639, 3903, 203, 3639, 1338, 5592, 203, 565, 288, 203, 3639, 2583, 12, 1615, 411, 8938, 18, 2469, 16, 315, 1615, 596, 434, 4972, 8863, 203, 3639, 309, 261, 1615, 411, 8938, 18, 2469, 300, 404, 13, 288, 203, 5411, 8938, 63, 1615, 65, 273, 8938, 63, 20376, 18, 2469, 300, 404, 15533, 203, 3639, 289, 203, 3639, 8938, 18, 5120, 5621, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-02-12 */ // SPDX-License-Identifier: MIT pragma solidity =0.8.10; abstract contract IDFSRegistry { function getAddr(bytes4 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256 digits); function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library Address { //insufficient balance error InsufficientBalance(uint256 available, uint256 required); //unable to send value, recipient may have reverted error SendingValueFail(); //insufficient balance for call error InsufficientBalanceForCall(uint256 available, uint256 required); //call to non-contract error NonContractCall(); function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { uint256 balance = address(this).balance; if (balance < amount){ revert InsufficientBalance(balance, amount); } // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); if (!(success)){ revert SendingValueFail(); } } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { uint256 balance = address(this).balance; if (balance < value){ revert InsufficientBalanceForCall(balance, value); } return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { if (!(isContract(target))){ revert NonContractCall(); } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /// @dev Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract MainnetAuthAddresses { address internal constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD; address internal constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; address internal constant ADMIN_ADDR = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; // USED IN ADMIN VAULT CONSTRUCTOR } contract AuthHelper is MainnetAuthAddresses { } contract AdminVault is AuthHelper { address public owner; address public admin; error SenderNotAdmin(); constructor() { owner = msg.sender; admin = ADMIN_ADDR; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { if (admin != msg.sender){ revert SenderNotAdmin(); } owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { if (admin != msg.sender){ revert SenderNotAdmin(); } admin = _admin; } } contract AdminAuth is AuthHelper { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR); error SenderNotOwner(); error SenderNotAdmin(); modifier onlyOwner() { if (adminVault.owner() != msg.sender){ revert SenderNotOwner(); } _; } modifier onlyAdmin() { if (adminVault.admin() != msg.sender){ revert SenderNotAdmin(); } _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DFSRegistry is AdminAuth { error EntryAlreadyExistsError(bytes4); error EntryNonExistentError(bytes4); error EntryNotInChangeError(bytes4); error ChangeNotReadyError(uint256,uint256); error EmptyPrevAddrError(bytes4); error AlreadyInContractChangeError(bytes4); error AlreadyInWaitPeriodChangeError(bytes4); event AddNewContract(address,bytes4,address,uint256); event RevertToPreviousAddress(address,bytes4,address,address); event StartContractChange(address,bytes4,address,address); event ApproveContractChange(address,bytes4,address,address); event CancelContractChange(address,bytes4,address,address); event StartWaitPeriodChange(address,bytes4,uint256); event ApproveWaitPeriodChange(address,bytes4,uint256,uint256); event CancelWaitPeriodChange(address,bytes4,uint256,uint256); struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes4 => Entry) public entries; mapping(bytes4 => address) public previousAddresses; mapping(bytes4 => address) public pendingAddresses; mapping(bytes4 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes4 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes4 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes4 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { if (entries[_id].exists){ revert EntryAlreadyExistsError(_id); } entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); emit AddNewContract(msg.sender, _id, _contractAddr, _waitPeriod); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes4 _id) public onlyOwner { if (!(entries[_id].exists)){ revert EntryNonExistentError(_id); } if (previousAddresses[_id] == address(0)){ revert EmptyPrevAddrError(_id); } address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; emit RevertToPreviousAddress(msg.sender, _id, currentAddr, previousAddresses[_id]); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes4 _id, address _newContractAddr) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inWaitPeriodChange){ revert AlreadyInWaitPeriodChangeError(_id); } entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; emit StartContractChange(msg.sender, _id, entries[_id].contractAddr, _newContractAddr); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){// solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; emit ApproveContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; emit CancelContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes4 _id, uint256 _newWaitPeriod) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inContractChange){ revert AlreadyInContractChangeError(_id); } pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; emit StartWaitPeriodChange(msg.sender, _id, _newWaitPeriod); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){ // solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; emit ApproveWaitPeriodChange(msg.sender, _id, oldWaitTime, entries[_id].waitPeriod); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; emit CancelWaitPeriodChange(msg.sender, _id, oldWaitPeriod, entries[_id].waitPeriod); } } abstract contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view virtual returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "Not authorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(address(0))) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) { if (!(setCache(_cacheAddr))){ require(isAuthorized(msg.sender, msg.sig), "Not authorized"); } } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code function execute(bytes memory _code, bytes memory _data) public payable virtual returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public payable virtual returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } contract DefisaverLogger { event RecipeEvent( address indexed caller, string indexed logName ); event ActionDirectEvent( address indexed caller, string indexed logName, bytes data ); function logRecipeEvent( string memory _logName ) public { emit RecipeEvent(msg.sender, _logName); } function logActionDirectEvent( string memory _logName, bytes memory _data ) public { emit ActionDirectEvent(msg.sender, _logName, _data); } } contract MainnetActionsUtilAddresses { address internal constant DFS_REG_CONTROLLER_ADDR = 0xF8f8B3C98Cf2E63Df3041b73f80F362a4cf3A576; address internal constant REGISTRY_ADDR = 0x287778F121F134C66212FB16c9b53eC991D32f5b; address internal constant DFS_LOGGER_ADDR = 0xcE7a977Cac4a481bc84AC06b2Da0df614e621cf3; } contract ActionsUtilHelper is MainnetActionsUtilAddresses { } abstract contract ActionBase is AdminAuth, ActionsUtilHelper { event ActionEvent( string indexed logName, bytes data ); DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( DFS_LOGGER_ADDR ); //Wrong sub index value error SubIndexValueError(); //Wrong return index value error ReturnIndexValueError(); /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, FEE_ACTION, CHECK_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the RecipeExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = uint256(_subData[getSubIndex(_mapType)]); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal view returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { /// @dev The last two values are specially reserved for proxy addr and owner addr if (_mapType == 254) return address(this); //DSProxy address if (_mapType == 255) return DSProxy(payable(address(this))).owner(); // owner of DSProxy _param = address(uint160(uint256(_subData[getSubIndex(_mapType)]))); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = _subData[getSubIndex(_mapType)]; } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { if (!(isReturnInjection(_type))){ revert SubIndexValueError(); } return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { if (_type < SUB_MIN_INDEX_VALUE){ revert ReturnIndexValueError(); } return (_type - SUB_MIN_INDEX_VALUE); } } abstract contract IWETH { function allowance(address, address) public virtual view returns (uint256); function balanceOf(address) public virtual view returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } library TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken( address _tokenAddr, address _to, uint256 _amount ) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokensIfNeeded( address _token, address _from, uint256 _amount ) internal returns (uint256) { // handle max uint amount if (_amount == type(uint256).max) { _amount = getBalance(_token, _from); } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function depositWeth(uint256 _amount) internal { IWETH(WETH_ADDR).deposit{value: _amount}(); } function withdrawWeth(uint256 _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } contract MainnetUniV3Addresses { address internal constant POSITION_MANAGER_ADDR = 0xC36442b4a4522E871399CD717aBDD847Ab11FE88; } abstract contract IUniswapV3NonfungiblePositionManager{ struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } function mint(MintParams calldata params) external virtual payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } function increaseLiquidity(IncreaseLiquidityParams calldata params) external virtual payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } function decreaseLiquidity(DecreaseLiquidityParams calldata params) external virtual payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } function collect(CollectParams calldata params) external virtual payable returns (uint256 amount0, uint256 amount1); function positions(uint256 tokenId) external virtual 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 ); function balanceOf(address owner) external virtual view returns (uint256 balance); function tokenOfOwnerByIndex(address owner, uint256 index) external virtual view returns (uint256 tokenId); function approve(address to, uint256 tokenId) public virtual; /// @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 virtual payable returns (address pool); } contract UniV3Helper is MainnetUniV3Addresses { IUniswapV3NonfungiblePositionManager public constant positionManager = IUniswapV3NonfungiblePositionManager(POSITION_MANAGER_ADDR); } contract UniSupplyV3 is ActionBase, UniV3Helper{ using TokenUtils for address; /// @param tokenId - The ID of the token for which liquidity is being increased /// @param liquidity -The amount by which liquidity will be increased, /// @param amount0Desired - The desired amount of token0 that should be supplied, /// @param amount1Desired - The desired amount of token1 that should be supplied, /// @param amount0Min - The minimum amount of token0 that should be supplied, /// @param amount1Min - The minimum amount of token1 that should be supplied, /// @param deadline - The time by which the transaction must be included to effect the change /// @param from - account to take amounts from /// @param token0 - address of the first token /// @param token1 - address of the second token struct Params { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; address from; address token0; address token1; } /// @inheritdoc ActionBase function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory uniData = parseInputs(_callData); uniData.tokenId = _parseParamUint(uniData.tokenId, _paramMapping[0], _subData, _returnValues); uniData.amount0Desired = _parseParamUint(uniData.amount0Desired, _paramMapping[1], _subData, _returnValues); uniData.amount1Desired = _parseParamUint(uniData.amount1Desired, _paramMapping[2], _subData, _returnValues); (uint128 liquidity, bytes memory logData) = _uniSupplyPosition(uniData); emit ActionEvent("UniSupplyV3", logData); return bytes32(uint256(liquidity)); } /// @inheritdoc ActionBase function executeActionDirect(bytes memory _callData) public payable override { Params memory uniData = parseInputs(_callData); (, bytes memory logData) = _uniSupplyPosition(uniData); logger.logActionDirectEvent("UniSupplyV3", logData); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// function _uniSupplyPosition(Params memory _uniData) internal returns(uint128 liquidity, bytes memory logData) { // fetch tokens from address uint amount0Pulled = _uniData.token0.pullTokensIfNeeded(_uniData.from, _uniData.amount0Desired); uint amount1Pulled = _uniData.token1.pullTokensIfNeeded(_uniData.from, _uniData.amount1Desired); // approve positionManager so it can pull tokens _uniData.token0.approveToken(address(positionManager), amount0Pulled); _uniData.token1.approveToken(address(positionManager), amount1Pulled); _uniData.amount0Desired = amount0Pulled; _uniData.amount1Desired = amount1Pulled; uint256 amount0; uint256 amount1; (liquidity, amount0, amount1) = _uniSupply(_uniData); //send leftovers _uniData.token0.withdrawTokens(_uniData.from, _uniData.amount0Desired - amount0); _uniData.token1.withdrawTokens(_uniData.from, _uniData.amount1Desired - amount1); logData = abi.encode(_uniData, liquidity, amount0, amount1); } /// @dev increases liquidity by token amounts desired /// @return liquidity new liquidity amount function _uniSupply(Params memory _uniData) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { IUniswapV3NonfungiblePositionManager.IncreaseLiquidityParams memory increaseLiquidityParams = IUniswapV3NonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: _uniData.tokenId, amount0Desired: _uniData.amount0Desired, amount1Desired: _uniData.amount1Desired, amount0Min: _uniData.amount0Min, amount1Min: _uniData.amount1Min, deadline: _uniData.deadline }); (liquidity, amount0, amount1) = positionManager.increaseLiquidity(increaseLiquidityParams); } function parseInputs(bytes memory _callData) public pure returns ( Params memory uniData ) { uniData = abi.decode(_callData, (Params)); } }
@dev increases liquidity by token amounts desired @return liquidity new liquidity amount
function _uniSupply(Params memory _uniData) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { IUniswapV3NonfungiblePositionManager.IncreaseLiquidityParams memory increaseLiquidityParams = IUniswapV3NonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: _uniData.tokenId, amount0Desired: _uniData.amount0Desired, amount1Desired: _uniData.amount1Desired, amount0Min: _uniData.amount0Min, amount1Min: _uniData.amount1Min, deadline: _uniData.deadline }); (liquidity, amount0, amount1) = positionManager.increaseLiquidity(increaseLiquidityParams); }
7,848,615
[ 1, 267, 1793, 3304, 4501, 372, 24237, 635, 1147, 30980, 6049, 327, 4501, 372, 24237, 394, 4501, 372, 24237, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 318, 77, 3088, 1283, 12, 1370, 3778, 389, 318, 77, 751, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 203, 5411, 2254, 10392, 4501, 372, 24237, 16, 203, 5411, 2254, 5034, 3844, 20, 16, 203, 5411, 2254, 5034, 3844, 21, 203, 3639, 262, 203, 565, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 23, 3989, 12125, 75, 1523, 2555, 1318, 18, 382, 11908, 48, 18988, 24237, 1370, 3778, 10929, 48, 18988, 24237, 1370, 273, 7010, 5411, 467, 984, 291, 91, 438, 58, 23, 3989, 12125, 75, 1523, 2555, 1318, 18, 382, 11908, 48, 18988, 24237, 1370, 12590, 203, 7734, 1147, 548, 30, 389, 318, 77, 751, 18, 2316, 548, 16, 203, 7734, 3844, 20, 25683, 30, 389, 318, 77, 751, 18, 8949, 20, 25683, 16, 203, 7734, 3844, 21, 25683, 30, 389, 318, 77, 751, 18, 8949, 21, 25683, 16, 203, 7734, 3844, 20, 2930, 30, 389, 318, 77, 751, 18, 8949, 20, 2930, 16, 203, 7734, 3844, 21, 2930, 30, 389, 318, 77, 751, 18, 8949, 21, 2930, 16, 203, 7734, 14096, 30, 389, 318, 77, 751, 18, 22097, 1369, 203, 5411, 15549, 203, 3639, 261, 549, 372, 24237, 16, 3844, 20, 16, 3844, 21, 13, 273, 1754, 1318, 18, 267, 11908, 48, 18988, 24237, 12, 267, 11908, 48, 18988, 24237, 1370, 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 ]
./partial_match/56/0xa2006a4C4609793439967825463008Ad8bAd55f2/sources/StrategymssLP.sol
* @dev Swaps {mss} for {lpToken0}, {lpToken1} & {wbnb} using PancakeSwap./
function addLiquidity() internal { uint256 mssHalf = IERC20(mss).balanceOf(address(this)).div(2); if (lpToken0 != mss) { IPancakeRouter(unirouter).swapExactTokensForTokens( mssHalf, 0, mssToLp0Route, address(this), now.add(600) ); } if (lpToken1 != mss) { IPancakeRouter(unirouter).swapExactTokensForTokens( mssHalf, 0, mssToLp1Route, address(this), now.add(600) ); } uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this)); uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this)); IPancakeRouter(unirouter).addLiquidity( lpToken0, lpToken1, lp0Bal, lp1Bal, 1, 1, address(this), now.add(600) ); }
11,068,499
[ 1, 6050, 6679, 288, 959, 87, 97, 364, 288, 9953, 1345, 20, 5779, 288, 9953, 1345, 21, 97, 473, 288, 9464, 6423, 97, 1450, 12913, 23780, 12521, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 48, 18988, 24237, 1435, 2713, 288, 203, 3639, 2254, 5034, 312, 1049, 16168, 273, 467, 654, 39, 3462, 12, 959, 87, 2934, 12296, 951, 12, 2867, 12, 2211, 13, 2934, 2892, 12, 22, 1769, 203, 203, 3639, 309, 261, 9953, 1345, 20, 480, 312, 1049, 13, 288, 203, 5411, 2971, 19292, 911, 8259, 12, 318, 77, 10717, 2934, 22270, 14332, 5157, 1290, 5157, 12, 203, 7734, 312, 1049, 16168, 16, 203, 7734, 374, 16, 203, 7734, 312, 1049, 774, 48, 84, 20, 3255, 16, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 2037, 18, 1289, 12, 28133, 13, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 309, 261, 9953, 1345, 21, 480, 312, 1049, 13, 288, 203, 5411, 2971, 19292, 911, 8259, 12, 318, 77, 10717, 2934, 22270, 14332, 5157, 1290, 5157, 12, 203, 7734, 312, 1049, 16168, 16, 203, 7734, 374, 16, 203, 7734, 312, 1049, 774, 48, 84, 21, 3255, 16, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 2037, 18, 1289, 12, 28133, 13, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 12423, 20, 38, 287, 273, 467, 654, 39, 3462, 12, 9953, 1345, 20, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 12423, 21, 38, 287, 273, 467, 654, 39, 3462, 12, 9953, 1345, 21, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2971, 19292, 911, 8259, 12, 318, 77, 10717, 2934, 1289, 48, 18988, 24237, 12, 203, 5411, 12423, 1345, 20, 16, 203, 5411, 12423, 1345, 2 ]
/** * @notice TellerNFTDictionary Version 1.02 * * @notice This contract is used to gather data for TellerV1 NFTs more efficiently. * @notice This contract has data which must be continuously synchronized with the TellerV1 NFT data * * @author [email protected] */ pragma solidity ^0.8.0; // Contracts import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; // Interfaces import "./IStakeableNFT.sol"; /** * @notice This contract is used by borrowers to call Dapp functions (using delegate calls). * @notice This contract should only be constructed using it's upgradeable Proxy contract. * @notice In order to call a Dapp function, the Dapp must be added in the DappRegistry instance. * * @author [email protected] */ contract TellerNFTDictionary is IStakeableNFT, AccessControlUpgradeable { struct Tier { uint256 baseLoanSize; string[] hashes; address contributionAsset; uint256 contributionSize; uint8 contributionMultiplier; } mapping(uint256 => uint256) public baseLoanSizes; mapping(uint256 => string[]) public hashes; mapping(uint256 => address) public contributionAssets; mapping(uint256 => uint256) public contributionSizes; mapping(uint256 => uint8) public contributionMultipliers; /* Constants */ bytes32 public constant ADMIN = keccak256("ADMIN"); /* State Variables */ mapping(uint256 => uint256) public _tokenTierMappingCompressed; bool public _tokenTierMappingCompressedSet; /* Modifiers */ modifier onlyAdmin() { require(hasRole(ADMIN, _msgSender()), "TellerNFTDictionary: not admin"); _; } function initialize(address initialAdmin) public { _setupRole(ADMIN, initialAdmin); _setRoleAdmin(ADMIN, ADMIN); __AccessControl_init(); } /* External Functions */ /** * @notice It returns information about a Tier for a token ID. * @param tokenId ID of the token to get Tier info. */ function getTokenTierIndex(uint256 tokenId) public view returns (uint8 index_) { //32 * 8 = 256 - each uint256 holds the data of 32 tokens . 8 bits each. uint256 mappingIndex = tokenId / 32; uint256 compressedRegister = _tokenTierMappingCompressed[mappingIndex]; //use 31 instead of 32 to account for the '0x' in the start. //the '31 -' reverses our bytes order which is necessary uint256 offset = ((31 - (tokenId % 32)) * 8); uint8 tierIndex = uint8((compressedRegister >> offset)); return tierIndex; } function getTierHashes(uint256 tierIndex) external view returns (string[] memory) { return hashes[tierIndex]; } /** * @notice Adds a new Tier to be minted with the given information. * @dev It auto increments the index of the next tier to add. * @param newTier Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTier(uint256 index, Tier memory newTier) external onlyAdmin returns (bool) { baseLoanSizes[index] = newTier.baseLoanSize; hashes[index] = newTier.hashes; contributionAssets[index] = newTier.contributionAsset; contributionSizes[index] = newTier.contributionSize; contributionMultipliers[index] = newTier.contributionMultiplier; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param tiersMapping Information about the new tiers to add. * * Requirements: * - Caller must have the {Admin} role */ function setAllTokenTierMappings(uint256[] memory tiersMapping) public onlyAdmin returns (bool) { require( !_tokenTierMappingCompressedSet, "TellerNFTDictionary: token tier mapping already set" ); for (uint256 i = 0; i < tiersMapping.length; i++) { _tokenTierMappingCompressed[i] = tiersMapping[i]; } _tokenTierMappingCompressedSet = true; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param index the mapping row, each holds data for 32 tokens * @param tierMapping Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierMapping(uint256 index, uint256 tierMapping) public onlyAdmin returns (bool) { _tokenTierMappingCompressed[index] = tierMapping; return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenIds the NFT token Ids for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenIds( uint256[] calldata tokenIds, uint256 tokenTier ) public onlyAdmin returns (bool) { for (uint256 i; i < tokenIds.length; i++) { setTokenTierForTokenId(tokenIds[i], tokenTier); } return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenId the NFT token Id for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenId(uint256 tokenId, uint256 tokenTier) public onlyAdmin returns (bool) { uint256 mappingIndex = tokenId / 32; uint256 existingRegister = _tokenTierMappingCompressed[mappingIndex]; uint256 offset = ((31 - (tokenId % 32)) * 8); uint256 updateMaskShifted = 0x00000000000000000000000000000000000000000000000000000000000000FF << offset; uint256 updateMaskShiftedNegated = ~updateMaskShifted; uint256 tokenTierShifted = ((0x0000000000000000000000000000000000000000000000000000000000000000 | tokenTier) << offset); uint256 existingRegisterClearedWithMask = existingRegister & updateMaskShiftedNegated; uint256 updatedRegister = existingRegisterClearedWithMask | tokenTierShifted; _tokenTierMappingCompressed[mappingIndex] = updatedRegister; return true; } function supportsInterface(bytes4 interfaceId) public view override(AccessControlUpgradeable) returns (bool) { return interfaceId == type(IStakeableNFT).interfaceId || AccessControlUpgradeable.supportsInterface(interfaceId); } /** New methods for the dictionary */ /** * @notice It returns Base Loan Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenBaseLoanSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return baseLoanSizes[tokenTier]; } /** * @notice It returns Token URI Hash for a token ID. * @param tokenId ID of the token to get info. */ function tokenURIHash(uint256 tokenId) public view override returns (string memory) { uint8 tokenTier = getTokenTierIndex(tokenId); string[] memory tierImageHashes = hashes[tokenTier]; return tierImageHashes[tokenId % (tierImageHashes.length)]; } /** * @notice It returns Contribution Asset for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionAsset(uint256 tokenId) public view override returns (address) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionAssets[tokenTier]; } /** * @notice It returns Contribution Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionSizes[tokenTier]; } /** * @notice It returns Contribution Multiplier for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionMultiplier(uint256 tokenId) public view override returns (uint8) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionMultipliers[tokenTier]; } }
* @notice Sets a specific tier for a specific tokenId using compressed data. @param tokenId the NFT token Id for which to add data @param tokenTier the index of the tier that these tokenIds should have Requirements: - Caller must have the {Admin} role/
function setTokenTierForTokenId(uint256 tokenId, uint256 tokenTier) public onlyAdmin returns (bool) { uint256 mappingIndex = tokenId / 32; uint256 existingRegister = _tokenTierMappingCompressed[mappingIndex]; uint256 offset = ((31 - (tokenId % 32)) * 8); uint256 updateMaskShifted = 0x00000000000000000000000000000000000000000000000000000000000000FF << offset; uint256 updateMaskShiftedNegated = ~updateMaskShifted; uint256 tokenTierShifted = ((0x0000000000000000000000000000000000000000000000000000000000000000 | tokenTier) << offset); uint256 existingRegisterClearedWithMask = existingRegister & updateMaskShiftedNegated; uint256 updatedRegister = existingRegisterClearedWithMask | tokenTierShifted; _tokenTierMappingCompressed[mappingIndex] = updatedRegister; return true; }
896,622
[ 1, 2785, 279, 2923, 17742, 364, 279, 2923, 1147, 548, 1450, 8968, 501, 18, 225, 1147, 548, 326, 423, 4464, 1147, 3124, 364, 1492, 358, 527, 501, 225, 1147, 15671, 326, 770, 434, 326, 17742, 716, 4259, 1147, 2673, 1410, 1240, 29076, 30, 225, 300, 20646, 1297, 1240, 326, 288, 4446, 97, 2478, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22629, 15671, 1290, 1345, 548, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 1147, 15671, 13, 203, 3639, 1071, 203, 3639, 1338, 4446, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2254, 5034, 2874, 1016, 273, 1147, 548, 342, 3847, 31, 203, 203, 3639, 2254, 5034, 2062, 3996, 273, 389, 2316, 15671, 3233, 16841, 63, 6770, 1016, 15533, 203, 203, 3639, 2254, 5034, 1384, 273, 14015, 6938, 300, 261, 2316, 548, 738, 3847, 3719, 380, 1725, 1769, 203, 203, 3639, 2254, 5034, 1089, 5796, 10544, 329, 273, 374, 92, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 9449, 2246, 2296, 203, 7734, 1384, 31, 203, 203, 3639, 2254, 5034, 1089, 5796, 10544, 329, 14337, 690, 273, 4871, 2725, 5796, 10544, 329, 31, 203, 203, 3639, 2254, 5034, 1147, 15671, 10544, 329, 273, 14015, 20, 92, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 571, 203, 7734, 1147, 15671, 13, 2296, 1384, 1769, 203, 203, 3639, 2254, 5034, 2062, 3996, 4756, 2258, 1190, 5796, 273, 2062, 3996, 473, 203, 5411, 1089, 5796, 10544, 329, 14337, 690, 31, 203, 203, 3639, 2254, 5034, 3526, 3996, 273, 2062, 3996, 4756, 2258, 1190, 5796, 571, 203, 5411, 1147, 15671, 10544, 329, 31, 203, 203, 3639, 389, 2316, 15671, 3233, 16841, 63, 6770, 1016, 65, 273, 3526, 3996, 31, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.12; // This is an NFT for CryptoMofayas https://www.cryptomofayas.com/ // Smart contract developed by Ian Cherkowski https://twitter.com/IanCherkowski // Thanks to chiru-labs for their gas friendly ERC721A implementation. // import "./ERC721A.sol"; import "./Ownable.sol"; import "./IERC20.sol"; import "./ReentrancyGuard.sol"; contract CryptoMofayasNFT is ERC721A, ReentrancyGuard, Ownable { event PaymentReceived(address from, uint256 amount); string private constant _name = "CryptoMofayas"; string private constant _symbol = "CMS"; string public baseURI = "https://ipfs.io/ipfs/QmcZjwmDovzBU3AQP4q91pHyZ3moE1vXyAU8Tsxmcmmeyv/"; uint256 public maxMint = 20; uint256 public presaleLimit = 200; uint256 public presalePrice = 0.09 ether; uint256 public mintPrice = 0.1 ether; uint256 public maxSupply = 1999; uint256 public commission = 15; bool public freeze = false; bool public status = false; bool public presale = false; bool public onlyAffiliate = true; mapping(address => bool) public affiliateList; constructor() ERC721A(_name, _symbol) payable { } // @dev needed to enable receiving to test withdrawls receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } // @dev owner can mint to a list of addresses with the quantity entered function gift(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner { uint256 numTokens = 0; uint256 i; require(recipients.length == amounts.length, "CryptoMofayas: The number of addresses is not matching the number of amounts"); //find total to be minted for (i = 0; i < recipients.length; i++) { require(Address.isContract(recipients[i]) == false, "CryptoMofayas: no contracts"); numTokens += amounts[i]; } require(numTokens < 200, "CryptoMofayas: Minting more than 200 may get stuck"); require(totalSupply() + numTokens <= maxSupply, "CryptoMofayas: Can't mint more than the max supply"); //mint to the list for (i = 0; i < amounts.length; i++) { _safeMint(recipients[i], amounts[i]); } } // @dev public minting, accepts affiliate address function mint(uint256 _mintAmount, address affiliate) external payable nonReentrant { uint256 supply = totalSupply(); require(Address.isContract(msg.sender) == false, "CryptoMofayas: no contracts"); require(Address.isContract(affiliate) == false, "CryptoMofayas: no contracts"); require(status || presale, "CryptoMofayas: Minting not started yet"); require(_mintAmount > 0, "CryptoMofayas: Cant mint 0"); require(_mintAmount <= maxMint, "CryptoMofayas: Must mint less than the max"); require(supply + _mintAmount <= maxSupply, "CryptoMofayas: Cant mint more than max supply"); if (presale && !status) { require(supply + _mintAmount <= presaleLimit, "CryptoMofayas: Presale is sold out"); require(msg.value >= presalePrice * _mintAmount, "CryptoMofayas: Must send eth of cost per nft"); } else { require(msg.value >= mintPrice * _mintAmount, "CryptoMofayas: Must send eth of cost per nft"); } _safeMint(msg.sender, _mintAmount); //if address is owner then no payout if (affiliate != owner() && commission > 0) { //if only recorded affiliates can receive payout if (onlyAffiliate == false || (onlyAffiliate && affiliateList[affiliate])) { //pay out the affiliate Address.sendValue(payable(affiliate), msg.value * _mintAmount * commission / 100); } } } // @dev record affiliate address function allowAffiliate(address newAffiliate, bool allow) external onlyOwner { require(newAffiliate != address(0), "CryptoMofayas: not valid address"); require(Address.isContract(newAffiliate) == false, "CryptoMofayas: no contracts"); affiliateList[newAffiliate] = allow; } // @dev set commission amount in percentage function setCommission(uint256 _newCommission) external onlyOwner { require(_newCommission < 100, "CryptoMofayas: must be percentage"); commission = _newCommission; } // @dev if only recorded affiliate can receive payout function setOnlyAffiliate(bool _affiliate) external onlyOwner { onlyAffiliate = _affiliate; } // @dev set cost of minting function setMintPrice(uint256 _newmintPrice) external onlyOwner { mintPrice = _newmintPrice; } // @dev set cost of minting function setPresalePrice(uint256 _newmintPrice) external onlyOwner { presalePrice = _newmintPrice; } // @dev max mint during presale function setPresaleLimit(uint256 _newLimit) external onlyOwner { presaleLimit = _newLimit; } // @dev max mint amount per transaction function setMaxMint(uint256 _newMaxMintAmount) external onlyOwner { maxMint = _newMaxMintAmount; } // @dev unpause main minting stage function setSaleStatus(bool _status) external onlyOwner { status = _status; } // @dev unpause presale minting stage function setPresaleStatus(bool _presale) external onlyOwner { presale = _presale; } // @dev Set the base url path to the metadata used by opensea function setBaseURI(string memory _baseTokenURI) external onlyOwner { require(freeze == false, "CryptoMofayas: uri is frozen"); baseURI = _baseTokenURI; } // @dev freeze the URI after the reveal function freezeURI() external onlyOwner { freeze = true; } // @dev show the baseuri function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // @dev used to reduce the max supply instead of a burn function reduceMaxSupply(uint256 newMax) external onlyOwner { require(newMax < maxSupply, "CryptoMofayas: New maximum must be less than existing maximum"); require(newMax >= totalSupply(), "CryptoMofayas: New maximum can't be less than minted count"); maxSupply = newMax; } // @dev used to withdraw erc20 tokens like DAI function withdrawERC20(IERC20 token, address to) external onlyOwner { require(Address.isContract(to) == false, "CryptoMofayas: no contracts"); token.transfer(payable(to), token.balanceOf(address(this))); } // @dev used to withdraw eth function withdraw(address payable to) external onlyOwner { require(Address.isContract(to) == false, "CryptoMofayas: no contracts"); Address.sendValue(payable(to),address(this).balance); } }
@dev used to withdraw eth
function withdraw(address payable to) external onlyOwner { require(Address.isContract(to) == false, "CryptoMofayas: no contracts"); Address.sendValue(payable(to),address(this).balance); }
10,105,344
[ 1, 3668, 358, 598, 9446, 13750, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 2867, 8843, 429, 358, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 1887, 18, 291, 8924, 12, 869, 13, 422, 629, 16, 315, 18048, 16727, 507, 93, 345, 30, 1158, 20092, 8863, 203, 3639, 5267, 18, 4661, 620, 12, 10239, 429, 12, 869, 3631, 2867, 12, 2211, 2934, 12296, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xC25148cB2a1CE39d121003f26422E724bD46782C/sources/contracts/Tranche.sol
Make strategy calculate and disburse yield
function _collectYield( uint256 trancheId, address currency, address recipient ) internal returns (uint256) { address holdingStrategy = getCurrentHoldingStrategy(trancheId); uint256 yield = IStrategy(holdingStrategy).collectYield( trancheId, currency, recipient ); _trackUpdated(trancheId); return yield; }
4,635,086
[ 1, 6464, 6252, 4604, 471, 1015, 70, 295, 307, 2824, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 14676, 16348, 12, 203, 3639, 2254, 5034, 13637, 18706, 548, 16, 203, 3639, 1758, 5462, 16, 203, 3639, 1758, 8027, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1758, 19918, 4525, 273, 5175, 20586, 25866, 12, 13171, 18706, 548, 1769, 203, 3639, 2254, 5034, 2824, 273, 467, 4525, 12, 21056, 25866, 2934, 14676, 16348, 12, 203, 5411, 13637, 18706, 548, 16, 203, 5411, 5462, 16, 203, 5411, 8027, 203, 3639, 11272, 203, 203, 3639, 389, 4101, 7381, 12, 13171, 18706, 548, 1769, 203, 3639, 327, 2824, 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 ]
pragma solidity ^0.4.11; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => uint256) public balances; bool public endICO = false; uint256 public dateEndIco; event TransferStart(); modifier canTransfer() { require(endICO); require(dateEndIco + (3 weeks) > now); _; } /** * @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 canTransfer returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function finishICO() internal returns (bool) { endICO = true; dateEndIco = now; TransferStart(); return true; } } /** @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract TokenRecipient { function receiveApproval(address _from, uint _value, address _tknAddress, bytes _extraData); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public canTransfer returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public canTransfer returns (bool) { allowed[msg.sender][_spender] = _value; Approval(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 canTransfer returns (bool success) { TokenRecipient spender = TokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); 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 canTransfer constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public canTransfer returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public canTransfer returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; finishICO(); MintFinished(); return true; } } /** * @title SampleCrowdsaleToken * @dev Very simple ERC20 Token that can be minted. * It is meant to be used in a crowdsale contract. */ contract NOUSToken is MintableToken { string public constant name = "NOUSTOKEN"; string public constant symbol = "NST"; uint32 public constant decimals = 18; }
* @title Basic token @dev Basic version of StandardToken, with no allowances./
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => uint256) public balances; bool public endICO = false; uint256 public dateEndIco; event TransferStart(); modifier canTransfer() { require(endICO); require(dateEndIco + (3 weeks) > now); _; } function transfer(address _to, uint256 _value) public canTransfer returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function finishICO() internal returns (bool) { endICO = true; dateEndIco = now; TransferStart(); return true; } }
10,704,115
[ 1, 8252, 1147, 225, 7651, 1177, 434, 8263, 1345, 16, 598, 1158, 1699, 6872, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7651, 1345, 353, 4232, 39, 3462, 8252, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 324, 26488, 31, 203, 203, 565, 1426, 1071, 679, 2871, 51, 273, 629, 31, 203, 565, 2254, 5034, 1071, 1509, 1638, 45, 2894, 31, 203, 203, 565, 871, 12279, 1685, 5621, 203, 203, 565, 9606, 848, 5912, 1435, 288, 203, 3639, 2583, 12, 409, 2871, 51, 1769, 203, 3639, 2583, 12, 712, 1638, 45, 2894, 397, 261, 23, 17314, 13, 405, 2037, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 848, 5912, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 3639, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 5381, 1135, 261, 11890, 5034, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 67, 8443, 15533, 203, 565, 289, 203, 203, 565, 445, 4076, 2871, 51, 1435, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 679, 2871, 51, 273, 638, 31, 203, 3639, 1509, 1638, 45, 2 ]
pragma solidity ^0.4.14; // Daily Price Oracles » Brave New Coin https://bravenewcoin.com/services/oracles/daily-price-oracles // The BNC Bitcoin Liquid Index (BNC-BLX) // https://create.smartcontract.com/#/contracts/35495df8a3031f4cd342e0a476e64e5d // Ethereum Address: 0x182f88d457b26196a263a8af45caa1f0b6b3b1c3 // Read Function Address: 9fa6a6e3 // https://api.bravenewcoin.com/ep_pub/v2/gwa-eod-latest-twap?&coin=BTC /* { "success": true, "source": "BraveNewCoin", "time_stamp": 1503792000, "utc_date": "2017-08-27 00:00:00", "coin_symbol": "BTC", "coin_name": "Bitcoin", "eod_twap": "4345.19575258", "price_currency": "USD", "price_currency_name": "United States Dollar" } */ contract Oracle{ function update(bytes32 _newCurrent); function current()constant returns(bytes32 _current); } contract MyOracle is Oracle { bytes32 x; // 4345.19575258 // 434519575258 // 0x652B628ADA // "0x00000000000000000000000000000000000000000000000000000652B628ADA" function update(bytes32 _newCurrent) { x = _newCurrent; } function current() constant returns(bytes32 _current){ return x; } function oracleCurrentInt() returns (uint){ return uint(x); } } contract MyOracle2{ uint x; function update(uint _newCurrent) { x = _newCurrent; } function current() constant returns(uint _current){ return x; } } contract Foo { MyOracle2 oracle; function setMyOracle2(address _addrMyOracle){ oracle = MyOracle2(_addrMyOracle); } function mbtcToUsd(uint _value) returns (uint){ return oracle.current() * _value / 1000; } } // TODO // ETHEREUM PRICE ORACLE // SmartContract https://create.smartcontract.com/#/contracts/0ccd9464f479480e6a25d4b21e54d023
4345.19575258 434519575258 0x652B628ADA "0x00000000000000000000000000000000000000000000000000000652B628ADA"
contract MyOracle is Oracle { bytes32 x; function update(bytes32 _newCurrent) { x = _newCurrent; } function current() constant returns(bytes32 _current){ return x; } function oracleCurrentInt() returns (uint){ return uint(x); } }
12,700,465
[ 1, 24, 25574, 18, 31677, 5877, 2947, 28, 1059, 25574, 31677, 5877, 2947, 28, 374, 92, 9222, 22, 38, 26, 6030, 1880, 37, 315, 20, 92, 12648, 12648, 12648, 12648, 12648, 12648, 2787, 7677, 9401, 38, 26, 6030, 1880, 37, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8005, 23601, 353, 28544, 288, 203, 377, 203, 565, 1731, 1578, 619, 31, 203, 565, 445, 1089, 12, 3890, 1578, 389, 2704, 3935, 13, 288, 203, 3639, 619, 273, 389, 2704, 3935, 31, 203, 565, 289, 203, 202, 203, 202, 915, 783, 1435, 5381, 1135, 12, 3890, 1578, 389, 2972, 15329, 203, 202, 565, 327, 619, 31, 203, 202, 97, 203, 202, 203, 202, 915, 20865, 3935, 1702, 1435, 1135, 261, 11890, 15329, 203, 3639, 327, 2254, 12, 92, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/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 (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // 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 pragma solidity ^0.8.0; /// _______ _______ _______ _ _______ _______ _______ _______ /// ( ____ \( ___ )( ___ )( \ ( ____ )( ___ )( ___ )( ____ ) /// | ( \/| ( ) || ( ) || ( | ( )|| ( ) || ( ) || ( )| /// | | | | | || | | || | | (____)|| | | || (___) || (____)| /// | | | | | || | | || | | _____)| | | || ___ || _____) /// | | | | | || | | || | | ( | | | || ( ) || ( /// | (____/\| (___) || (___) || (____/\| ) | (___) || ) ( || ) /// (_______/(_______)(_______)(_______/|/ (_______)|/ \||/ /// /// @author: kfei.eth /// @notice: Not audited, please use at your own risk. import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract CoolPOAP is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _eventIdTracker; Counters.Counter private _tokenIdTracker; struct Event { string uri; address host; } error CP_NoPermission(); error CP_EventDoesNotExist(); error CP_TokenDoesNotExist(); event CP_EventCreated(uint256 indexed eventId, string indexed uri); event CP_EventURIUpdated(uint256 indexed eventId, string indexed uri); event CP_EventHostUpdated(uint256 indexed eventId, address indexed host); mapping(uint256 => Event) _events; mapping(uint256 => uint256) _tokenEventIds; /** * @dev Constructooooooor */ constructor(string memory n, string memory s) ERC721(n, s) {} /** * @dev Create an event, permissionlessly */ function createEvent(string calldata uri, address host) external payable returns (uint256) { uint256 id = _eventIdTracker.current() + 1; _events[id] = Event({uri: uri, host: host}); _eventIdTracker.increment(); emit CP_EventCreated(id, uri); return id; } /** * @dev Reverts when the event doesn't exist or caller isn't the host */ modifier onlyHost(uint256 eventId, address user) { if (eventId > _eventIdTracker.current()) revert CP_EventDoesNotExist(); if (_events[eventId].host != user) revert CP_NoPermission(); _; } /** * @dev Mint tokens to each recipient */ function mint(uint256 eventId, address[] calldata recipients) external payable onlyHost(eventId, msg.sender) { uint256 currentId = _tokenIdTracker.current(); unchecked { for (uint256 i = 0; i < recipients.length; i++) { uint256 tokenId = ++currentId; _safeMint(recipients[i], tokenId); _tokenEventIds[tokenId] = eventId; _tokenIdTracker.increment(); } } } /** * @dev Update the tokenURI for an event */ function setEventURI(uint256 eventId, string calldata uri) external onlyHost(eventId, msg.sender) { _events[eventId].uri = uri; emit CP_EventURIUpdated(eventId, uri); } /** * @dev Transfer the host role */ function setEventHost(uint256 eventId, address host) external onlyHost(eventId, msg.sender) { _events[eventId].host = host; emit CP_EventHostUpdated(eventId, host); } /** * @notice Just in case */ function withdraw(address payable recipient, uint256 amount) external onlyOwner { recipient.transfer(amount); } /** * @notice Just in case */ function withdraw( address recipient, address erc20, uint256 amount ) external onlyOwner { IERC20(erc20).transfer(recipient, amount); } /** * @dev Get event URI by ID */ function getEventURIById(uint256 eventId) external view returns (string memory) { return _events[eventId].uri; } /** * @dev Get event host by ID */ function getEventHostById(uint256 eventId) external view returns (address) { return _events[eventId].host; } /** * @dev Get event ID by token */ function getEventIdByToken(uint256 tokenId) external view returns (uint256) { if (!_exists(tokenId)) revert CP_TokenDoesNotExist(); return _tokenEventIds[tokenId]; } /** * @dev See {IERC721Enumerable-totalSupply} */ function totalSupply() external view returns (uint256) { return _tokenIdTracker.current(); } /** * @dev See {IERC721Metadata-tokenURI} */ function tokenURI(uint256 tokenId) public view override returns (string memory) { if (!_exists(tokenId)) revert CP_TokenDoesNotExist(); return _events[_tokenEventIds[tokenId]].uri; } /** * @notice Just in case */ receive() external payable {} }
* @dev Get event URI by ID/
function getEventURIById(uint256 eventId) external view returns (string memory) { return _events[eventId].uri; }
10,320,266
[ 1, 967, 871, 3699, 635, 1599, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9832, 3098, 5132, 12, 11890, 5034, 26004, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 327, 389, 5989, 63, 2575, 548, 8009, 1650, 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 ]
// pragma solidity ^0.4.25; pragma solidity ^0.4.24; 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 uint private balance; // define contract funds mapping(address => uint256) private credits; // credit balance of an address mapping(bytes32 => mapping(address => uint256)) private insurances; // individual insurance balance mapping(address => bool) private authorizedContracts; struct Flight { bool isRegistered; uint8 statusCode; uint256 departureTimestamp; uint256 updatedArrivalTimestamp; address airline; } mapping(bytes32 => Flight) private flights; struct Airline { bool isRegistered; uint256 invitations; mapping(address => bool) hasInvited; uint256 deposit; } mapping(address => Airline) private airlines; uint256 private airlineCount; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // The deploying account becomes contractOwner // First airline gets registered and funded automatically constructor() public payable { contractOwner = msg.sender; airlineCount = 1; airlines[contractOwner].isRegistered = true; fund(msg.value); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifier that requires the "operational" boolean variable to be "true" modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; } // Modifier that requires the "ContractOwner" account to be the function caller modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } // Added modifier that requires airline to be authorized (registered and funded) modifier isCallerAuthorized() { require(authorizedContracts[msg.sender], 'Caller is not authorized'); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ // Get operating status of contract and return A bool that is the current operating status function isOperational() public view returns(bool) { return operational; } // 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 */ /********************************************************************************************/ // Add an airline to the registration queue // Can only be called from FlightSuretyApp contract function registerAirline(address airline, address endorsingAirline) external isCallerAuthorized() returns(bool success, uint256 votes) { // Only existing airline may register a new airline until there are at least four airlines registered if (airlineCount < 4) { airlines[endorsingAirline].hasInvited[airline] = true; airlineCount++; airlines[airline].isRegistered = true; airlines[airline].invitations = 1; return (true, 1); } else { // Registration of fifth and subsequent airlines requires multi-party consensus of 50% of registered airlines if (airlines[airline].invitations.mul(2) >= airlineCount) { airlineCount++; airlines[airline].isRegistered = true; airlines[airline].invitations += 1; return (true, airlines[airline].invitations); } else { airlines[airline].invitations += 1; return (false, airlines[airline].invitations); } } } // Register flight function registerFlight(address airline, string flight, uint256 departureTimestamp ) external isCallerAuthorized() returns(bool) { require(airlines[airline].isRegistered, "Airline not found"); bytes32 flightKey = getFlightKey(airline, flight, departureTimestamp); flights[flightKey].isRegistered = true; flights[flightKey].departureTimestamp = departureTimestamp; return true; } // Set flight status code function setFlightStatus(bytes32 flightKey, uint8 statusCode) external isCallerAuthorized() returns(uint8) { flights[flightKey].statusCode = statusCode; return statusCode; } // Buy insurance for a flight function buy(address airline, string flight, uint256 timestamp) external payable { require(msg.value > 0 && msg.value <= 1 ether, 'Pay up to 1 Ether'); bytes32 flightKey = getFlightKey(airline, flight, timestamp); insurances[flightKey][msg.sender] = msg.value; } // Credits payouts to insurees function creditInsuree(address passenger, address airline, string flight, uint256 departureTimestamp ) external isCallerAuthorized() returns(bool) { bytes32 flightKey = getFlightKey(airline, flight, departureTimestamp); require(flights[flightKey].statusCode == 20, 'Airline has caused no delay'); uint256 total = insurances[flightKey][passenger]; require(total > 0, "No insurance purchased"); // If flight is delayed due to airline fault, passenger receives credit of 1.5X the amount they paid uint256 payout = insurances[flightKey][passenger].mul(3).div(2); uint256 credit = credits[passenger]; insurances[flightKey][passenger] = insurances[flightKey][passenger].sub(total); credits[passenger] = credit.add(payout); require(credit.add(payout) > 0, 'No credits to pay out'); } // Transfers eligible payout funds to insuree function pay() external { uint256 credit = credits[msg.sender]; credits[msg.sender] = 0; msg.sender.transfer(credit); } // Initial funding for the insurance. Unless there are too many delayed flights // resulting in insurance payouts, the contract should be self-sustaining function fund(uint256 amount) internal { balance = balance.add(amount); } function getFlightKey(address airline, string memory flight, uint256 timestamp) pure internal returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // function isFlight(address airline, string flight, uint256 timestamp) external view returns(bool) { // bytes32 flightKey = getFlightKey(airline, flight, timestamp); // return flights[flightKey].isRegistered; // } // function isAirline(address candidateAirline) external view returns(bool) { // Airline memory airline = airlines[candidateAirline]; // return airline.isRegistered && (airline.deposit >= 10 ether); // } // function isRegistered(address airline) public view returns(bool) { // return airlines[airline].isRegistered; // } // function depositAirlineFee(address airline) external payable requireIsOperational() isCallerAuthorized() returns(bool) { // require(airlines[airline].isRegistered, 'Not a registered airline'); // airlines[airline].deposit += msg.value; // return true; // } // Fallback function for funding smart contract function()external payable { fund(msg.value); } }
Transfers eligible payout funds to insuree
function pay() external { uint256 credit = credits[msg.sender]; credits[msg.sender] = 0; msg.sender.transfer(credit); }
15,817,109
[ 1, 1429, 18881, 21351, 293, 2012, 284, 19156, 358, 316, 2055, 73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8843, 1435, 3903, 288, 203, 3639, 2254, 5034, 12896, 273, 6197, 1282, 63, 3576, 18, 15330, 15533, 203, 3639, 6197, 1282, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 20688, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0xCcCDD8cea6EE2409eB92500b5436322A1A317A4B/sources/project_/contracts/Vault.sol
Getting the vaults by owner.
function GetMyVaults() public view returns(uint[] memory){ return vaultsByOwner[msg.sender]; }
3,243,458
[ 1, 19213, 326, 9229, 87, 635, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 968, 12062, 12003, 87, 1435, 1071, 1476, 1135, 12, 11890, 8526, 3778, 15329, 203, 3639, 327, 9229, 87, 858, 5541, 63, 3576, 18, 15330, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import './GenArt721Minter_DoodleLabs_MultiMinter.sol'; import './Strings.sol'; import './MerkleProof.sol'; interface IGenArt721Minter_DoodleLabs_Config { function getPurchaseManyLimit(uint256 projectId) external view returns (uint256 limit); function getState(uint256 projectId) external view returns (uint256 _state); function setStateFamilyCollectors(uint256 projectId) external; function setStateRedemption(uint256 projectId) external; function setStatePublic(uint256 projectId) external; } interface IGenArt721Minter_DoodleLabs_WhiteList { function getMerkleRoot(uint256 projectId) external view returns (bytes32 merkleRoot); function getWhitelisted(uint256 projectId, address user) external view returns (uint256 amount); function addWhitelist( uint256 projectId, address[] calldata users, uint256[] calldata amounts ) external; function increaseAmount( uint256 projectId, address to, uint256 quantity ) external; } contract GenArt721Minter_DoodleLabs_Custom_Sale is GenArt721Minter_DoodleLabs_MultiMinter { using SafeMath for uint256; event Redeem(uint256 projectId); // Must match what is on the GenArtMinterV2_State contract enum SaleState { FAMILY_COLLECTORS, REDEMPTION, PUBLIC } IGenArt721Minter_DoodleLabs_WhiteList public activeWhitelist; IGenArt721Minter_DoodleLabs_Config public minterState; modifier onlyWhitelisted() { require(genArtCoreContract.isWhitelisted(msg.sender), 'can only be set by admin'); _; } modifier notRedemptionState(uint256 projectId) { require( uint256(minterState.getState(projectId)) != uint256(SaleState.REDEMPTION), 'can not purchase in redemption phase' ); _; } modifier onlyRedemptionState(uint256 projectId) { require( uint256(minterState.getState(projectId)) == uint256(SaleState.REDEMPTION), 'not in redemption phase' ); _; } constructor(address _genArtCore, address _minterStateAddress) public GenArt721Minter_DoodleLabs_MultiMinter(_genArtCore) { minterState = IGenArt721Minter_DoodleLabs_Config(_minterStateAddress); } function getMerkleRoot(uint256 projectId) public view returns (bytes32 merkleRoot) { require(address(activeWhitelist) != address(0), 'Active whitelist not set'); return activeWhitelist.getMerkleRoot(projectId); } function getWhitelisted(uint256 projectId, address user) external view returns (uint256 amount) { require(address(activeWhitelist) != address(0), 'Active whitelist not set'); return activeWhitelist.getWhitelisted(projectId, user); } function setActiveWhitelist(address whitelist) public onlyWhitelisted { activeWhitelist = IGenArt721Minter_DoodleLabs_WhiteList(whitelist); } function purchase(uint256 projectId, uint256 quantity) public payable notRedemptionState(projectId) returns (uint256[] memory _tokenIds) { return purchaseTo(msg.sender, projectId, quantity); } function purchaseTo( address to, uint256 projectId, uint256 quantity ) public payable notRedemptionState(projectId) returns (uint256[] memory _tokenIds) { require( quantity <= minterState.getPurchaseManyLimit(projectId), 'Max purchase many limit reached' ); if ( uint256(minterState.getState(projectId)) == uint256(SaleState.FAMILY_COLLECTORS) && msg.value > 0 ) { require(false, 'ETH not accepted at this time'); } return _purchaseManyTo(to, projectId, quantity); } function redeem( uint256 projectId, uint256 quantity, uint256 allottedAmount, bytes32[] memory proof ) public payable onlyRedemptionState(projectId) returns (uint256[] memory _tokenIds) { return redeemTo(msg.sender, projectId, quantity, allottedAmount, proof); } function redeemTo( address to, uint256 projectId, uint256 quantity, uint256 allottedAmount, bytes32[] memory proof ) public payable onlyRedemptionState(projectId) returns (uint256[] memory _tokenIds) { require(address(activeWhitelist) != address(0), 'Active whitelist not set'); require( activeWhitelist.getWhitelisted(projectId, to).add(quantity) <= allottedAmount, 'Address has already claimed' ); string memory key = _addressToString(to); key = _appendStrings(key, Strings.toString(allottedAmount), Strings.toString(projectId)); bytes32 leaf = keccak256(abi.encodePacked(key)); require(MerkleProof.verify(proof, getMerkleRoot(projectId), leaf), 'Invalid proof'); uint256[] memory createdTokens = _purchaseManyTo(to, projectId, quantity); activeWhitelist.increaseAmount(projectId, to, quantity); emit Redeem(projectId); return createdTokens; } function _appendStrings( string memory a, string memory b, string memory c ) internal pure returns (string memory) { return string(abi.encodePacked(a, '::', b, '::', c)); } function _addressToString(address addr) private pure returns (string memory) { // From: https://www.reddit.com/r/ethdev/comments/qga46a/i_created_a_function_to_convert_address_to_string/ // Cast address to byte array bytes memory addressBytes = abi.encodePacked(addr); // Byte array for the new string bytes memory stringBytes = new bytes(42); // Assign first two bytes to '0x' stringBytes[0] = '0'; stringBytes[1] = 'x'; // Iterate over every byte in the array // Each byte contains two hex digits that gets individually converted // into their ASCII representation and added to the string for (uint256 i = 0; i < 20; i++) { // Convert hex to decimal values uint8 leftValue = uint8(addressBytes[i]) / 16; uint8 rightValue = uint8(addressBytes[i]) - 16 * leftValue; // Convert decimals to ASCII values bytes1 leftChar = leftValue < 10 ? bytes1(leftValue + 48) : bytes1(leftValue + 87); bytes1 rightChar = rightValue < 10 ? bytes1(rightValue + 48) : bytes1(rightValue + 87); // Add ASCII values to the string byte array stringBytes[2 * i + 3] = rightChar; stringBytes[2 * i + 2] = leftChar; // console.log(string(stringBytes)); } // Cast byte array to string and return return string(stringBytes); } }
Must match what is on the GenArtMinterV2_State contract
contract GenArt721Minter_DoodleLabs_Custom_Sale is GenArt721Minter_DoodleLabs_MultiMinter { using SafeMath for uint256; event Redeem(uint256 projectId); enum SaleState { FAMILY_COLLECTORS, REDEMPTION, PUBLIC } IGenArt721Minter_DoodleLabs_WhiteList public activeWhitelist; IGenArt721Minter_DoodleLabs_Config public minterState; modifier onlyWhitelisted() { require(genArtCoreContract.isWhitelisted(msg.sender), 'can only be set by admin'); _; } modifier notRedemptionState(uint256 projectId) { require( uint256(minterState.getState(projectId)) != uint256(SaleState.REDEMPTION), 'can not purchase in redemption phase' ); _; } modifier onlyRedemptionState(uint256 projectId) { require( uint256(minterState.getState(projectId)) == uint256(SaleState.REDEMPTION), 'not in redemption phase' ); _; } constructor(address _genArtCore, address _minterStateAddress) public GenArt721Minter_DoodleLabs_MultiMinter(_genArtCore) { minterState = IGenArt721Minter_DoodleLabs_Config(_minterStateAddress); } function getMerkleRoot(uint256 projectId) public view returns (bytes32 merkleRoot) { require(address(activeWhitelist) != address(0), 'Active whitelist not set'); return activeWhitelist.getMerkleRoot(projectId); } function getWhitelisted(uint256 projectId, address user) external view returns (uint256 amount) { require(address(activeWhitelist) != address(0), 'Active whitelist not set'); return activeWhitelist.getWhitelisted(projectId, user); } function setActiveWhitelist(address whitelist) public onlyWhitelisted { activeWhitelist = IGenArt721Minter_DoodleLabs_WhiteList(whitelist); } function purchase(uint256 projectId, uint256 quantity) public payable notRedemptionState(projectId) returns (uint256[] memory _tokenIds) { return purchaseTo(msg.sender, projectId, quantity); } function purchaseTo( address to, uint256 projectId, uint256 quantity ) public payable notRedemptionState(projectId) returns (uint256[] memory _tokenIds) { require( quantity <= minterState.getPurchaseManyLimit(projectId), 'Max purchase many limit reached' ); if ( uint256(minterState.getState(projectId)) == uint256(SaleState.FAMILY_COLLECTORS) && msg.value > 0 ) { require(false, 'ETH not accepted at this time'); } return _purchaseManyTo(to, projectId, quantity); } function purchaseTo( address to, uint256 projectId, uint256 quantity ) public payable notRedemptionState(projectId) returns (uint256[] memory _tokenIds) { require( quantity <= minterState.getPurchaseManyLimit(projectId), 'Max purchase many limit reached' ); if ( uint256(minterState.getState(projectId)) == uint256(SaleState.FAMILY_COLLECTORS) && msg.value > 0 ) { require(false, 'ETH not accepted at this time'); } return _purchaseManyTo(to, projectId, quantity); } function redeem( uint256 projectId, uint256 quantity, uint256 allottedAmount, bytes32[] memory proof ) public payable onlyRedemptionState(projectId) returns (uint256[] memory _tokenIds) { return redeemTo(msg.sender, projectId, quantity, allottedAmount, proof); } function redeemTo( address to, uint256 projectId, uint256 quantity, uint256 allottedAmount, bytes32[] memory proof ) public payable onlyRedemptionState(projectId) returns (uint256[] memory _tokenIds) { require(address(activeWhitelist) != address(0), 'Active whitelist not set'); require( activeWhitelist.getWhitelisted(projectId, to).add(quantity) <= allottedAmount, 'Address has already claimed' ); string memory key = _addressToString(to); key = _appendStrings(key, Strings.toString(allottedAmount), Strings.toString(projectId)); bytes32 leaf = keccak256(abi.encodePacked(key)); require(MerkleProof.verify(proof, getMerkleRoot(projectId), leaf), 'Invalid proof'); uint256[] memory createdTokens = _purchaseManyTo(to, projectId, quantity); activeWhitelist.increaseAmount(projectId, to, quantity); emit Redeem(projectId); return createdTokens; } function _appendStrings( string memory a, string memory b, string memory c ) internal pure returns (string memory) { return string(abi.encodePacked(a, '::', b, '::', c)); } function _addressToString(address addr) private pure returns (string memory) { bytes memory addressBytes = abi.encodePacked(addr); bytes memory stringBytes = new bytes(42); stringBytes[0] = '0'; stringBytes[1] = 'x'; for (uint256 i = 0; i < 20; i++) { uint8 leftValue = uint8(addressBytes[i]) / 16; uint8 rightValue = uint8(addressBytes[i]) - 16 * leftValue; bytes1 leftChar = leftValue < 10 ? bytes1(leftValue + 48) : bytes1(leftValue + 87); bytes1 rightChar = rightValue < 10 ? bytes1(rightValue + 48) : bytes1(rightValue + 87); stringBytes[2 * i + 3] = rightChar; stringBytes[2 * i + 2] = leftChar; } } function _addressToString(address addr) private pure returns (string memory) { bytes memory addressBytes = abi.encodePacked(addr); bytes memory stringBytes = new bytes(42); stringBytes[0] = '0'; stringBytes[1] = 'x'; for (uint256 i = 0; i < 20; i++) { uint8 leftValue = uint8(addressBytes[i]) / 16; uint8 rightValue = uint8(addressBytes[i]) - 16 * leftValue; bytes1 leftChar = leftValue < 10 ? bytes1(leftValue + 48) : bytes1(leftValue + 87); bytes1 rightChar = rightValue < 10 ? bytes1(rightValue + 48) : bytes1(rightValue + 87); stringBytes[2 * i + 3] = rightChar; stringBytes[2 * i + 2] = leftChar; } } return string(stringBytes); }
5,807,893
[ 1, 10136, 845, 4121, 353, 603, 326, 10938, 4411, 49, 2761, 58, 22, 67, 1119, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10938, 4411, 27, 5340, 49, 2761, 67, 3244, 369, 298, 48, 5113, 67, 3802, 67, 30746, 353, 10938, 4411, 27, 5340, 49, 2761, 67, 3244, 369, 298, 48, 5113, 67, 5002, 49, 2761, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 868, 24903, 12, 11890, 5034, 9882, 1769, 203, 203, 565, 2792, 348, 5349, 1119, 288, 203, 3639, 478, 2192, 25554, 67, 4935, 3918, 14006, 16, 203, 3639, 2438, 1639, 49, 3725, 16, 203, 3639, 17187, 203, 565, 289, 203, 203, 565, 467, 7642, 4411, 27, 5340, 49, 2761, 67, 3244, 369, 298, 48, 5113, 67, 13407, 682, 1071, 2695, 18927, 31, 203, 565, 467, 7642, 4411, 27, 5340, 49, 2761, 67, 3244, 369, 298, 48, 5113, 67, 809, 1071, 1131, 387, 1119, 31, 203, 203, 565, 9606, 1338, 18927, 329, 1435, 288, 203, 3639, 2583, 12, 4507, 4411, 4670, 8924, 18, 291, 18927, 329, 12, 3576, 18, 15330, 3631, 296, 4169, 1338, 506, 444, 635, 3981, 8284, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 486, 426, 19117, 375, 1119, 12, 11890, 5034, 9882, 13, 288, 203, 3639, 2583, 12, 203, 5411, 2254, 5034, 12, 1154, 387, 1119, 18, 588, 1119, 12, 4406, 548, 3719, 480, 2254, 5034, 12, 30746, 1119, 18, 862, 1639, 49, 3725, 3631, 203, 5411, 296, 4169, 486, 23701, 316, 283, 19117, 375, 6855, 11, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 426, 19117, 375, 1119, 12, 11890, 5034, 9882, 13, 2 ]
pragma solidity ^0.4.18; /** * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool); /** * @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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool); /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /*^ ^*/ } /* k to the N to the 0 | () (..) () \ .' kn0 thy token v 1.0 | __ rbl __ } .',,,,,,,,,,,,,,,,,,_____|_(\\\-----\\*/ contract kn0Token is StandardToken { string public name; // solium-disable-line uppercase string public symbol; // solium-disable-line uppercase uint8 public decimals; // solium-disable-line uppercase uint256 public aDropedThisWeek; uint256 lastWeek; uint256 decimate; uint256 weekly_limit; uint256 air_drop; mapping(address => uint256) airdroped; address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); require(newOwner != address(this)); OwnershipTransferred(owner, newOwner); owner = newOwner; update(); } /** * @dev kn0more */ function destroy() onlyOwner external { selfdestruct(owner); } function kn0Token(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) public { // 0xebbebae0fe balances[msg.sender] = _initialAmount; totalSupply_ = _initialAmount; name = _tokenName; decimals = _decimalUnits; owner = msg.sender; symbol = _tokenSymbol; Transfer(0x0, msg.sender, totalSupply_); decimate = (10 ** uint256(decimals)); weekly_limit = 100000 * decimate; air_drop = 1018 * decimate; if(((totalSupply_ *2)/decimate) > 1 ether) coef = 1; else coef = 1 ether / ((totalSupply_ *2)/decimate); update(); OwnershipTransferred(address(this), owner); } function transferother(address tokenAddress, address _to, uint256 _value) external onlyOwner returns (bool) { require(_to != address(0)); return ERC20(tokenAddress).transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); update(); return true; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // if no balance, see if eligible for airdrop instead if(balances[msg.sender] == 0) { uint256 qty = availableAirdrop(msg.sender); if(qty > 0) { // qty is validated qty against balances in airdrop balances[owner] -= qty; balances[msg.sender] += qty; Transfer(owner, _to, _value); update(); airdroped[msg.sender] = qty; aDropedThisWeek += qty; // airdrops don't trigger ownership change return true; } revert(); // no go } // existing balance if(balances[msg.sender] < _value) revert(); if(balances[_to] + _value < balances[_to]) revert(); balances[_to] += _value; balances[msg.sender] -= _value; Transfer(msg.sender, _to, _value); update(); return true; } function balanceOf(address who) public view returns (uint256 balance) { balance = balances[who]; if(balance == 0) return availableAirdrop(who); return balance; } /* * @dev check the faucet */ function availableAirdrop(address who) internal constant returns (uint256) { if(balances[owner] == 0) return 0; if(airdroped[who] > 0) return 0; // already used airdrop if (thisweek() > lastWeek || aDropedThisWeek < weekly_limit) { if(balances[owner] > air_drop) return air_drop; else return balances[owner]; } return 0; } function thisweek() private view returns (uint256) { return now / 1 weeks; } function getAirDropedToday() public view returns (uint256) { if (thisweek() > lastWeek) return 0; else return aDropedThisWeek; } function transferTo(address _to) external onlyOwner { require(_to != address(0)); assert(_to.send(this.balance)); } function () payable public { uint256 qty = calc(msg.value); if(qty > 0) { balances[msg.sender] += qty; balances[owner] -= qty; Transfer(owner, msg.sender, qty); update(); } else revert(); } uint256 public current; uint256 public coef; uint256 public ownerBalance; function update() internal { if(balances[owner] != ownerBalance) { current = (((totalSupply_ - balances[owner]) ** 2) / coef); ownerBalance = balances[owner]; } } function calc(uint256 value) public view returns (uint256) { if(balances[owner] == 0) return 0; uint256 x = (coef * (value + current)); uint256 qty = x; uint256 z = (x + 1) / 2; while (z < qty) { qty = z; z = (x / z + z) / 2; } uint256 worth = (qty - (totalSupply_ - balances[owner])); if(worth > balances[owner]) return balances[owner]; return worth; } }
* @dev Decrease the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol @param _spender The address which will spend the funds. @param _subtractedValue The amount of tokens to decrease the allowance by./
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /*^ ^*/
14,121,142
[ 1, 23326, 448, 326, 3844, 434, 2430, 716, 392, 3410, 2935, 358, 279, 17571, 264, 18, 6617, 537, 1410, 506, 2566, 1347, 2935, 63, 67, 87, 1302, 264, 65, 422, 374, 18, 2974, 15267, 2935, 460, 353, 7844, 358, 999, 333, 445, 358, 4543, 576, 4097, 261, 464, 2529, 3180, 326, 1122, 2492, 353, 1131, 329, 13, 6338, 9041, 355, 483, 18485, 3155, 18, 18281, 225, 389, 87, 1302, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 389, 1717, 1575, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 20467, 23461, 12, 2867, 389, 87, 1302, 264, 16, 2254, 389, 1717, 1575, 329, 620, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2254, 11144, 273, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 15533, 203, 565, 309, 261, 67, 1717, 1575, 329, 620, 405, 11144, 13, 288, 203, 1377, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 374, 31, 203, 1377, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 11144, 18, 1717, 24899, 1717, 1575, 329, 620, 1769, 203, 565, 289, 203, 565, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 19226, 203, 565, 327, 638, 31, 203, 225, 289, 12900, 1748, 66, 565, 3602, 5549, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /* The Polymath Security Token Registrar provides a way to lookup security token details from a single place and allows wizard creators to earn POLY fees by uploading to the registrar. */ import './interfaces/ISecurityTokenRegistrar.sol'; import './interfaces/IERC20.sol'; import './SecurityToken.sol'; /** * @title SecurityTokenRegistrar * @dev Contract use to register the security token on Polymath platform */ contract SecurityTokenRegistrar is ISecurityTokenRegistrar { string public VERSION = "2"; IERC20 public PolyToken; // Address of POLY token address public polyCustomersAddress; // Address of the polymath-core Customers contract address address public polyComplianceAddress; // Address of the polymath-core Compliance contract address struct NameSpaceData { address owner; uint256 fee; } // Security Token struct SecurityTokenData { // A structure that contains the specific info of each ST string nameSpace; string ticker; address owner; uint8 securityType; } mapping (string => NameSpaceData) nameSpaceData; // Mapping from nameSpace to owner / fee of nameSpace mapping (address => SecurityTokenData) securityTokens; // Mapping from securityToken address to data about the securityToken mapping (string => mapping (string => address)) tickers; // Mapping from nameSpace, to a mapping of ticker name to correspondong securityToken addresses event LogNewSecurityToken(string _nameSpace, string _ticker, address indexed _securityTokenAddress, address indexed _owner, uint8 _type); event LogNameSpaceCreated(string _nameSpace, address _owner, uint256 _fee); event LogNameSpaceChange(string _nameSpace, address _newOwner, uint256 _newFee); /** * @dev Constructor use to set the essentials addresses to facilitate * the creation of the security token */ function SecurityTokenRegistrar( address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public { require(_polyTokenAddress != address(0)); require(_polyCustomersAddress != address(0)); require(_polyComplianceAddress != address(0)); PolyToken = IERC20(_polyTokenAddress); polyCustomersAddress = _polyCustomersAddress; polyComplianceAddress = _polyComplianceAddress; } /** * @dev Creates a securityToken name space * @param _nameSpace Name space string * @param _fee Fee for this name space */ function createNameSpace(string _nameSpace, uint256 _fee) public { require(bytes(_nameSpace).length > 0); string memory nameSpace = lower(_nameSpace); require(nameSpaceData[nameSpace].owner == address(0)); nameSpaceData[nameSpace].owner = msg.sender; nameSpaceData[nameSpace].fee = _fee; LogNameSpaceCreated(nameSpace, msg.sender, _fee); } /** * @dev changes a string to lower case * @param _base string to change */ function lower(string _base) internal pure returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { bytes1 b1 = _baseBytes[i]; if (b1 >= 0x41 && b1 <= 0x5A) { b1 = bytes1(uint8(b1)+32); } _baseBytes[i] = b1; } return string(_baseBytes); } /** * @dev Changes name space fee * @param _nameSpace Name space string * @param _fee New fee for security token creation for this name space */ function changeNameSpace(string _nameSpace, uint256 _fee) public { string memory nameSpace = lower(_nameSpace); require(msg.sender == nameSpaceData[nameSpace].owner); nameSpaceData[nameSpace].fee = _fee; LogNameSpaceChange(nameSpace, msg.sender, _fee); } /** * @dev Creates a new Security Token and saves it to the registry * @param _nameSpaceName Name space for this security token * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _decimals Decimals value for token * @param _owner Ethereum public key address of the security token owner * @param _type Type of security being tokenized */ function createSecurityToken ( string _nameSpaceName, string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint8 _type ) external { require(_totalSupply > 0); NameSpaceData storage nameSpace = nameSpaceData[_nameSpaceName]; require(tickers[_nameSpaceName][_ticker] == address(0)); require(nameSpace.owner != address(0)); require(_owner != address(0)); require(bytes(_name).length > 0 && bytes(_ticker).length > 0); require(PolyToken.transferFrom(msg.sender, nameSpace.owner, nameSpace.fee)); address newSecurityTokenAddress = new SecurityToken( _name, _ticker, _totalSupply, _decimals, _owner, PolyToken, polyCustomersAddress, polyComplianceAddress ); tickers[_nameSpaceName][_ticker] = newSecurityTokenAddress; securityTokens[newSecurityTokenAddress] = SecurityTokenData( _nameSpaceName, _ticker, _owner, _type ); LogNewSecurityToken(_nameSpaceName, _ticker, newSecurityTokenAddress, _owner, _type); } ////////////////////////////// ///////// Get Functions ////////////////////////////// /** * @dev Get security token address by ticker name * @param _nameSpace Name space of the Scurity token * @param _ticker Symbol of the Scurity token * @return address _ticker */ function getSecurityTokenAddress(string _nameSpace, string _ticker) public view returns (address) { return tickers[_nameSpace][_ticker]; } /** * @dev Get Security token details by its ethereum address * @param _STAddress Security token address */ function getSecurityTokenData(address _STAddress) public view returns ( string, string, address, uint8 ) { return ( securityTokens[_STAddress].nameSpace, securityTokens[_STAddress].ticker, securityTokens[_STAddress].owner, securityTokens[_STAddress].securityType ); } /** * @dev Get the name space data * @param _nameSpace Name space string. */ function getNameSpaceData(string _nameSpace) public view returns(address, uint256) { string memory nameSpace = lower(_nameSpace); return ( nameSpaceData[nameSpace].owner, nameSpaceData[nameSpace].fee ); } }
Mapping from securityToken address to data about the securityToken
mapping (address => SecurityTokenData) securityTokens;
15,793,121
[ 1, 3233, 628, 4373, 1345, 1758, 358, 501, 2973, 326, 4373, 1345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 261, 2867, 516, 6036, 1345, 751, 13, 4373, 5157, 31, 5411, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xA0F1AD295DDF31e3c1aeE820e71D22Ff2bc35D20/sources/SimpleSale.sol
uint[2]{price, total_quantity}
{ mapping(address => uint) public _tkn_sale_quantity; mapping(address => uint[2]) public _tkn_sale_params; mapping(address => address) public _tkn_owners; mapping(address => uint) public balances; event SetTokenParams(address indexed token, address owner); event SetSaleParams(address indexed token, address owner, uint price, uint quantity); event CrowdSell(address indexed token, uint price, uint volume, address user); event Claim(address indexed receiver, uint amount); modifier tokenExists(address token) { require(_tkn_owners[token] != address(0x00), "the token not exists!"); _; } constructor() DSAuth() payable public { } function claim(uint amount) public { require(balances[msg.sender] > 0, "There is no award."); require(balances[msg.sender] >= amount, "The balance is insufficient."); balances[msg.sender] -= amount; uint userBalance = msg.sender.balance; msg.sender.transfer(amount); require(sub(msg.sender.balance, userBalance) == amount, "reentry!"); emit Claim(msg.sender, amount); } function crowdsell(address token) public payable tokenExists(token) { sell(token, msg.value, msg.sender); emit CrowdSell(token, _tkn_sale_params[token][0], msg.value, msg.sender); } function sell(address token, uint msgValue, address msgSender) private { require(_tkn_owners[token] != address(0x00) && _tkn_sale_params[token][0] > 0, "Not yet started, stay tuned."); address token_owner = _tkn_owners[token]; uint price = _tkn_sale_params[token][0]; uint total_quantity = _tkn_sale_params[token][1]; uint amount = mul(price, msgValue); require(add(_tkn_sale_quantity[token],amount) <= total_quantity, "sold out!"); require(DSToken(token).allowance(token_owner, address(this)) >= amount, "reach to uplimit of allowance."); DSToken(token).transferFrom(token_owner, msgSender, amount); _tkn_sale_quantity[token] = add(_tkn_sale_quantity[token], amount); balances[token_owner] = add(balances[token_owner], amount); } function setSaleParams(address token, address owner, uint[2] memory price_uplimit) public auth{ if(_tkn_owners[token] == address(0x00)) { _tkn_owners[token] = owner; } require(token != address(0x00), "incorrect token address."); require(owner != address(0x00), "incorrect token owner."); require(price_uplimit.length == 2 && price_uplimit[0] > 0 && price_uplimit[1] > 0, "They must be correct(price, sale quantity)."); DSToken(token).approve(owner, price_uplimit[1]); _tkn_sale_params[token] = price_uplimit; emit SetSaleParams(token, owner, price_uplimit[0], price_uplimit[1]); } function setSaleParams(address token, address owner, uint[2] memory price_uplimit) public auth{ if(_tkn_owners[token] == address(0x00)) { _tkn_owners[token] = owner; } require(token != address(0x00), "incorrect token address."); require(owner != address(0x00), "incorrect token owner."); require(price_uplimit.length == 2 && price_uplimit[0] > 0 && price_uplimit[1] > 0, "They must be correct(price, sale quantity)."); DSToken(token).approve(owner, price_uplimit[1]); _tkn_sale_params[token] = price_uplimit; emit SetSaleParams(token, owner, price_uplimit[0], price_uplimit[1]); } function getSaleParams(address token) public view returns (uint[2] memory) { return _tkn_sale_params[token]; } function getTokenOwner(address token) public view returns (address) { return _tkn_owners[token]; } function getSaleQuantity(address token) public view returns (uint) { return _tkn_sale_quantity[token]; } }
9,068,820
[ 1, 11890, 63, 22, 7073, 8694, 16, 2078, 67, 16172, 97, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 95, 203, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 389, 16099, 82, 67, 87, 5349, 67, 16172, 31, 203, 377, 203, 565, 2874, 12, 2867, 516, 2254, 63, 22, 5717, 1071, 389, 16099, 82, 67, 87, 5349, 67, 2010, 31, 203, 565, 2874, 12, 2867, 516, 1758, 13, 1071, 389, 16099, 82, 67, 995, 414, 31, 203, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 324, 26488, 31, 203, 203, 565, 871, 1000, 1345, 1370, 12, 2867, 8808, 1147, 16, 1758, 3410, 1769, 203, 565, 871, 1000, 30746, 1370, 12, 2867, 8808, 1147, 16, 1758, 3410, 16, 2254, 6205, 16, 2254, 10457, 1769, 203, 565, 871, 385, 492, 72, 55, 1165, 12, 2867, 8808, 1147, 16, 2254, 6205, 16, 2254, 3940, 16, 1758, 729, 1769, 203, 565, 871, 18381, 12, 2867, 8808, 5971, 16, 2254, 3844, 1769, 203, 203, 565, 9606, 1147, 4002, 12, 2867, 1147, 13, 203, 203, 203, 565, 288, 203, 3639, 2583, 24899, 16099, 82, 67, 995, 414, 63, 2316, 65, 480, 1758, 12, 20, 92, 713, 3631, 315, 5787, 1147, 486, 1704, 4442, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 8678, 1730, 1435, 8843, 429, 1071, 7010, 565, 288, 203, 203, 565, 289, 203, 203, 565, 445, 7516, 12, 11890, 3844, 13, 1071, 7010, 565, 288, 203, 3639, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 65, 405, 374, 16, 315, 9828, 353, 1158, 279, 2913, 1199, 1769, 203, 3639, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 65, 1545, 3844, 16, 315, 2 ]
./partial_match/1/0x5d3AC83258dC3d609e9a5740ECCF8F03812022Cf/sources/Shethereum.sol
buy tax applied if buy
if(automatedMarketMakerPairs[from]) {
16,030,692
[ 1, 70, 9835, 5320, 6754, 309, 30143, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 12, 5854, 362, 690, 3882, 278, 12373, 10409, 63, 2080, 5717, 288, 10792, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xb61fD7224CE4177Ba8C7Bcf21A3C7f8ff194b098/sources/browser/CoinBlackList.sol
@dev returns the revision number of the contract. Needs to be defined in the inherited class as a constant. @dev Returns true if and only if the function is running in the constructor 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.solium-disable-next-line
function getRevision() internal virtual pure returns (uint256); function isConstructor() private view returns (bool) { uint256 cs; assembly { cs := extcodesize(address()) } return cs == 0; }
663,212
[ 1, 6154, 326, 6350, 1300, 434, 326, 6835, 18, 29164, 358, 506, 2553, 316, 326, 12078, 667, 487, 279, 5381, 18, 225, 2860, 638, 309, 471, 1338, 309, 326, 445, 353, 3549, 316, 326, 3885, 1110, 7000, 554, 4271, 326, 963, 434, 326, 981, 4041, 316, 392, 1758, 16, 471, 1758, 1135, 326, 783, 1758, 18, 7897, 326, 981, 353, 4859, 486, 19357, 1347, 3549, 279, 3885, 16, 1281, 4271, 603, 2097, 981, 963, 903, 2824, 3634, 16, 10480, 518, 392, 11448, 4031, 358, 5966, 309, 279, 6835, 353, 3613, 16171, 578, 486, 18, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 26911, 1435, 2713, 5024, 16618, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 353, 6293, 1435, 3238, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 2873, 31, 203, 3639, 19931, 288, 203, 5411, 2873, 519, 1110, 7000, 554, 12, 2867, 10756, 203, 3639, 289, 203, 3639, 327, 2873, 422, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0xa6616Fc321E5Dc0ab8C79324Ca052E33617AD310/sources/contracts/donationMiner/DonationMinerImplementation.sol
* @notice Updates Staking address @param _newStaking address of new Staking contract/
function updateStaking(IStaking _newStaking) external override onlyOwner { address _oldStakingAddress = address(staking); staking = _newStaking; emit StakingUpdated(_oldStakingAddress, address(_newStaking)); }
13,251,901
[ 1, 5121, 934, 6159, 1758, 225, 389, 2704, 510, 6159, 1758, 434, 394, 934, 6159, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 510, 6159, 12, 45, 510, 6159, 389, 2704, 510, 6159, 13, 3903, 3849, 1338, 5541, 288, 203, 3639, 1758, 389, 1673, 510, 6159, 1887, 273, 1758, 12, 334, 6159, 1769, 203, 3639, 384, 6159, 273, 389, 2704, 510, 6159, 31, 203, 203, 3639, 3626, 934, 6159, 7381, 24899, 1673, 510, 6159, 1887, 16, 1758, 24899, 2704, 510, 6159, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; // This import is automatically injected by Remix import "remix_tests.sol"; // This import is required to use custom transaction context // Although it may fail compilation in 'Solidity Compiler' plugin // But it will work fine in 'Solidity Unit Testing' plugin import "remix_accounts.sol"; import "../contracts/Bonacrypto.sol"; // File name has to end with '_test.sol', this file can contain more than one testSuite contracts contract testSuite is BonaCrypto { /// More special functions are: 'beforeEach', 'beforeAll', 'afterEach' & 'afterAll' address payable public charityOneAddress = payable(0x1aE0EA34a72D944a8C7603FfB3eC30a6669E454C); address payable public charityTwoAddress = payable(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2); address payable public charityThreeAddress = payable(0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c); string public charityNameOne = "testCharityOne"; string public charityNameTwo = "testCharityTwo"; string public charityNameThree= "testCharityThree"; /// 'beforeAll' runs before all other tests function beforeAll() public { this.registerCharity(charityNameOne, charityOneAddress); this.registerCharity(charityNameTwo, charityTwoAddress); this.registerCharity(charityNameThree, charityThreeAddress); } string[] public expectedCharityNames; function checkRegisterCharity() public { expectedCharityNames.push("testCharityOne"); expectedCharityNames.push("testCharityTwo"); expectedCharityNames.push("testCharityThree"); string[] memory returnedCharityNames = this.viewCharityNames(); for (uint i = 0; i< 3; i++) { Assert.equal(returnedCharityNames[i], expectedCharityNames[i], "Verify charity names are identical."); } Assert.equal(expectedCharityNames.length, returnedCharityNames.length, "Verify size of charity names list is identical."); } function checkCharitySummary() public { (string memory charityName, address payable charityAddress, uint totalDonations) = this.viewCharitySummary(charityNameOne); Assert.equal(charityName, charityNameOne, "Verify charity name is correct."); Assert.equal(charityAddress, charityOneAddress, "Verify charity address is correct."); Assert.equal(totalDonations, 0, "Verify total donation amount is correct."); } /// #value: 100 function checkDonateToCharity() public payable { // Use 'Assert' methods: https://remix-ide.readthedocs.io/en/latest/assert_library.html Assert.equal(msg.value, 100, "Verify that value being sent is equal to 100"); this.donateToCharity(charityNameTwo, 100); (string memory charityName, address payable charityAddress, uint totalDonations) = this.viewCharitySummary(charityNameTwo); Assert.equal(charityName, charityNameTwo, "Verify charity name is correct."); Assert.equal(charityAddress, charityTwoAddress, "Verify charity address is correct."); Assert.equal(totalDonations, 100, "Verify total donation amount is correct."); } // Should abort with an error. Comment out charitySummary line to see if it passes. function checkRemoveCharity() public { // Verify that charityNameTwo has money donated. (string memory charityName, address payable charityAddress, uint totalDonations) = this.viewCharitySummary(charityNameTwo); Assert.equal(charityName, charityNameTwo, "Verify charity name is correct."); Assert.equal(charityAddress, charityTwoAddress, "Verify charity address is correct."); Assert.equal(totalDonations, 100, "Verify total donation amount is correct."); Assert.equal(this.viewCharityNames()[1], charityNameTwo, "Second element of charityNames list should be charityNameTwo."); // Remove charity. this.removeCharity(charityName); Assert.notEqual(this.viewCharityNames()[1], charityNameTwo, "Second element of charityNames should no longer be charityNameThree."); // (string memory removedCharityName, address payable removedCharityAddress, uint removedTotalDonations) = this.viewCharitySummary(charityNameTwo); } }
#value: 100 Use 'Assert' methods: https:remix-ide.readthedocs.io/en/latest/assert_library.html
function checkDonateToCharity() public payable { Assert.equal(msg.value, 100, "Verify that value being sent is equal to 100"); this.donateToCharity(charityNameTwo, 100); (string memory charityName, address payable charityAddress, uint totalDonations) = this.viewCharitySummary(charityNameTwo); Assert.equal(charityName, charityNameTwo, "Verify charity name is correct."); Assert.equal(charityAddress, charityTwoAddress, "Verify charity address is correct."); Assert.equal(totalDonations, 100, "Verify total donation amount is correct."); }
5,516,696
[ 1, 1132, 30, 2130, 2672, 296, 8213, 11, 2590, 30, 2333, 30, 2764, 697, 17, 831, 18, 25254, 329, 22280, 18, 1594, 19, 275, 19, 13550, 19, 11231, 67, 12083, 18, 2620, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 866, 22293, 340, 774, 2156, 560, 1435, 1071, 8843, 429, 288, 203, 540, 203, 3639, 5452, 18, 9729, 12, 3576, 18, 1132, 16, 2130, 16, 315, 8097, 716, 460, 3832, 3271, 353, 3959, 358, 2130, 8863, 203, 540, 203, 3639, 333, 18, 19752, 340, 774, 2156, 560, 12, 3001, 560, 461, 11710, 16, 2130, 1769, 203, 540, 203, 3639, 261, 1080, 3778, 1149, 560, 461, 16, 1758, 8843, 429, 1149, 560, 1887, 16, 2254, 2078, 22293, 1012, 13, 273, 333, 18, 1945, 2156, 560, 4733, 12, 3001, 560, 461, 11710, 1769, 203, 540, 203, 3639, 5452, 18, 9729, 12, 3001, 560, 461, 16, 1149, 560, 461, 11710, 16, 315, 8097, 1149, 560, 508, 353, 3434, 1199, 1769, 203, 3639, 5452, 18, 9729, 12, 3001, 560, 1887, 16, 1149, 560, 11710, 1887, 16, 315, 8097, 1149, 560, 1758, 353, 3434, 1199, 1769, 203, 3639, 5452, 18, 9729, 12, 4963, 22293, 1012, 16, 2130, 16, 315, 8097, 2078, 2727, 367, 3844, 353, 3434, 1199, 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 ]
./full_match/1/0x5682dC851C33adb48F6958a963A5d3Aa31F6f184/sources/contracts/router/libs/Structs.sol
@notice Returns a bitmask with only the given action set to True.
function mask(Action action) internal pure returns (uint256) { return 1 << uint256(action); }
4,844,546
[ 1, 1356, 279, 24941, 598, 1338, 326, 864, 1301, 444, 358, 1053, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3066, 12, 1803, 1301, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 404, 2296, 2254, 5034, 12, 1128, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xc106e720761D71a8E9a8fA45ED18D1Ab85D27832/sources/src/Kong/Distributor.sol
@notice Set reward rate for rebase @param _rewardRate New rate
function setRate(uint256 _rewardRate) external onlyOwner { require(_rewardRate <= rateDenominator, "Rate cannot exceed denominator"); rate = _rewardRate; }
17,105,991
[ 1, 694, 19890, 4993, 364, 283, 1969, 225, 389, 266, 2913, 4727, 225, 1166, 4993, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 444, 4727, 12, 11890, 5034, 389, 266, 2913, 4727, 13, 3903, 1338, 5541, 288, 203, 202, 202, 6528, 24899, 266, 2913, 4727, 1648, 4993, 8517, 26721, 16, 315, 4727, 2780, 9943, 15030, 8863, 203, 202, 202, 5141, 273, 389, 266, 2913, 4727, 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 ]
./full_match/1/0x4E3eB34950f1246ACFFCF79DDF9E4435fc785dbE/sources/contracts/TAYC2.sol
reserve some Trippy Apes for team
contract TAYC is ERC721, Ownable { using SafeMath for uint256; string public TAYC_PROVENANCE = ""; string public LICENSE_TEXT = ""; uint256 public constant trippyApePrice = 0.042 * 10 ** 18; uint256 public constant MAX_TRIPPY_APES = 6969; uint public trippyApeReserve = 1000; uint public constant maxTrippyApePurchase = 20; bool public saleIsActive = false; bool licenseLocked = false; mapping(uint => string) public trippyApeNames; mapping(uint => uint) public bundlePrices; event trippyApeNameChange(address _by, uint _tokenId, string _name); event licenseIsLocked(string _licenseText); constructor() public ERC721("Trippy Ape Yacht Club", "TAYC") { bundlePrices[5] = 0.04 * 10 ** 18; bundlePrices[10] = 0.0369 * 10 ** 18; bundlePrices[20] = 0.035 * 10 ** 18; } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function reserveTrippyApe(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= trippyApeReserve, "Not enough reserve left for the team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } trippyApeReserve = trippyApeReserve.sub(_reserveAmount); } function reserveTrippyApe(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= trippyApeReserve, "Not enough reserve left for the team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } trippyApeReserve = trippyApeReserve.sub(_reserveAmount); } function setBaseURI(string memory _baseURI) public onlyOwner { _setBaseURI(_baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function tokensOfOwner(address _owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); for (uint256 index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokensOfOwner(address _owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); for (uint256 index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } } else { function tokensOfOwner(address _owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); for (uint256 index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "Choose a Trippy Ape within range!"); return LICENSE_TEXT; } function lockLicense() public onlyOwner { licenseLocked = true; emit licenseIsLocked(LICENSE_TEXT); } function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked!"); LICENSE_TEXT = _license; } function mintTrippyApe(uint _numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint a Trippy Ape..."); require(_numberOfTokens > 0 && _numberOfTokens <= maxTrippyApePurchase, "Can only mint 20 Trippy Apes at a time!"); require(totalSupply().add(_numberOfTokens) <= MAX_TRIPPY_APES, "Not enough Trippy Apes available for minting..."); require(msg.value >= trippyApePrice.mul(_numberOfTokens), "Ether value sent is not enough..."); for (uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TRIPPY_APES) { _safeMint(msg.sender, mintIndex); } } } function mintTrippyApe(uint _numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint a Trippy Ape..."); require(_numberOfTokens > 0 && _numberOfTokens <= maxTrippyApePurchase, "Can only mint 20 Trippy Apes at a time!"); require(totalSupply().add(_numberOfTokens) <= MAX_TRIPPY_APES, "Not enough Trippy Apes available for minting..."); require(msg.value >= trippyApePrice.mul(_numberOfTokens), "Ether value sent is not enough..."); for (uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TRIPPY_APES) { _safeMint(msg.sender, mintIndex); } } } function mintTrippyApe(uint _numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint a Trippy Ape..."); require(_numberOfTokens > 0 && _numberOfTokens <= maxTrippyApePurchase, "Can only mint 20 Trippy Apes at a time!"); require(totalSupply().add(_numberOfTokens) <= MAX_TRIPPY_APES, "Not enough Trippy Apes available for minting..."); require(msg.value >= trippyApePrice.mul(_numberOfTokens), "Ether value sent is not enough..."); for (uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TRIPPY_APES) { _safeMint(msg.sender, mintIndex); } } } function mintTrippyApeFree(uint _numberOfTokens) public { require(saleIsActive, "Sale must be active to mint a Trippy Ape..."); require(_numberOfTokens > 0 && _numberOfTokens <= maxTrippyApePurchase, "Can only mint 20 Trippy Apes at a time!"); require(totalSupply().add(_numberOfTokens) <= MAX_TRIPPY_APES, "Not enough Trippy Apes available for minting..."); for (uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TRIPPY_APES) { _safeMint(msg.sender, mintIndex); } } } function mintTrippyApeFree(uint _numberOfTokens) public { require(saleIsActive, "Sale must be active to mint a Trippy Ape..."); require(_numberOfTokens > 0 && _numberOfTokens <= maxTrippyApePurchase, "Can only mint 20 Trippy Apes at a time!"); require(totalSupply().add(_numberOfTokens) <= MAX_TRIPPY_APES, "Not enough Trippy Apes available for minting..."); for (uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TRIPPY_APES) { _safeMint(msg.sender, mintIndex); } } } function mintTrippyApeFree(uint _numberOfTokens) public { require(saleIsActive, "Sale must be active to mint a Trippy Ape..."); require(_numberOfTokens > 0 && _numberOfTokens <= maxTrippyApePurchase, "Can only mint 20 Trippy Apes at a time!"); require(totalSupply().add(_numberOfTokens) <= MAX_TRIPPY_APES, "Not enough Trippy Apes available for minting..."); for (uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TRIPPY_APES) { _safeMint(msg.sender, mintIndex); } } } function changeTrippyApeName(uint _tokenId, string memory _name) public { require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this Trippy Ape!"); require(sha256(bytes(_name)) != sha256(bytes(trippyApeNames[_tokenId]))); trippyApeNames[_tokenId] = _name; emit trippyApeNameChange(msg.sender, _tokenId, _name); } function viewTrippyApeName(uint _tokenId) public view returns(string memory) { require(_tokenId < totalSupply(), "Choose a Trippy Ape within range."); return trippyApeNames[_tokenId]; } function trippyApeNamesOfOwner(address _owner) external view returns(string[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); for (uint index = 0; index < tokenCount; index++) { result[index] = trippyApeNames[tokenOfOwnerByIndex(_owner, index)]; } return result; } } function trippyApeNamesOfOwner(address _owner) external view returns(string[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); for (uint index = 0; index < tokenCount; index++) { result[index] = trippyApeNames[tokenOfOwnerByIndex(_owner, index)]; } return result; } } } else { function trippyApeNamesOfOwner(address _owner) external view returns(string[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); for (uint index = 0; index < tokenCount; index++) { result[index] = trippyApeNames[tokenOfOwnerByIndex(_owner, index)]; } return result; } } }
8,463,510
[ 1, 455, 6527, 2690, 10000, 84, 2074, 1716, 281, 364, 5927, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 399, 5255, 39, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 225, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 1071, 399, 5255, 39, 67, 3373, 58, 1157, 4722, 273, 1408, 31, 203, 565, 533, 1071, 511, 2871, 23396, 67, 5151, 273, 1408, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 20654, 2074, 37, 347, 5147, 273, 374, 18, 3028, 22, 380, 1728, 2826, 6549, 31, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 6566, 6584, 61, 67, 37, 1423, 55, 273, 20963, 8148, 31, 203, 203, 565, 2254, 1071, 20654, 2074, 37, 347, 607, 6527, 273, 4336, 31, 203, 565, 2254, 1071, 5381, 943, 16148, 2074, 37, 347, 23164, 273, 4200, 31, 203, 203, 565, 1426, 1071, 272, 5349, 2520, 3896, 273, 629, 31, 203, 565, 1426, 8630, 8966, 273, 629, 31, 203, 203, 565, 2874, 12, 11890, 516, 533, 13, 1071, 20654, 2074, 37, 347, 1557, 31, 203, 565, 2874, 12, 11890, 516, 2254, 13, 1071, 3440, 31862, 31, 203, 203, 565, 871, 20654, 2074, 37, 347, 461, 3043, 12, 2867, 389, 1637, 16, 2254, 389, 2316, 548, 16, 533, 389, 529, 1769, 203, 565, 871, 8630, 2520, 8966, 12, 1080, 389, 12687, 1528, 1769, 203, 203, 203, 565, 3885, 1435, 1071, 4232, 39, 27, 5340, 2932, 16148, 2074, 432, 347, 1624, 497, 88, 3905, 373, 3113, 315, 56, 5255, 39, 7923, 288, 203, 3639, 3440, 31862, 63, 25, 65, 273, 374, 18, 3028, 380, 1728, 2826, 6549, 31, 203, 3639, 3440, 31862, 63, 2 ]
//Address: 0x2f97dc94317760c7204e72a5bd058c10b409dc12 //Contract name: BCSCrowdsale //Balance: 0 Ether //Verification Date: 10/8/2017 //Transacion Count: 12 // CODE STARTS HERE /************************************************************************* * This contract has been merged with solidify * https://github.com/tiesnetwork/solidify *************************************************************************/ pragma solidity ^0.4.10; /************************************************************************* * import "../token/ITokenPool.sol" : start *************************************************************************/ /************************************************************************* * import "./ERC20StandardToken.sol" : start *************************************************************************/ /************************************************************************* * import "./IERC20Token.sol" : start *************************************************************************/ /**@dev ERC20 compliant token interface. https://theethereum.wiki/w/index.php/ERC20_Token_Standard https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public constant returns (string _name) { _name; } function symbol() public constant returns (string _symbol) { _symbol; } function decimals() public constant returns (uint8 _decimals) { _decimals; } function totalSupply() constant returns (uint total) {total;} function balanceOf(address _owner) constant returns (uint balance) {_owner; balance;} function allowance(address _owner, address _spender) constant returns (uint remaining) {_owner; _spender; remaining;} function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /************************************************************************* * import "./IERC20Token.sol" : end *************************************************************************/ /************************************************************************* * import "../common/SafeMath.sol" : start *************************************************************************/ /**dev Utility methods for overflow-proof arithmetic operations */ contract SafeMath { /**dev Returns the sum of a and b. Throws an exception if it exceeds uint256 limits*/ function safeAdd(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /**dev Returns the difference of a and b. Throws an exception if a is less than b*/ function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(a >= b); return a - b; } /**dev Returns the product of a and b. Throws an exception if it exceeds uint256 limits*/ function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0) || (z / x == y)); return z; } function safeDiv(uint256 x, uint256 y) internal returns (uint256) { assert(y != 0); return x / y; } }/************************************************************************* * import "../common/SafeMath.sol" : end *************************************************************************/ /**@dev Standard ERC20 compliant token implementation */ contract ERC20StandardToken is IERC20Token, SafeMath { string public name; string public symbol; uint8 public decimals; //tokens already issued uint256 tokensIssued; //balances for each account mapping (address => uint256) balances; //one account approves the transfer of an amount to another account mapping (address => mapping (address => uint256)) allowed; function ERC20StandardToken() { } // //IERC20Token implementation // function totalSupply() constant returns (uint total) { total = tokensIssued; } function balanceOf(address _owner) constant returns (uint balance) { balance = balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool) { require(_to != address(0)); // safeSub inside doTransfer will throw if there is not enough balance. doTransfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); // Check for allowance is not needed because sub(_allowance, _value) will throw if this condition is not met allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); // safeSub inside doTransfer will throw if there is not enough balance. doTransfer(_from, _to, _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { remaining = allowed[_owner][_spender]; } // // Additional functions // /**@dev Gets real token amount in the smallest token units */ function getRealTokenAmount(uint256 tokens) constant returns (uint256) { return tokens * (uint256(10) ** decimals); } // // Internal functions // function doTransfer(address _from, address _to, uint256 _value) internal { balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); } }/************************************************************************* * import "./ERC20StandardToken.sol" : end *************************************************************************/ /**@dev Token pool that manages its tokens by designating trustees */ contract ITokenPool { /**@dev Token to be managed */ ERC20StandardToken public token; /**@dev Changes trustee state */ function setTrustee(address trustee, bool state); // these functions aren't abstract since the compiler emits automatically generated getter functions as external /**@dev Returns remaining token amount */ function getTokenAmount() constant returns (uint256 tokens) {tokens;} }/************************************************************************* * import "../token/ITokenPool.sol" : end *************************************************************************/ /************************************************************************* * import "../token/ReturnTokenAgent.sol" : start *************************************************************************/ /************************************************************************* * import "../common/Manageable.sol" : start *************************************************************************/ /************************************************************************* * import "../common/Owned.sol" : start *************************************************************************/ contract Owned { address public owner; function Owned() { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /**@dev allows transferring the contract ownership. */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); owner = _newOwner; } } /************************************************************************* * import "../common/Owned.sol" : end *************************************************************************/ ///A token that have an owner and a list of managers that can perform some operations ///Owner is always a manager too contract Manageable is Owned { event ManagerSet(address manager, bool state); mapping (address => bool) public managers; function Manageable() Owned() { managers[owner] = true; } /**@dev Allows execution by managers only */ modifier managerOnly { assert(managers[msg.sender]); _; } function transferOwnership(address _newOwner) public ownerOnly { super.transferOwnership(_newOwner); managers[_newOwner] = true; managers[msg.sender] = false; } function setManager(address manager, bool state) ownerOnly { managers[manager] = state; ManagerSet(manager, state); } }/************************************************************************* * import "../common/Manageable.sol" : end *************************************************************************/ /************************************************************************* * import "../token/ReturnableToken.sol" : start *************************************************************************/ ///Token that when sent to specified contract (returnAgent) invokes additional actions contract ReturnableToken is Manageable, ERC20StandardToken { /**@dev List of return agents */ mapping (address => bool) public returnAgents; function ReturnableToken() {} /**@dev Sets new return agent */ function setReturnAgent(ReturnTokenAgent agent) managerOnly { returnAgents[address(agent)] = true; } /**@dev Removes return agent from list */ function removeReturnAgent(ReturnTokenAgent agent) managerOnly { returnAgents[address(agent)] = false; } function doTransfer(address _from, address _to, uint256 _value) internal { super.doTransfer(_from, _to, _value); if (returnAgents[_to]) { ReturnTokenAgent(_to).returnToken(_from, _value); } } }/************************************************************************* * import "../token/ReturnableToken.sol" : end *************************************************************************/ ///Returnable tokens receiver contract ReturnTokenAgent is Manageable { //ReturnableToken public returnableToken; /**@dev List of returnable tokens in format token->flag */ mapping (address => bool) public returnableTokens; /**@dev Allows only token to execute method */ //modifier returnableTokenOnly {require(msg.sender == address(returnableToken)); _;} modifier returnableTokenOnly {require(returnableTokens[msg.sender]); _;} /**@dev Executes when tokens are transferred to this */ function returnToken(address from, uint256 amountReturned); /**@dev Sets token that can call returnToken method */ function setReturnableToken(ReturnableToken token) managerOnly { returnableTokens[address(token)] = true; } /**@dev Removes token that can call returnToken method */ function removeReturnableToken(ReturnableToken token) managerOnly { returnableTokens[address(token)] = false; } }/************************************************************************* * import "../token/ReturnTokenAgent.sol" : end *************************************************************************/ /************************************************************************* * import "./IInvestRestrictions.sol" : start *************************************************************************/ /** @dev Restrictions on investment */ contract IInvestRestrictions is Manageable { /**@dev Returns true if investmet is allowed */ function canInvest(address investor, uint amount, uint tokensLeft) constant returns (bool result) { investor; amount; result; tokensLeft; } /**@dev Called when investment was made */ function investHappened(address investor, uint amount) managerOnly {} }/************************************************************************* * import "./IInvestRestrictions.sol" : end *************************************************************************/ /************************************************************************* * import "./ICrowdsaleFormula.sol" : start *************************************************************************/ /**@dev Abstraction of crowdsale token calculation function */ contract ICrowdsaleFormula { /**@dev Returns amount of tokens that can be bought with given weiAmount */ function howManyTokensForEther(uint256 weiAmount) constant returns(uint256 tokens, uint256 excess) { weiAmount; tokens; excess; } /**@dev Returns how many tokens left for sale */ function tokensLeft() constant returns(uint256 _left) { _left;} }/************************************************************************* * import "./ICrowdsaleFormula.sol" : end *************************************************************************/ /**@dev Crowdsale base contract, used for PRE-TGE and TGE stages * Token holder should also be the owner of this contract */ contract BCSCrowdsale is ICrowdsaleFormula, Manageable, SafeMath { enum State {Unknown, BeforeStart, Active, FinishedSuccess, FinishedFailure} ITokenPool public tokenPool; IInvestRestrictions public restrictions; //restrictions on investment address public beneficiary; //address of contract to collect ether uint256 public startTime; //unit timestamp of start time uint256 public endTime; //unix timestamp of end date uint256 public minimumGoalInWei; //TODO or in tokens uint256 public tokensForOneEther; //how many tokens can you buy for 1 ether uint256 realAmountForOneEther; //how many tokens can you buy for 1 ether * 10**decimals uint256 bonusPct; //additional percent of tokens bool public withdrew; //true if beneficiary already withdrew uint256 public weiCollected; uint256 public tokensSold; bool public failure; //true if some error occurred during crowdsale mapping (address => uint256) public investedFrom; //how many wei specific address invested mapping (address => uint256) public tokensSoldTo; //how many tokens sold to specific addreess mapping (address => uint256) public overpays; //overpays for send value excesses // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount); // Refund was processed for a contributor event Refund(address investor, uint weiAmount); // Overpay refund was processed for a contributor event OverpayRefund(address investor, uint weiAmount); /**@dev Crowdsale constructor, can specify startTime as 0 to start crowdsale immediately _tokensForOneEther - doesn't depend on token decimals */ function BCSCrowdsale( ITokenPool _tokenPool, IInvestRestrictions _restrictions, address _beneficiary, uint256 _startTime, uint256 _durationInHours, uint256 _goalInWei, uint256 _tokensForOneEther, uint256 _bonusPct) { require(_beneficiary != 0x0); require(address(_tokenPool) != 0x0); require(_durationInHours > 0); require(_tokensForOneEther > 0); tokenPool = _tokenPool; beneficiary = _beneficiary; restrictions = _restrictions; if (_startTime == 0) { startTime = now; } else { startTime = _startTime; } endTime = (_durationInHours * 1 hours) + startTime; tokensForOneEther = _tokensForOneEther; minimumGoalInWei = _goalInWei; bonusPct = _bonusPct; weiCollected = 0; tokensSold = 0; failure = false; withdrew = false; realAmountForOneEther = tokenPool.token().getRealTokenAmount(tokensForOneEther); } function() payable { invest(); } function invest() payable { require(canInvest(msg.sender, msg.value)); uint256 excess; uint256 weiPaid = msg.value; uint256 tokensToBuy; (tokensToBuy, excess) = howManyTokensForEther(weiPaid); require(tokensToBuy <= tokensLeft() && tokensToBuy > 0); if (excess > 0) { overpays[msg.sender] = safeAdd(overpays[msg.sender], excess); weiPaid = safeSub(weiPaid, excess); } investedFrom[msg.sender] = safeAdd(investedFrom[msg.sender], weiPaid); tokensSoldTo[msg.sender] = safeAdd(tokensSoldTo[msg.sender], tokensToBuy); tokensSold = safeAdd(tokensSold, tokensToBuy); weiCollected = safeAdd(weiCollected, weiPaid); if(address(restrictions) != 0x0) { restrictions.investHappened(msg.sender, msg.value); } require(tokenPool.token().transferFrom(tokenPool, msg.sender, tokensToBuy)); Invested(msg.sender, weiPaid, tokensToBuy); } /**@dev Returns true if it is possible to invest */ function canInvest(address investor, uint256 amount) constant returns(bool) { return getState() == State.Active && (address(restrictions) == 0x0 || restrictions.canInvest(investor, amount, tokensLeft())); } /**@dev ICrowdsaleFormula override */ function howManyTokensForEther(uint256 weiAmount) constant returns(uint256 tokens, uint256 excess) { uint256 bpct = getCurrentBonusPct(); uint256 maxTokens = (tokensLeft() * 100) / (100 + bpct); tokens = weiAmount * realAmountForOneEther / 1 ether; if (tokens > maxTokens) { tokens = maxTokens; } excess = weiAmount - tokens * 1 ether / realAmountForOneEther; tokens = (tokens * 100 + tokens * bpct) / 100; } /**@dev Returns current bonus percent [0-100] */ function getCurrentBonusPct() constant returns (uint256) { return bonusPct; } /**@dev Returns how many tokens left for sale */ function tokensLeft() constant returns(uint256) { return tokenPool.getTokenAmount(); } /**@dev Returns funds that should be sent to beneficiary */ function amountToBeneficiary() constant returns (uint256) { return weiCollected; } /**@dev Returns crowdsale current state */ function getState() constant returns (State) { if (failure) { return State.FinishedFailure; } if (now < startTime) { return State.BeforeStart; } else if (now < endTime && tokensLeft() > 0) { return State.Active; } else if (weiCollected >= minimumGoalInWei || tokensLeft() <= 0) { return State.FinishedSuccess; } else { return State.FinishedFailure; } } /**@dev Allows investors to withdraw funds and overpays in case of crowdsale failure */ function refund() { require(getState() == State.FinishedFailure); uint amount = investedFrom[msg.sender]; if (amount > 0) { investedFrom[msg.sender] = 0; weiCollected = safeSub(weiCollected, amount); msg.sender.transfer(amount); Refund(msg.sender, amount); } } /**@dev Allows investor to withdraw overpay */ function withdrawOverpay() { uint amount = overpays[msg.sender]; overpays[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { OverpayRefund(msg.sender, amount); } else { overpays[msg.sender] = amount; //restore funds in case of failed send } } } /**@dev Transfers all collected funds to beneficiary*/ function transferToBeneficiary() { require(getState() == State.FinishedSuccess && !withdrew); withdrew = true; uint256 amount = amountToBeneficiary(); beneficiary.transfer(amount); Refund(beneficiary, amount); } /**@dev Makes crowdsale failed/ok, for emergency reasons */ function makeFailed(bool state) managerOnly { failure = state; } /**@dev Sets new beneficiary */ function changeBeneficiary(address newBeneficiary) managerOnly { beneficiary = newBeneficiary; } }
*@dev Sets new return agent */
function setReturnAgent(ReturnTokenAgent agent) managerOnly { returnAgents[address(agent)] = true; }
1,004,095
[ 1, 2785, 394, 327, 4040, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 990, 3630, 12, 990, 1345, 3630, 4040, 13, 3301, 3386, 288, 203, 3639, 327, 23400, 63, 2867, 12, 5629, 25887, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.10; import "@rari-capital/solmate/src/tokens/ERC721.sol"; import "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; import "./Ownable.sol"; import "./IERC721.sol"; import "./Strings.sol"; error DoesNotExist(); error NoTokensLeft(); error NotEnoughETH(); error AssertionError(); error NotTokenOwner(); error MintNotActive(); error MintAlreadyActive(); error MintLimitPerTx(); contract xApe721 is Ownable, ERC721 { using Strings for uint256; uint256 public constant TOTAL_SUPPLY = 10_000; uint256 public constant PRICE_PER_MINT = 0.05 ether; uint256 public constant MAX_MINT_PER_TX = 20; bool public mintActive; uint256 public totalSupply; string public baseURI; IERC721 public oldContract = IERC721(0x090b1DE324fEA5f0A0B4226101Db645819102629); address private teamWallet = 0xC7639015cB3da4FDd1C8c1925B22fB32ae133dAb; address private dev1Wallet = 0x29c36265c63fE0C3d024b2E4d204b49deeFdD671; address private dev2Wallet = 0x0c4618FfbE21f926d040043976457d0a489ea360; uint256 private devMints = 0; constructor( string memory name, string memory symbol, string memory _baseURI, address _oldContract, address _dev1Wallet, address _dev2Wallet, address _teamWallet ) payable ERC721(name, symbol) { baseURI = _baseURI; if (_oldContract != address(0)) { oldContract = IERC721(_oldContract); } if (_dev1Wallet != address(0)) { dev1Wallet = _dev1Wallet; } if (_dev2Wallet != address(0)) { dev2Wallet = _dev2Wallet; } if (_teamWallet != address(0)) { teamWallet = _teamWallet; } } modifier onlyTeamWallet() { require(msg.sender == teamWallet, "Not callable except by team wallet"); _; } modifier onlyDev() { require( (msg.sender == dev1Wallet || msg.sender == dev2Wallet), "Only callable by devs"); _; } modifier devMintLimit(uint256 amount) { require(devMints + amount <= 6, "Devs only promised 3 free mints each"); _; } function mint(uint16 amount) external payable { if (!mintActive) revert MintNotActive(); if (totalSupply + amount >= TOTAL_SUPPLY) revert NoTokensLeft(); if (msg.value < amount * PRICE_PER_MINT) revert NotEnoughETH(); if (amount > MAX_MINT_PER_TX) revert MintLimitPerTx(); unchecked { for (uint16 index = 0; index < amount; index++) { uint256 newId = _getNextUnusedID(totalSupply++); _mint(msg.sender, newId); } } } function claim(uint256 tokenId) external payable { if (_ownsOldToken(msg.sender, tokenId)) { // Transfering into this contract effectively burns the old // token as there is no way to get it out of here oldContract.safeTransferFrom(msg.sender, address(this), tokenId); _mint(msg.sender, tokenId); return; } revert NotTokenOwner(); } function claimAll() external payable { uint256[] memory ownedTokens = oldContract.getPhunksBelongingToOwner(msg.sender); uint256 length = ownedTokens.length; // gas saving for (uint256 i; i < length; ++i) { if (ownerOf[ownedTokens[i]] == address(0)) { // Has not been claimed yet // Transfering into this contract effectively burns the // old token as there is no way to get it out of here oldContract.safeTransferFrom(msg.sender, address(this), ownedTokens[i]); _mint(msg.sender, ownedTokens[i]); } } } function _ownsOldToken(address account, uint256 tokenId) internal view returns(bool) { try oldContract.ownerOf(tokenId) returns (address tokenOwner) { return account == tokenOwner; } catch Error(string memory /*reason*/) { return false; } } function _getNextUnusedID(uint256 currentSupply) internal view returns (uint256) { uint256 newId = 10000 + currentSupply; // IDs start at 10000 // Using 10 iterations instead of while loop as it is known // that the maximum contiguous group of successive IDs in // the original contract is 7 (14960-14966). Cannot have unbounded gas usage for (uint256 i; i < 10; ++i) { if (ownerOf[newId] != address(0)) { // Token is owned in this contract newId++; continue; } try oldContract.ownerOf(newId) returns (address) { // Token is owned in the old contract // ownerOf always reverts if the token isn't owned // so no need for zero check here newId++; continue; } catch Error(string memory /*reason*/) { return newId; } } revert AssertionError(); } function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) revert DoesNotExist(); return string(abi.encodePacked(baseURI, id.toString())); } function withdraw() external onlyTeamWallet() { SafeTransferLib.safeTransferETH(teamWallet, address(this).balance); } function devMint(uint16 amount) external onlyDev() devMintLimit(amount) { if (totalSupply + amount >= TOTAL_SUPPLY) revert NoTokensLeft(); unchecked { for (uint16 index = 0; index < amount; index++) { uint256 newId = _getNextUnusedID(totalSupply++); _mint(msg.sender, newId); devMints++; } } } function pauseMint() external { if (msg.sender != _owner) revert NotOwner(); if (!mintActive) revert MintNotActive(); mintActive = false; } function startMint() external { if (msg.sender != _owner) revert NotOwner(); if (mintActive) revert MintAlreadyActive(); mintActive = true; } function supportsInterface(bytes4 interfaceId) public pure override returns (bool) { return interfaceId == 0x7f5828d0 || // ERC165 Interface ID for ERC173 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f || // ERC165 Interface ID for ERC165 interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC721Metadata interfaceId == 0x150b7a02; // ERC721 Receiver } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4) { return 0x150b7a02; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern, minimalist, and gas efficient ERC-721 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) /// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC. abstract contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /*/////////////////////////////////////////////////////////////// METADATA STORAGE/LOGIC //////////////////////////////////////////////////////////////*/ string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC721 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED"); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } function _burn(uint256 id) internal virtual { address owner = ownerOf[id]; require(ownerOf[id] != address(0), "NOT_MINTED"); // Ownership check above ensures no underflow. unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } /*/////////////////////////////////////////////////////////////// INTERNAL SAFE MINT LOGIC //////////////////////////////////////////////////////////////*/ function _safeMint(address to, uint256 id) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function _safeMint( address to, uint256 id, bytes memory data ) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } } /// @notice A generic interface for a contract which properly accepts ERC721 tokens. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) interface ERC721TokenReceiver { function onERC721Received( address operator, address from, uint256 id, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.10; error NotOwner(); abstract contract Ownable { address internal _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { _owner = msg.sender; } function owner() external view returns (address) { return _owner; } function transferOwnership(address _newOwner) external { if (msg.sender != _owner) revert NotOwner(); _owner = _newOwner; } function renounceOwnership() public { if (msg.sender != _owner) revert NotOwner(); _owner = address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 { /** * @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; // Original 0xApes contract specifc function getPhunksBelongingToOwner(address _owner) external view returns (uint256[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.10; library Strings { /** * @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); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } }
IDs start at 10000
uint256 newId = 10000 + currentSupply;
6,441,698
[ 1, 5103, 787, 622, 12619, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 27598, 273, 12619, 397, 783, 3088, 1283, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: contracts/lib/ECRecovery.sol /** * @title Eliptic curve signature operations * * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 * */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * @dev and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", hash )); } } // File: contracts/MultiSigDocument.sol contract IMultipleSignatory { function isEnoughSignature() public view returns (bool); function changeNumberOfRquiredSignatures(uint newRequiredNumber) public; function isVerifier(address addr) public view returns (bool); function isIssuer(address addr) public view returns (bool); function signDocument(bytes memory sig) public; function verifyDocument() public; function revokeDocument() public; function deleteDocument() public; function submitDeleteConfirmation(bool deleted, bytes memory sig) public; function getProofHash() public view returns (bytes32); function isValidDataHash(bytes32 hash, bytes _sig) internal view returns(bool); function isVerified() public view returns (bool); event Verification(address indexed verifier, address indexed doc); event Revocation(address indexed verifier, address indexed doc); event LogInvalidSignatureSubmission(address submitter); event LogNumOfRequiredSignatureChanged(uint oldNum, uint indexed newNum); event DocumentSigned(address indexed document, address indexed verifier); event DeleteDocumentConfirmation(address indexed document, address indexed verifier); } contract MultiSigDocument is IMultipleSignatory { using ECRecovery for bytes32; uint public constant MAX_SIGNER_COUNT = 10; uint public createdTime; //Timestamp uint public validDays = 365; //days uint public expiration = 2**256-1; // Default to infinite time - Timestamp bool public autoActivation = false; bool public verified = false; uint public allowModificationDeadline = 0; //Timestamp uint public numOfRequiredSignature; address public verifier; address public issuer; // Keep track of signers // uint32 public signerCount = 0; // include issuer uint8 public finalizedSigConfirmations = 0; uint8 public deleteConfirmations = 0; mapping (address => SignerProperty) public signerProperties; address[] signers = new address[](MAX_SIGNER_COUNT); struct SignerProperty { bool IsSigner; bool IsSigned; bool DeleteConfirmed; } modifier validRequirement(uint _signerCount, uint _numOfRequiredSignature, uint _validDays, uint _allowRevocationPeriodInDays) { require(_signerCount > 0 && _signerCount <= MAX_SIGNER_COUNT); require(_numOfRequiredSignature > 0 && _numOfRequiredSignature < MAX_SIGNER_COUNT); require(_validDays > 0 && _allowRevocationPeriodInDays < _validDays); _; } modifier signerDoesNotExist(address addr) { require(!signerProperties[addr].IsSigner); _; } // GDPR modifier allowDelete() { require(checkDeleteConfirmations()); _; } modifier beforeModificationDeadline() { require(now < allowModificationDeadline); _; } modifier afterModificationDeadline() { require(now > allowModificationDeadline); _; } modifier signerExists(address addr) { require(signerProperties[addr].IsSigner); _; } modifier onlyVerifier() { require(verifier == msg.sender); _; } modifier isExpired() { require(now > expiration); _; } modifier onlyIssuer() { require(issuer == msg.sender); _; } modifier notVerified() { assert(!verified); _; } constructor(address[] _signer, address _verifier, uint _numOfRequiredSignature, uint _validDays, uint _allowRevocationPeriodInDays) public validRequirement( _signer.length, _numOfRequiredSignature, _validDays, _allowRevocationPeriodInDays) { for (uint i=0; i<_signer.length; i++) { assert(_signer[i] != address(0) && _signer[i] != msg.sender); signerProperties[_signer[i]].IsSigner = true; signers.push(_signer[i]); } issuer = msg.sender; signerProperties[issuer].IsSigner = true; signers.push(issuer); verifier = _verifier; createdTime = now; validDays = _validDays == 0 ? 0 : _validDays; expiration = _validDays == 0 ? expiration : (createdTime + (validDays * 1 days)); numOfRequiredSignature = _numOfRequiredSignature + 1; allowModificationDeadline = createdTime + (_allowRevocationPeriodInDays * 1 days); } function isVerifier(address addr) public view returns (bool) { return (verifier == addr); } function isIssuer(address addr) public view returns (bool) { return (issuer == addr); } function submitDeleteConfirmation(bool confirmedDeleted, bytes memory sig) public { address recoveredAddr = keccak256(abi.encodePacked(address(this), confirmedDeleted)) .toEthSignedMessageHash() .recover(sig); assert(signerProperties[recoveredAddr].IsSigner); assert(signerProperties[recoveredAddr].IsSigned); signerProperties[recoveredAddr].DeleteConfirmed = confirmedDeleted; emit DeleteDocumentConfirmation(address(this), verifier); } function changeNumberOfRquiredSignatures(uint newRequiredNumber) public onlyVerifier() beforeModificationDeadline() notVerified() { require(newRequiredNumber > 0 && newRequiredNumber < signers.length); emit LogNumOfRequiredSignatureChanged(numOfRequiredSignature, newRequiredNumber); numOfRequiredSignature = newRequiredNumber; } function signDocument(bytes memory sig) public { if(!isValidSignature(sig)) { emit LogInvalidSignatureSubmission(msg.sender); revert('Submitting signature is invalid!'); } address recoveredAddr = keccak256( abi.encodePacked(address(this), verifier, getProofHash())) .toEthSignedMessageHash() .recover(sig); signerProperties[recoveredAddr].IsSigned = true; finalizedSigConfirmations++; emit DocumentSigned(address(this), verifier); } /** * TODO: Overide this function */ function getProofHash() public view returns (bytes32) { return keccak256(abi.encodePacked("")); } /** * @dev is the signature of `this + verifier + documentProofHash` from a signer? * @return bool */ function isValidSignature(bytes _sig) internal view returns (bool) { return isValidDataHash( keccak256(abi.encodePacked(address(this), verifier, getProofHash())), _sig ); } /** * @dev internal function to convert a hash to an eth signed message * and then recover the signature and check it against the bouncer role * @return bool */ function isValidDataHash(bytes32 hash, bytes _sig) internal view returns (bool) { address recoveredAddr = hash .toEthSignedMessageHash() .recover(_sig); return signerProperties[recoveredAddr].IsSigner; } function isEnoughSignature() public view returns (bool) { if(!signerProperties[issuer].IsSigned) return false; if(finalizedSigConfirmations < numOfRequiredSignature) return false; return true; } function checkDeleteConfirmations() public view returns (bool) { uint8 _tmpCount = 0; for (uint8 i=0; i < signers.length; i++) { if (signerProperties[signers[i]].DeleteConfirmed == true) _tmpCount++; } if(_tmpCount < numOfRequiredSignature) { return false; } return true; } function verifyDocument() public notVerified() onlyVerifier() afterModificationDeadline() { /* * TODO: Please extend this function by adding validation of signature */ assert(isEnoughSignature()); verified = true; emit Verification(msg.sender, address(this)); } function deleteDocument() public isExpired() allowDelete() signerExists(msg.sender) { /* * TODO: Please extend this function */ selfdestruct(issuer); } function isVerified() public view returns (bool) { return verified; } function revokeDocument() public isExpired() onlyVerifier() { verified = false; emit Revocation(verifier, address(this)); } function () public { //fallback } } // File: contracts/lib/strings.sol /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.4.14; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal pure returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal pure returns (string) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal pure returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal pure returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal pure returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal pure returns (slice) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } event log_bytemask(bytes32 mask); // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal pure returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal pure returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal pure returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal pure returns (string) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal pure returns (string) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // File: contracts/MultiSigDocumentWithStorage.sol contract ILockableStorage { function getAllKeys() public view returns(string); function addEntry(string memory key, string value) public; function getEntry(string memory key) public view returns (string); function updateEntry(string memory key, string value) public; function deleteEntry(string memory key) public; // Delete Value only function changeWritePermission(bool _writable, string memory key) public; event EntrySet(address indexed document, string entryKey); event EntryDeleted(address indexed document, string entryKey); event EntryUpdateRequest(address indexed document, string entryKey); } contract MultiSigDocumentWithStorage is MultiSigDocument, ILockableStorage { using strings for *; string constant NULL_CHAR = '\u0000'; //Data mapping (bytes32 => string) public entryStorage; // A long string contains all of the key allKeysInString /* string public allKeysInString; */ string[] public entryKeys; bool public writable = false; constructor( address[] signers, address verifier, uint8 required, uint effectiveDurationInDay, uint offset, bytes buffer ) MultiSigDocument(signers, verifier, required, effectiveDurationInDay, 30) public { setData(offset, buffer); } modifier entryNotExisted(string memory entryKey) { assert(bytes(entryStorage[entryKey.toSlice().keccak()]).length == 0); _; } modifier entryExisted(string memory entryKey) { assert(bytes(entryStorage[entryKey.toSlice().keccak()]).length != 0); _; } modifier isWritable() { assert(writable); _; } event LogString(uint l1, string s1, string s2); function setData(uint offset, bytes memory buffer) internal { while(offset > 0) { uint size; assembly { size := mload(add(buffer, offset)) } string memory strKey = new string(size); writeBytesToString(offset, buffer, bytes(strKey)); offset -= sizeOfString(strKey); assembly { size := mload(add(buffer, offset)) } string memory strVal = new string(size); writeBytesToString(offset, buffer, bytes(strVal)); offset -= sizeOfString(strVal); string memory strippedVal = strVal.toSlice().split(NULL_CHAR.toSlice()).toString(); entryStorage[keccak256(abi.encodePacked(strKey))] = strippedVal; entryKeys.push(strKey.toSlice().split(NULL_CHAR.toSlice()).toString()); } } function sizeOfString(string _in) internal pure returns(uint _size) { _size = bytes(_in).length / 32; if(bytes(_in).length % 32 != 0) _size++; _size++; _size *= 32; } function writeBytesToString(uint offset, bytes buffer, bytes output) internal pure { uint size = 32; assembly { let word_count size := mload(add(buffer, offset)) word_count := add(div(size,32), 1) if gt(mod(size, 32), 0) { word_count := add(word_count,1) } for { let i := 0 } lt(i, word_count) { i := add(i, 1) } { mstore(add(output,mul(i, 0x20)),mload(add(buffer,offset))) offset:= sub(offset, 32) } } } function getAllKeys() public view returns (string memory out1) { for(uint32 i = 0 ; i < entryKeys.length; i++) { out1 = out1.toSlice().concat( entryKeys[i].toSlice()).toSlice().concat(";".toSlice()); } } function getAllValues() public view returns (string memory out1) { for(uint32 i = 0 ; i < entryKeys.length; i++) { string memory s = entryStorage[entryKeys[i].toSlice().keccak()]; out1 = out1.toSlice().concat(s.toSlice()); } } function getProofHash() public view returns (bytes32) { return keccak256(abi.encodePacked(getAllValues())); } function addEntry(string memory key, string value) public isWritable() entryNotExisted(key) beforeModificationDeadline() onlyIssuer() { entryStorage[key.toSlice().keccak()] = value; entryKeys.push(key); emit EntrySet(address(this), key); } function updateEntry(string memory key, string value) public isWritable() beforeModificationDeadline() entryExisted(key) onlyIssuer() { entryStorage[key.toSlice().keccak()] = value; emit EntrySet(address(this), key); } function deleteEntry(string memory key) public beforeModificationDeadline() isWritable() onlyIssuer() { delete entryStorage[key.toSlice().keccak()]; emit EntryDeleted(address(this), key); } function changeWritePermission(bool _writable, string memory key) public onlyVerifier() { writable = _writable; emit EntryUpdateRequest(address(this), key); } function getEntry(string memory key) public view returns (string) { return entryStorage[key.toSlice().keccak()]; } function getKKHash(string memory s1) public view returns (bytes32) { return keccak256(abi.encodePacked(entryStorage[s1.toSlice().keccak()])); } function deleteDocument() public isExpired() allowDelete() signerExists(msg.sender) { selfdestruct(issuer); } function deleteData() internal { } function () public { // fallback } }
* @dev is the signature of `this + verifier + documentProofHash` from a signer? @return bool/
function isValidSignature(bytes _sig) internal view returns (bool) { return isValidDataHash( keccak256(abi.encodePacked(address(this), verifier, getProofHash())), _sig ); }
1,792,078
[ 1, 291, 326, 3372, 434, 1375, 2211, 397, 20130, 397, 1668, 20439, 2310, 68, 628, 279, 10363, 35, 327, 1426, 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, 225, 445, 4908, 5374, 12, 3890, 389, 7340, 13, 203, 565, 2713, 203, 565, 1476, 203, 565, 1135, 261, 6430, 13, 203, 225, 288, 203, 565, 327, 4908, 751, 2310, 12, 203, 1377, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2867, 12, 2211, 3631, 20130, 16, 3570, 792, 2310, 10756, 3631, 203, 1377, 389, 7340, 203, 565, 11272, 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 ]
./full_match/11155111/0x1259Aa9FaCd0feFB5a91da65682C7EDD51608D4b/sources/contracts/base/FallbackManager.sol
* @title Fallback Manager - A contract managing fallback calls made to this contract @author Richard Meissner - @rmeissner/ keccak256("fallback_manager.handler.address")
abstract contract FallbackManager is SelfAuthorized { event ChangedFallbackHandler(address indexed handler); bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5; pragma solidity >=0.7.0 <0.9.0; function internalSetFallbackHandler(address handler) internal { If a fallback handler is set to self, then the following attack vector is opened: Imagine we have a function like this: function withdraw() internal authorized { withdrawalAddress.call.value(address(this).balance)(""); } If the fallback method is triggered, the fallback handler appends the msg.sender address to the calldata and calls the fallback handler. A potential attacker could call a Safe with the 3 bytes signature of a withdraw function. Since 3 bytes do not create a valid signature, the call would end in a fallback handler. Since it appends the msg.sender address to the calldata, the attacker could craft an address where the first 3 bytes of the previous calldata + the first byte of the address make up a valid function signature. The subsequent call would result in unsanctioned access to Safe's internal protected methods. For some reason, solidity matches the first 4 bytes of the calldata to a function signature, regardless if more data follow these 4 bytes. require(handler != address(this), "GS400"); bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; assembly { sstore(slot, handler) } } function internalSetFallbackHandler(address handler) internal { If a fallback handler is set to self, then the following attack vector is opened: Imagine we have a function like this: function withdraw() internal authorized { withdrawalAddress.call.value(address(this).balance)(""); } If the fallback method is triggered, the fallback handler appends the msg.sender address to the calldata and calls the fallback handler. A potential attacker could call a Safe with the 3 bytes signature of a withdraw function. Since 3 bytes do not create a valid signature, the call would end in a fallback handler. Since it appends the msg.sender address to the calldata, the attacker could craft an address where the first 3 bytes of the previous calldata + the first byte of the address make up a valid function signature. The subsequent call would result in unsanctioned access to Safe's internal protected methods. For some reason, solidity matches the first 4 bytes of the calldata to a function signature, regardless if more data follow these 4 bytes. require(handler != address(this), "GS400"); bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; assembly { sstore(slot, handler) } } function internalSetFallbackHandler(address handler) internal { If a fallback handler is set to self, then the following attack vector is opened: Imagine we have a function like this: function withdraw() internal authorized { withdrawalAddress.call.value(address(this).balance)(""); } If the fallback method is triggered, the fallback handler appends the msg.sender address to the calldata and calls the fallback handler. A potential attacker could call a Safe with the 3 bytes signature of a withdraw function. Since 3 bytes do not create a valid signature, the call would end in a fallback handler. Since it appends the msg.sender address to the calldata, the attacker could craft an address where the first 3 bytes of the previous calldata + the first byte of the address make up a valid function signature. The subsequent call would result in unsanctioned access to Safe's internal protected methods. For some reason, solidity matches the first 4 bytes of the calldata to a function signature, regardless if more data follow these 4 bytes. require(handler != address(this), "GS400"); bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; assembly { sstore(slot, handler) } } function setFallbackHandler(address handler) public authorized { internalSetFallbackHandler(handler); emit ChangedFallbackHandler(handler); } fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; assembly { function allocate(length) -> pos { pos := mload(0x40) mstore(0x40, add(pos, length)) } let handler := sload(slot) if iszero(handler) { return(0, 0) } let calldataPtr := allocate(calldatasize()) calldatacopy(calldataPtr, 0, calldatasize()) mstore(senderPtr, shl(96, caller())) let returnDataPtr := allocate(returndatasize()) returndatacopy(returnDataPtr, 0, returndatasize()) if iszero(success) { revert(returnDataPtr, returndatasize()) } return(returnDataPtr, returndatasize()) } } fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; assembly { function allocate(length) -> pos { pos := mload(0x40) mstore(0x40, add(pos, length)) } let handler := sload(slot) if iszero(handler) { return(0, 0) } let calldataPtr := allocate(calldatasize()) calldatacopy(calldataPtr, 0, calldatasize()) mstore(senderPtr, shl(96, caller())) let returnDataPtr := allocate(returndatasize()) returndatacopy(returnDataPtr, 0, returndatasize()) if iszero(success) { revert(returnDataPtr, returndatasize()) } return(returnDataPtr, returndatasize()) } } fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; assembly { function allocate(length) -> pos { pos := mload(0x40) mstore(0x40, add(pos, length)) } let handler := sload(slot) if iszero(handler) { return(0, 0) } let calldataPtr := allocate(calldatasize()) calldatacopy(calldataPtr, 0, calldatasize()) mstore(senderPtr, shl(96, caller())) let returnDataPtr := allocate(returndatasize()) returndatacopy(returnDataPtr, 0, returndatasize()) if iszero(success) { revert(returnDataPtr, returndatasize()) } return(returnDataPtr, returndatasize()) } } fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; assembly { function allocate(length) -> pos { pos := mload(0x40) mstore(0x40, add(pos, length)) } let handler := sload(slot) if iszero(handler) { return(0, 0) } let calldataPtr := allocate(calldatasize()) calldatacopy(calldataPtr, 0, calldatasize()) mstore(senderPtr, shl(96, caller())) let returnDataPtr := allocate(returndatasize()) returndatacopy(returnDataPtr, 0, returndatasize()) if iszero(success) { revert(returnDataPtr, returndatasize()) } return(returnDataPtr, returndatasize()) } } let senderPtr := allocate(20) let success := call(gas(), handler, 0, calldataPtr, add(calldatasize(), 20), 0, 0) fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; assembly { function allocate(length) -> pos { pos := mload(0x40) mstore(0x40, add(pos, length)) } let handler := sload(slot) if iszero(handler) { return(0, 0) } let calldataPtr := allocate(calldatasize()) calldatacopy(calldataPtr, 0, calldatasize()) mstore(senderPtr, shl(96, caller())) let returnDataPtr := allocate(returndatasize()) returndatacopy(returnDataPtr, 0, returndatasize()) if iszero(success) { revert(returnDataPtr, returndatasize()) } return(returnDataPtr, returndatasize()) } } }
3,822,658
[ 1, 12355, 8558, 300, 432, 6835, 30632, 5922, 4097, 7165, 358, 333, 6835, 225, 534, 1354, 1060, 7499, 1054, 1224, 300, 632, 86, 3501, 1054, 1224, 19, 417, 24410, 581, 5034, 2932, 16471, 67, 4181, 18, 4176, 18, 2867, 7923, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 21725, 1318, 353, 18954, 15341, 288, 203, 565, 871, 27707, 12355, 1503, 12, 2867, 8808, 1838, 1769, 203, 203, 565, 1731, 1578, 2713, 5381, 478, 4685, 8720, 67, 19937, 67, 19009, 67, 55, 1502, 56, 273, 374, 92, 26, 71, 29, 69, 26, 71, 24, 69, 5520, 22, 5193, 73, 6418, 329, 21, 8522, 8643, 72, 3707, 5877, 4700, 72, 29126, 2138, 69, 8875, 7301, 19192, 29, 6669, 69, 24, 5718, 26, 71, 8148, 23, 70, 11180, 2733, 2643, 72, 25, 31, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 411, 20, 18, 29, 18, 20, 31, 203, 565, 445, 2713, 694, 12355, 1503, 12, 2867, 1838, 13, 2713, 288, 203, 5411, 971, 279, 5922, 1838, 353, 444, 358, 365, 16, 1508, 326, 3751, 13843, 3806, 353, 10191, 30, 203, 5411, 19158, 558, 732, 1240, 279, 445, 3007, 333, 30, 203, 5411, 445, 598, 9446, 1435, 2713, 10799, 288, 203, 7734, 598, 9446, 287, 1887, 18, 1991, 18, 1132, 12, 2867, 12, 2211, 2934, 12296, 13, 2932, 8863, 203, 5411, 289, 203, 203, 5411, 971, 326, 5922, 707, 353, 10861, 16, 326, 5922, 1838, 8144, 326, 1234, 18, 15330, 1758, 358, 326, 745, 892, 471, 4097, 326, 5922, 1838, 18, 203, 5411, 432, 8555, 13843, 264, 3377, 745, 279, 14060, 598, 326, 890, 1731, 3372, 434, 279, 598, 9446, 445, 18, 7897, 890, 1731, 741, 486, 752, 279, 923, 3372, 16, 203, 5411, 326, 745, 4102, 679, 316, 279, 5922, 1838, 18, 7897, 518, 8144, 326, 1234, 18, 2 ]
pragma solidity 0.6.10; 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; } } //Note that assert() is now used because the try/catch mechanism in the DepoToken.sol contract does not revert on failure with require(); /** * @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; assert(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) { assert(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; assert(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) { assert(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) { assert(b != 0/*, errorMessage*/); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { assert(_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 { assert(newOwner != address(0)/*, "Ownable: new owner is the zero address"*/); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Contract used to calculate stakes. Unused currently. abstract contract CalculatorInterface { function calculateNumTokens(uint256 balance, uint256 daysStaked, address stakerAddress, uint256 totalSupply) public virtual returns (uint256); function randomness() public view virtual returns (uint256); } // Parent token contract, see DepoToken.sol abstract contract DepoToken { function balanceOf(address account) public view virtual returns (uint256); function _burn(address account, uint256 amount) external virtual; } /** * @dev Implementation of Depo: * Depo is a price-reactive cryptocurrency. * That is, the inflation rate of the token is wholly dependent on its market activity. * Minting does not happen when the price is less than the day prior. * When the price is greater than the day prior, the inflation for that day is * a function of its price, percent increase, volume, any positive price streaks, * and the amount of time any given holder has been holding. * In the first iteration, the dev team acts as the price oracle, but in the future, we plan to integrate a Chainlink price oracle. * This contract is the staking contract for the project and is upgradeable by the owner. */ contract DepoStaking is Ownable { using SafeMath for uint256; // A 'staker' is an individual who holds the minimum staking amount in his address. struct staker { uint startTimestamp; // When the staking started in unix time (block.timesamp) uint lastTimestamp; // When the last staking reward was claimed in unix time (block.timestamp) } struct update { // Price updateState uint timestamp; // Last update timestamp, unix time uint numerator; // Numerator of percent change (1% increase = 1/100) uint denominator; // Denominator of percent change uint price; // In USD. 0001 is $0.001, 1000 is $1.000, 1001 is $1.001, etc uint volume; // In whole USD (100 = $100) } DepoToken public token; // ERC20 token contract that uses this upgradeable contract for staking and burning modifier onlyToken() { assert(_msgSender() == address(token)/*, "Caller must be DEPO token contract."*/); _; } modifier onlyNextStakingContract() { // Caller must be the next staking contract assert(_msgSender() == _nextStakingContract); _; } mapping (address => staker) private _stakers; // Mapping of all individuals staking/holding tokens greater than minStake mapping (address => string) private _whitelist; // Mapping of all addresses that do not burn tokens on receive and send (generally other smart contracts). Mapping of address to reason (string) mapping (address => uint256) private _blacklist; // Mapping of all addresses that receive a specific token burn when receiving. Mapping of address to percent burn (uint256) bool private _enableBurns; // Enable burning on transfer or fee on transfer bool private _priceTarget1Hit; // Price targets, defined in updateState() bool private _priceTarget2Hit; address public _uniswapV2Pair; // Uniswap pair address, done for fees on Uniswap sells uint8 private _uniswapSellerBurnPercent; // Uniswap sells pay a fee bool private _enableUniswapDirectBurns; // Enable seller fees on Uniswap uint256 private _minStake; // Minimum amount to stake uint8 private _minStakeDurationDays; // Minimum amount of time to claim staking rewards uint8 private _minPercentIncrease; // Minimum percent increase to enable rewards for the day. 10 = 1.0%, 100 = 10.0% uint256 private _inflationAdjustmentFactor; // Factor to adjust the amount of rewards (inflation) to be given out in a single day uint256 private _streak; // Number of days in a row that the price has increased update public _lastUpdate; // latest price update CalculatorInterface private _externalCalculator; // external calculator to calculate the number of tokens given several variables (defined above). Currently unused address private _nextStakingContract; // Next staking contract deployed. Used for migrating staker state. bool private _useExternalCalc; // self-explanatory bool private _freeze; // freeze all transfers in an emergency bool private _enableHoldersDay; // once a month, holders receive a nice bump event StakerRemoved(address StakerAddress); // Staker was removed due to balance dropping below _minStake event StakerAdded(address StakerAddress); // Staker was added due to balance increasing abolve _minStake event StakesUpdated(uint Amount); // Staking rewards were claimed event MassiveCelebration(); // Happens when price targets are hit event Transfer(address indexed from, address indexed to, uint256 value); // self-explanatory constructor (DepoToken Token) public { token = Token; _minStake = 500E18; _inflationAdjustmentFactor = 100; _streak = 0; _minStakeDurationDays = 0; _useExternalCalc = false; _uniswapSellerBurnPercent = 5; _enableBurns = false; _freeze = false; _minPercentIncrease = 10; // 1.0% min increase _enableUniswapDirectBurns = false; } // The owner (or price oracle) will call this function to update the price on days the coin is positive. On negative days, no update is made. function updateState(uint numerator, uint denominator, uint256 price, uint256 volume) external onlyOwner { // when chainlink is integrated a separate contract will call this function (onlyOwner state will be changed as well) require(numerator > 0 && denominator > 0 && price > 0 && volume > 0, "Parameters cannot be negative or zero"); if (numerator < 2 && denominator == 100 || numerator < 20 && denominator == 1000) { require(mulDiv(1000, numerator, denominator) >= _minPercentIncrease, "Increase must be at least _minPercentIncrease to count"); } uint8 daysSinceLastUpdate = uint8((block.timestamp - _lastUpdate.timestamp) / 86400); // We calculate time since last price update in days. Overflow is possible but incredibly unlikely. if (daysSinceLastUpdate == 0) { // We should only update once per day, but block timestamps can vary _streak++; } else if (daysSinceLastUpdate == 1) { _streak++; // If we updated yesterday and today, we are on a streak } else { _streak = 1; } if (price >= 1000 && _priceTarget1Hit == false) { // 1000 = $1.00 _priceTarget1Hit = true; _streak = 50; emit MassiveCelebration(); } else if (price >= 10000 && _priceTarget2Hit == false) { // It is written, so it shall be done _priceTarget2Hit = true; _streak = 100; _minStake = 100E18; // Need $1000 to stake emit MassiveCelebration(); } _lastUpdate = update(block.timestamp, numerator, denominator, price, volume); } function resetStakeTime() external { // This is only necessary if a new staking contract is deployed. Resets 0 timestamp to block.timestamp uint balance = token.balanceOf(msg.sender); assert(balance > 0); assert(balance >= _minStake); staker memory thisStaker = _stakers[msg.sender]; if (thisStaker.lastTimestamp == 0) { _stakers[msg.sender].lastTimestamp = block.timestamp; } if (thisStaker.startTimestamp == 0) { _stakers[msg.sender].startTimestamp = block.timestamp; } } // This is used by the next staking contract to migrate staker state function resetStakeTimeMigrateState(address addr) external onlyNextStakingContract returns (uint256 startTimestamp, uint256 lastTimestamp) { startTimestamp = _stakers[addr].startTimestamp; lastTimestamp = _stakers[addr].lastTimestamp; _stakers[addr].lastTimestamp = block.timestamp; _stakers[addr].startTimestamp = block.timestamp; } function updateMyStakes(address stakerAddress, uint256 balance, uint256 totalSupply) external onlyToken returns (uint256) { // This function is called by the token contract. Holders call the function on the token contract every day the price is positive to claim rewards. assert(balance > 0); staker memory thisStaker = _stakers[stakerAddress]; assert(thisStaker.lastTimestamp > 0/*,"Error: your last timestamp cannot be zero."*/); // We use asserts now so that we fail on errors due to try/catch in token contract. assert(thisStaker.startTimestamp > 0/*,"Error: your start timestamp cannot be zero."*/); assert((block.timestamp.sub(_lastUpdate.timestamp)) / 86400 == 0/*, "Stakes must be updated the same day of the latest update"*/); // We recognize that block.timestamp can be gamed by miners to some extent, but from what we undertand block timestamps *cannot be before the last block* by consensus rules, otherwise they will fork the chain assert(block.timestamp > thisStaker.lastTimestamp/*, "Error: block timestamp is not greater than your last timestamp!"*/); assert(_lastUpdate.timestamp > thisStaker.lastTimestamp/*, "Error: you can only update stakes once per day. You also cannot update stakes on the same day that you purchased them."*/); uint daysStaked = block.timestamp.sub(thisStaker.startTimestamp) / 86400; // Calculate time staked in days assert(daysStaked >= _minStakeDurationDays/*, "You must stake for at least minStakeDurationDays to claim rewards"*/); assert(balance >= _minStake/*, "You must have a balance of at least minStake to claim rewards"*/); uint numTokens = calculateNumTokens(balance, daysStaked, stakerAddress, totalSupply); // Calls token calculation function - this is either an external contract or the function in this contract if (_enableHoldersDay && daysStaked >= 30) { numTokens = mulDiv(balance, daysStaked, 600); // Once a month, holders get a nice bump } _stakers[stakerAddress].lastTimestamp = block.timestamp; // Again, this can be gamed to some extent, but *cannot be before the last block* emit StakesUpdated(numTokens); return numTokens; // Token contract will add these tokens to the balance of stakerAddress } function calculateNumTokens(uint256 balance, uint256 daysStaked, address stakerAddress, uint256 totalSupply) internal returns (uint256) { if (_useExternalCalc) { return _externalCalculator.calculateNumTokens(balance, daysStaked, stakerAddress, totalSupply); // Use external contract, if one is enabled (disabled by default, currently unused) } uint256 inflationAdjustmentFactor = _inflationAdjustmentFactor; if (_streak > 1) { inflationAdjustmentFactor /= _streak; // If there is a streak, we decrease the inflationAdjustmentFactor } if (daysStaked > 60) { // If you stake for more than 60 days, you have hit the upper limit of the multiplier daysStaked = 60; } else if (daysStaked == 0) { // If the minimum days staked is zero, we change the number to 1 so we don't return zero below daysStaked = 1; } uint marketCap = mulDiv(totalSupply, _lastUpdate.price, 1000E18); // Market cap (including locked team tokens) uint ratio = marketCap.div(_lastUpdate.volume); // Ratio of market cap to volume if (ratio > 50) { // Too little volume. Decrease rewards. inflationAdjustmentFactor = inflationAdjustmentFactor.mul(10); } else if (ratio > 25) { // Still not enough. Streak doesn't count. inflationAdjustmentFactor = _inflationAdjustmentFactor; } uint numTokens = mulDiv(balance, _lastUpdate.numerator * daysStaked, _lastUpdate.denominator * inflationAdjustmentFactor); // Function that calculates how many tokens are due. See muldiv below. uint tenPercent = mulDiv(balance, 1, 10); if (numTokens > tenPercent) { // We don't allow a daily rewards of greater than ten percent of a holder's balance. numTokens = tenPercent; } return numTokens; } // Self-explanatory functions to update several configuration variables function updateTokenAddress(DepoToken newToken) external onlyOwner { require(address(newToken) != address(0)); token = newToken; } function updateCalculator(CalculatorInterface calc) external onlyOwner { if(address(calc) == address(0)) { _externalCalculator = CalculatorInterface(address(0)); _useExternalCalc = false; } else { _externalCalculator = calc; _useExternalCalc = true; } } function updateInflationAdjustmentFactor(uint256 inflationAdjustmentFactor) external onlyOwner { _inflationAdjustmentFactor = inflationAdjustmentFactor; } function updateStreak(uint streak) external onlyOwner { _streak = streak; } function updateMinStakeDurationDays(uint8 minStakeDurationDays) external onlyOwner { _minStakeDurationDays = minStakeDurationDays; } function updateMinStakes(uint minStake) external onlyOwner { _minStake = minStake; } function updateMinPercentIncrease(uint8 minIncrease) external onlyOwner { _minPercentIncrease = minIncrease; } function enableBurns(bool enabledBurns) external onlyOwner { _enableBurns = enabledBurns; } function updateHoldersDay(bool enableHoldersDay) external onlyOwner { _enableHoldersDay = enableHoldersDay; } function updateWhitelist(address addr, string calldata reason, bool remove) external onlyOwner returns (bool) { if (remove) { delete _whitelist[addr]; return true; } else { _whitelist[addr] = reason; return true; } return false; } function updateBlacklist(address addr, uint256 fee, bool remove) external onlyOwner returns (bool) { if (remove) { delete _blacklist[addr]; return true; } else { _blacklist[addr] = fee; return true; } return false; } function updateUniswapPair(address addr) external onlyOwner returns (bool) { require(addr != address(0)); _uniswapV2Pair = addr; return true; } function updateDirectSellBurns(bool enableDirectSellBurns) external onlyOwner { _enableUniswapDirectBurns = enableDirectSellBurns; } function updateUniswapSellerBurnPercent(uint8 sellerBurnPercent) external onlyOwner { _uniswapSellerBurnPercent = sellerBurnPercent; } function freeze(bool enableFreeze) external onlyOwner { _freeze = enableFreeze; } function updateNextStakingContract(address nextContract) external onlyOwner { require(nextContract != address(0)); _nextStakingContract = nextContract; } function getStaker(address staker) external view returns (uint256, uint256) { return (_stakers[staker].startTimestamp, _stakers[staker].lastTimestamp); } function getWhitelist(address addr) external view returns (string memory) { return _whitelist[addr]; } function getBlacklist(address addr) external view returns (uint) { return _blacklist[addr]; } // This function was not written by us. It was taken from here: https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // We believe it works but do not have the understanding of math required to verify it 100%. // Takes in three numbers and calculates x * (y/z) // This is very useful for this contract as percentages are used constantly function mulDiv (uint x, uint y, uint z) public pure returns (uint) { (uint l, uint h) = fullMul (x, y); assert (h < z); uint mm = mulmod (x, y, z); if (mm > l) h -= 1; l -= mm; uint pow2 = z & -z; z /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint r = 1; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; return l * r; } function fullMul (uint x, uint y) private pure returns (uint l, uint h) { uint mm = mulmod (x, y, uint (-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function streak() public view returns (uint) { return _streak; } // Hooks the transfer() function on DepoToken. All transfers call this function. Takes in sender, recipient address and balances and amount and returns sender balance, recipient balance, and burned amount function transferHook(address sender, address recipient, uint256 amount, uint256 senderBalance, uint256 recipientBalance) external onlyToken returns (uint256, uint256, uint256) { assert(_freeze == false); assert(sender != recipient); assert(amount > 0); assert(senderBalance >= amount); uint totalAmount = amount; bool shouldAddStaker = true; // We assume that the recipient is a potential staker (not a smart contract) uint burnedAmount = 0; if (_enableBurns && bytes(_whitelist[sender]).length == 0 && bytes(_whitelist[recipient]).length == 0) { // Burns are enabled and neither the recipient nor the sender are whitelisted burnedAmount = mulDiv(amount, _randomness(), 100); // Calculates the amount to be burned. Random integer between 1% and 4%. See _randomness() below if (_blacklist[recipient] > 0) { //Transferring to a blacklisted address incurs a specific fee burnedAmount = mulDiv(amount, _blacklist[recipient], 100); // Calculate the fee. The fee is burnt shouldAddStaker = false; // Blacklisted addresses will never be stakers. } if (burnedAmount > 0) { if (burnedAmount > amount) { totalAmount = 0; } else { totalAmount = amount.sub(burnedAmount); } senderBalance = senderBalance.sub(burnedAmount, "ERC20: burn amount exceeds balance"); // Remove the burned amount from the sender's balance } } else if (recipient == _uniswapV2Pair) { // Uniswap was used. This is a special case. Uniswap is burn on receive but whitelist on send, so sellers pay fee and buyers do not. shouldAddStaker = false; if (_enableUniswapDirectBurns) { burnedAmount = mulDiv(amount, _uniswapSellerBurnPercent, 100); // Seller fee if (burnedAmount > 0) { if (burnedAmount > amount) { totalAmount = 0; } else { totalAmount = amount.sub(burnedAmount); } senderBalance = senderBalance.sub(burnedAmount, "ERC20: burn amount exceeds balance"); } } } if (bytes(_whitelist[recipient]).length > 0) { shouldAddStaker = false; } // Here we calculate the percent of the balance an address is receiving. If the address receives too many tokens, the staking time and last time rewards were claimed is reset to block.timestamp // This is necessary because otherwise funds could move from address to address with no penality and thus an individual could claim multiple times with the same funds if (shouldAddStaker && _stakers[recipient].startTimestamp > 0 && recipientBalance > 0) { // If you are currently staking, these should all be true uint percent = mulDiv(1000000, totalAmount, recipientBalance); // This is not really 'percent' it is just a number that represents the totalAmount as a fraction of the recipientBalance assert(percent > 0); if(percent.add(_stakers[recipient].startTimestamp) > block.timestamp) { // We represent the 'percent' as seconds and add to the recipient's unix time _stakers[recipient].startTimestamp = block.timestamp; } else { _stakers[recipient].startTimestamp = _stakers[recipient].startTimestamp.add(percent); // Receiving too many tokens resets your holding time } if(percent.add(_stakers[recipient].lastTimestamp) > block.timestamp) { _stakers[recipient].lastTimestamp = block.timestamp; } else { _stakers[recipient].lastTimestamp = _stakers[recipient].lastTimestamp.add(percent); // Receiving too many tokens may make you ineligible to claim the next day } } else if (shouldAddStaker && recipientBalance == 0 && (_stakers[recipient].startTimestamp > 0 || _stakers[recipient].lastTimestamp > 0)) { // Invalid state, so we reset their data/remove them delete _stakers[recipient]; emit StakerRemoved(recipient); } senderBalance = senderBalance.sub(totalAmount, "ERC20: transfer amount exceeds balance"); // Normal ERC20 transfer recipientBalance = recipientBalance.add(totalAmount); if (shouldAddStaker && _stakers[recipient].startTimestamp == 0 && (totalAmount >= _minStake || recipientBalance >= _minStake)) { // If the recipient was not previously a staker and their balance is now greater than minStake, we add them automatically _stakers[recipient] = staker(block.timestamp, block.timestamp); emit StakerAdded(recipient); } if (senderBalance < _minStake) { // If the sender's balance is below the minimum stake, we remove them automatically // Remove staker delete _stakers[sender]; emit StakerRemoved(sender); } else { _stakers[sender].startTimestamp = block.timestamp; // Sending tokens automatically resets your 'holding time' if (_stakers[sender].lastTimestamp == 0) { _stakers[sender].lastTimestamp = block.timestamp; } } return (senderBalance, recipientBalance, burnedAmount); } function _randomness() internal view returns (uint256) { // Calculates token burn on transfer between 1% and 4% (integers) if(_useExternalCalc) { return _externalCalculator.randomness(); } return 1 + uint256(keccak256(abi.encodePacked(blockhash(block.number-1), _msgSender())))%4; // We use the previous block hash as entropy. Can be gamed by a miner to some extent, but we accept this. } function burn(address account, uint256 amount) external onlyOwner { // We allow ourselves to burn tokens in case they were minted due to a bug token._burn(account, amount); } function resetStakeTimeDebug(address account) external onlyOwner { // We allow ourselves to reset stake times in case they get changed incorrectly due to a bug _stakers[account].lastTimestamp = block.timestamp; _stakers[account].startTimestamp = block.timestamp; } }
freeze all transfers in an emergency
bool private _freeze;
5,712,973
[ 1, 29631, 777, 29375, 316, 392, 801, 24530, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1426, 3238, 389, 29631, 31, 27573, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.25 <0.7.0; import "./VickreyAuction.sol"; contract BiddingRing { uint public endOfBidding; uint public endOfRevealing; uint public _biddingPeriod; uint public _revealingPeriod; uint public numBidders = 0; VickreyAuction public auction; address auctionAddress; /** Constructor for the Bidding Ring Contract This function sets the Bidding Periods and Revelaing periods for the bidding ring @param biddingPeriod Time after which bids won't be accepted @param revealingPeriod Time after end of Bidding when bidders reveal their bids */ constructor (uint biddingPeriod, uint revealingPeriod) public { endOfBidding = now + biddingPeriod; endOfRevealing = endOfBidding + revealingPeriod; // auctionAddress = _auction; // auction = VickreyAuction(_auction); } /** Link the bidding ring with the VickreyAuction This is setter function which sets the auction variable in the Bidding Ring to the ongoing Vickrey Auction @param _address Address of the Vickrey Auction contract */ function setAuctionAddress(address _address) public { auctionAddress = _address; auction = VickreyAuction(_address); } /** This is a getter methods for testing if the auction address is set correctly @return Address of the VickreyAuction linked to Bidding Ring */ // function getAuctionAddress() public view returns(address) { // return auctionAddress; // } mapping(address => bytes32) public hashedBidOff; /** This function stores the hash of the bid submitted by the account generated by combining the ammount and a user specified key The function takes a bytes32 object which is a hashed value of the bid mapped to the bidder address @param hashed Hased value of the bidding amount along with a user defined key */ function bid(bytes32 hashed) public { require(now < endOfBidding, "Bidding Period is over"); hashedBidOff[msg.sender] = hashed; numBidders++; } /** This is a getter methods for testing if the contract balance is set correctly @return Balance of the bidding ring contract */ // function getBalance() public view returns(uint) { // return address(this).balance; // } /** This is a getter methods for testing if the bids are added correctly @return Number of bidders in the bidding ring */ // function getNumBidders() public view returns(uint) { // return numBidders; // } address payable public highBidder = msg.sender; uint public nonceBid; uint public highBid; /** This is a payable function only called during the reveal period in which bidders can choose to reveal their bids The bidder sends a request with the value as their bidding amount and the argument as the key. There is no penalty for bidders who don't reveal. At each reveal it is checked if the bid is highest and the required variable are set. If the bid is smaller than the highest bid, then the bid is refunded back. @param nonce Random key provided by the user */ function reveal(uint nonce) public payable { // Following line must be uncommented // This function should not return anything! It is just for checking require(now >= endOfBidding && now < endOfRevealing, "Reveal not performed during reveal period"); require(keccak256(abi.encodePacked(uint(msg.value), nonce)) == hashedBidOff[msg.sender], "This User has not made this bid"); if (uint(msg.value) > highBid) { highBidder.transfer(highBid); highBid = uint(msg.value); highBidder = msg.sender; nonceBid = nonce; } else { msg.sender.transfer(msg.value); } } /** Getter function for testing if the highest bidder is set correctly @return The address of the highest bidder */ // function getHighest() public view returns (address) { // return highBidder; // } /** Function to submit highest bid to the Vickrey Auction This function is called only when revealing period of bidding ring is over. It submits the bid to the auction set by the address */ function submitToAuction() public { require(now > endOfRevealing); auction.bid(keccak256(abi.encodePacked(highBid, nonceBid))); } /** Function to reveal highest bid to the Vickrey Auction This function is called only when revealing period of bidding ring is over. It reveals the bid to the auction set by the address */ function revealToAuction() public payable { require(now > endOfRevealing); require(msg.sender == highBidder); auction.reveal.value(highBid)(nonceBid); } }
*/ Following line must be uncommented This function should not return anything! It is just for checking
This is a payable function only called during the reveal period in which bidders can choose to reveal their bids The bidder sends a request with the value as their bidding amount and the argument as the key. There is no penalty for bidders who don't reveal. At each reveal it is checked if the bid is highest and the required variable are set. If the bid is smaller than the highest bid, then the bid is refunded back. @param nonce Random key provided by the user function reveal(uint nonce) public payable { require(now >= endOfBidding && now < endOfRevealing, "Reveal not performed during reveal period"); require(keccak256(abi.encodePacked(uint(msg.value), nonce)) == hashedBidOff[msg.sender], "This User has not made this bid"); if (uint(msg.value) > highBid) { highBidder.transfer(highBid); highBid = uint(msg.value); highBidder = msg.sender; nonceBid = nonce; } else { msg.sender.transfer(msg.value); } }
12,694,322
[ 1, 19, 16093, 310, 980, 1297, 506, 12704, 475, 329, 1220, 445, 1410, 486, 327, 6967, 5, 2597, 353, 2537, 364, 6728, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1220, 353, 279, 8843, 429, 445, 1338, 2566, 4982, 326, 283, 24293, 3879, 316, 1492, 324, 1873, 414, 848, 9876, 358, 283, 24293, 3675, 30534, 203, 203, 565, 1021, 9949, 765, 9573, 279, 590, 598, 326, 460, 487, 3675, 324, 1873, 310, 3844, 471, 326, 1237, 487, 326, 498, 18, 203, 565, 6149, 353, 1158, 23862, 364, 324, 1873, 414, 10354, 2727, 1404, 283, 24293, 18, 203, 565, 2380, 1517, 283, 24293, 518, 353, 5950, 309, 326, 9949, 353, 9742, 471, 326, 1931, 2190, 854, 444, 18, 203, 565, 971, 326, 9949, 353, 10648, 2353, 326, 9742, 9949, 16, 1508, 326, 9949, 353, 1278, 12254, 1473, 18, 203, 203, 565, 632, 891, 7448, 565, 8072, 498, 2112, 635, 326, 729, 203, 565, 445, 283, 24293, 12, 11890, 7448, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3338, 1545, 20706, 38, 1873, 310, 597, 2037, 411, 20706, 426, 24293, 310, 16, 315, 426, 24293, 486, 9591, 4982, 283, 24293, 3879, 8863, 203, 3639, 2583, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 11890, 12, 3576, 18, 1132, 3631, 7448, 3719, 422, 14242, 17763, 7210, 63, 3576, 18, 15330, 6487, 315, 2503, 2177, 711, 486, 7165, 333, 9949, 8863, 203, 3639, 309, 261, 11890, 12, 3576, 18, 1132, 13, 405, 3551, 17763, 13, 288, 203, 5411, 3551, 17763, 765, 18, 13866, 12, 8766, 17763, 1769, 203, 5411, 3551, 17763, 273, 2254, 12, 3576, 18, 1132, 1769, 203, 5411, 3551, 17763, 765, 273, 1234, 18, 15330, 31, 203, 5411, 7448, 17763, 2 ]
./partial_match/7700/0xae2BF8e822C5f92d8E5F9aD3225C8F815893BB32/sources/motorChef.sol
* @notice User supplies assets into the market and receives cTokens in exchange @dev Assumes interest has already been accrued up to the current block @param minter The address of the account which is supplying the assets @param mintAmount The amount of the underlying asset to supply/ Fail if mint not allowed */ Verify market's block number equals current block number */
function mintFresh(address minter, uint mintAmount) internal virtual { uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { revert MintComptrollerRejection(allowed); } if (accrualBlockNumber != getBlockNumber()) { revert MintFreshnessCheck(); } uint mintTokens = div_(actualMintAmount, exchangeRate); accountTokens[minter] = accountTokens[minter] + mintTokens; emit Transfer(address(this), minter, mintTokens);
3,505,741
[ 1, 1299, 1169, 5259, 7176, 1368, 326, 13667, 471, 17024, 276, 5157, 316, 7829, 225, 25374, 16513, 711, 1818, 2118, 4078, 86, 5957, 731, 358, 326, 783, 1203, 225, 1131, 387, 1021, 1758, 434, 326, 2236, 1492, 353, 14467, 310, 326, 7176, 225, 312, 474, 6275, 1021, 3844, 434, 326, 6808, 3310, 358, 14467, 19, 8911, 309, 312, 474, 486, 2935, 342, 8553, 13667, 1807, 1203, 1300, 1606, 783, 1203, 1300, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 42, 1955, 12, 2867, 1131, 387, 16, 2254, 312, 474, 6275, 13, 2713, 5024, 288, 203, 3639, 2254, 2935, 273, 532, 337, 1539, 18, 81, 474, 5042, 12, 2867, 12, 2211, 3631, 1131, 387, 16, 312, 474, 6275, 1769, 203, 3639, 309, 261, 8151, 480, 374, 13, 288, 203, 5411, 15226, 490, 474, 799, 337, 1539, 426, 3710, 12, 8151, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 8981, 86, 1462, 1768, 1854, 480, 11902, 1854, 10756, 288, 203, 5411, 15226, 490, 474, 42, 1955, 4496, 1564, 5621, 203, 3639, 289, 203, 203, 203, 203, 3639, 2254, 312, 474, 5157, 273, 3739, 67, 12, 18672, 49, 474, 6275, 16, 7829, 4727, 1769, 203, 3639, 2236, 5157, 63, 1154, 387, 65, 273, 2236, 5157, 63, 1154, 387, 65, 397, 312, 474, 5157, 31, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 2211, 3631, 1131, 387, 16, 312, 474, 5157, 1769, 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 ]
pragma solidity ^0.6.0; interface TokenInterface { function approve(address, uint256) external; function transfer(address, uint) external; function transferFrom(address, address, uint) external; function deposit() external payable; function withdraw(uint) external; function balanceOf(address) external view returns (uint); function decimals() external view returns (uint); } interface MemoryInterface { function getUint(uint id) external returns (uint num); function setUint(uint id, uint val) external; } interface EventInterface { function emitEvent(uint connectorType, uint connectorID, bytes32 eventCode, bytes calldata eventData) external; } contract Stores { /** * @dev Return memory variable address */ function getMemoryAddr() internal pure returns (address) { return 0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F; // InstaMemory Address } /** * @dev Return InstaEvent Address. */ function getEventAddr() internal pure returns (address) { return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97; // InstaEvent Address } /** * @dev Get Uint value from InstaMemory Contract. */ function getUint(uint getId, uint val) internal returns (uint returnVal) { returnVal = getId == 0 ? val : MemoryInterface(getMemoryAddr()).getUint(getId); } /** * @dev Set Uint value in InstaMemory Contract. */ function setUint(uint setId, uint val) virtual internal { if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val); } /** * @dev emit event on event contract */ function emitEvent(bytes32 eventCode, bytes memory eventData) virtual internal { (uint model, uint id) = connectorID(); EventInterface(getEventAddr()).emitEvent(model, id, eventCode, eventData); } /** * @dev Connector Details. */ function connectorID() public view returns(uint model, uint id) { (model, id) = (1, 39); } } /** * @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 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; } } contract DSMath { function sub(uint x, uint y) internal virtual pure returns (uint z) { z = SafeMath.sub(x, y); } } interface ICurve { function claim(address addr) external; } contract CurveVestingHelpers is Stores, DSMath { /** * @dev Return Curve Token Address */ function getCurveTokenAddr() internal pure returns (address) { return 0xD533a949740bb3306d119CC777fa900bA034cd52; } /** * @dev Return Curve Vesting Address */ function getCurveVestingAddr() internal pure returns (address) { return 0x575CCD8e2D300e2377B43478339E364000318E2c; } } contract CurveVestingProtocol is CurveVestingHelpers { event LogClaim(address account, uint256 claimAmount, uint256 getId, uint256 setId); /** * @dev Claim Curve DAO Token. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function claim(uint getId, uint setId) external{ TokenInterface curveTokenContract = TokenInterface(getCurveTokenAddr()); uint initialCurveBal = curveTokenContract.balanceOf(address(this)); ICurve(getCurveVestingAddr()).claim(address(this)); uint finalCurveBal = curveTokenContract.balanceOf(address(this)); uint claimedAmt = sub(finalCurveBal, initialCurveBal); setUint(setId, claimedAmt); emit LogClaim(address(this), claimedAmt, getId, setId); bytes32 _eventCode = keccak256("LogClaim(address,uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(address(this), claimedAmt, getId, setId); emitEvent(_eventCode, _eventParam); } } contract ConnectCurveVesting is CurveVestingProtocol { string public name = "Curve-vesting-v1"; }
* @dev Connector Details./
function connectorID() public view returns(uint model, uint id) { (model, id) = (1, 39); }
1,369,193
[ 1, 7487, 21897, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 8703, 734, 1435, 1071, 1476, 1135, 12, 11890, 938, 16, 2254, 612, 13, 288, 203, 565, 261, 2284, 16, 612, 13, 273, 261, 21, 16, 16977, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "./interfaces/IDivinium.sol"; import "./DiviniumGenesisStaker.sol"; import "./DiviniumCreaturesStaker.sol"; contract DiviniumStaker is UUPSUpgradeable, DiviniumGenesisStaker, DiviniumCreaturesStaker { string public constant VERSION = "1.0"; bytes32 public constant SPENDER_ROLE = keccak256("SPENDER"); IDivinium public deployedDivinium; // Yield tracking mapping(address => uint256) public addressToCumulatedRewards; /* * @dev Replaces the constructor for upgradeable contracts */ function initialize( address deployedPowerAddress, address deployedGenesisAddress, address deployedGenesisSupplyAddress ) public initializer { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); __DiviniumGenesisStaker_init_unchained( deployedGenesisAddress, deployedGenesisSupplyAddress ); deployedDivinium = IDivinium(deployedPowerAddress); } /** * @notice Claim $DVN from Genesis and Creatures * @param genesisIds Array containing all genesis ids. These are validated on chain * @dev genesisIds can be empty */ function claim(uint256[] memory genesisIds) external { updateRewards(genesisIds); deployedDivinium.mint( msg.sender, addressToCumulatedRewards[msg.sender] ); addressToCumulatedRewards[msg.sender] = 0; } /** * @notice Update $DNV from Genesis and Creatures * @param genesisIds Array containing all genesis ids. These are validated on chain * @dev genesisIds can be empty */ function updateRewards(uint256[] memory genesisIds) public { // Only run genesis claim if needed if (genesisIds.length > 0) { addressToCumulatedRewards[msg.sender] += _claimGenesisRewards( genesisIds ); } // Only run creature update if creature exists if (address(deployedCreature) != address(0)) { addressToCumulatedRewards[ msg.sender ] += _claimCreaturesPendingRewards(msg.sender); } } /** * @notice Get pending Creatures reward for a user * @param user The user * @return The pending rewards for a user */ function getCreaturesPendingRewards(address user) external view returns (uint256) { return _getCreaturesPendingRewards(user) + addressToCumulatedRewards[user]; } /** * @notice Update the creatures rewards * @dev Called on transfers from Creatures and ascension * @param from The user who transfered * @param to The user who received * @param creatureId The ID of the creature to update * @param creatureType The type of the creature to update */ function updateCreaturesReward( address from, address to, uint256 creatureId, CreaturesAscensionType creatureType ) external onlyRole(CREATURES_ROLE) { uint256 rewardsToAdd = _updateCreaturesRewardAndTimestamp( from, creatureId, creatureType ); if (rewardsToAdd > 0) { addressToCumulatedRewards[from] += rewardsToAdd; } // No need to cumulate rewards here because they've been claimed already above _updateCreaturesRewardAndTimestamp(to, creatureId, creatureType); } /** * @notice Update the creatures rewards form ascension * @dev Called on transfers from Creatures and ascension * @param from The user who transfered * @param creatureId The ID of the creature to update * @param creatureType The type of the creature to update */ function updateCreaturesRewardFromAscension( address from, uint256 creatureId, CreaturesAscensionType creatureType ) external onlyRole(CREATURES_ROLE) { addressToCumulatedRewards[from] += _updateCreaturesRewardAndTimestamp( from, creatureId, creatureType ); } function spendUnclaimedRewards(address from, uint256 amount) external onlyRole(SPENDER_ROLE) returns (uint256 spent) { require(addressToCumulatedRewards[from] > 0, "No unclaimed fund"); spent = amount; if (addressToCumulatedRewards[from] > amount) { addressToCumulatedRewards[from] -= amount; } else { spent = addressToCumulatedRewards[from]; addressToCumulatedRewards[from] = 0; } } /** * UUPS upgradeable */ function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IDivinium { function mint(address to_, uint256 amount_) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/IGenesisTypes.sol"; import "./interfaces/IGenesisSupply.sol"; import "./interfaces/IGenesis.sol"; import "./DiviniumConfig.sol"; abstract contract DiviniumGenesisStaker is Initializable, IGenesisTypes, DiviniumConfig { uint256 public constant GENESIS_START_TIMESTAMP = 1641627068; struct GenesisUpdate { TokenType genesisType; uint256 lastUpdatedAt; } IGenesis public deployedGenesis; IGenesisSupply public deployedGenesisSupply; // Yield tracking mapping(uint256 => GenesisUpdate) public genesisIdToUpdate; event GenesisDiviniumClaim(uint256 indexed tokenId, address indexed user); /** * @dev Chained initializer */ function __DiviniumGenesisStaker_init( address deployedGenesisAddress, address deployedGenesisSupplyAddress ) internal onlyInitializing { __DiviniumGenesisStaker_init_unchained( deployedGenesisAddress, deployedGenesisSupplyAddress ); } /** * @dev Unchained initializer */ function __DiviniumGenesisStaker_init_unchained( address deployedGenesisAddress, address deployedGenesisSupplyAddress ) internal onlyInitializing { deployedGenesis = IGenesis(deployedGenesisAddress); deployedGenesisSupply = IGenesisSupply(deployedGenesisSupplyAddress); } /** * @notice Gets the rate multiplier for a genesis holder * @param genesisType The type of genesis * @return rate multiplier for Genesis collection */ function _getGenesisMultiplierForType(TokenType genesisType) internal pure returns (uint256) { require(genesisType != TokenType.NONE, "Invalid Type"); if (genesisType == TokenType.GOD) { return 16; } else if (genesisType == TokenType.DEMI_GOD) { return 8; } return 6; } /** * @notice Get Genesis reward for specific ID * @param id The ID to check reward * @param genesisType The type of genesis * @return The reward for an ID */ function _getGenesisRewardForId(uint256 id, TokenType genesisType) internal view returns (uint256) { uint256 startTimestamp = genesisIdToUpdate[id].lastUpdatedAt; if (startTimestamp == 0) { startTimestamp = GENESIS_START_TIMESTAMP; } return (BASE_RATE * _getGenesisMultiplierForType(genesisType) * (block.timestamp - startTimestamp)) / 1 days; } /** * @notice Claim $DVN from Genesis * @param genesisIds Array containing all genesis ids. These are validated on chain * @return The total Genesis $DVN rewards for ids */ function _claimGenesisRewards(uint256[] memory genesisIds) internal returns (uint256) { uint256 totalRewards; uint256 totalIds = genesisIds.length; TokenTraits memory traits; for (uint256 index = 0; index < totalIds; index++) { require( deployedGenesis.ownerOf(genesisIds[index]) == msg.sender, "Not owner of Genesis" ); traits = deployedGenesisSupply.getMetadataForTokenId( genesisIds[index] ); totalRewards += _getGenesisRewardForId( genesisIds[index], traits.tokenType ); genesisIdToUpdate[genesisIds[index]] = GenesisUpdate( traits.tokenType, block.timestamp ); emit GenesisDiviniumClaim(genesisIds[index], msg.sender); } return totalRewards; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "./interfaces/ICreatures.sol"; import "./interfaces/ICreaturesTypes.sol"; import "./DiviniumConfig.sol"; abstract contract DiviniumCreaturesStaker is Initializable, AccessControlUpgradeable, ICreaturesTypes, DiviniumConfig { bytes32 public constant CREATURES_ROLE = keccak256("CREATURES"); struct CreatureUpdate { CreaturesAscensionType creatureType; uint256 lastUpdatedAt; } ICreatures public deployedCreature; // Yield tracking mapping(uint256 => CreatureUpdate) public creaturesIdToUpdate; event CreaturesDiviniumClaim( uint256 indexed creatureId, address indexed user ); /** * @dev Chained initializer */ function __DiviniumCreaturesStaker_init() internal onlyInitializing { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); __DiviniumCreaturesStaker_init_unchained(); } /** * @dev Unchained initializer */ function __DiviniumCreaturesStaker_init_unchained() internal onlyInitializing {} /** * @notice Sets the Creatures contract address * @dev only admin can run this function * @param creaturesAddress Address of the contract */ function setCreaturesAddress(address creaturesAddress) external onlyRole(DEFAULT_ADMIN_ROLE) { deployedCreature = ICreatures(creaturesAddress); grantRole(CREATURES_ROLE, creaturesAddress); } /** * @notice Get pending Creatures reward for a user * @param user The user * @return The pending rewards for a user */ function _getCreaturesPendingRewards(address user) internal view returns (uint256) { uint256[] memory ids = deployedCreature.tokensForOwner(user); uint256 cumulRewards; // Loop through all indexes of owner, for (uint256 index = 0; index < ids.length; index++) { cumulRewards += _getCreaturesRewardForId(ids[index]); } return cumulRewards; } /** * @notice Gets the rate multiplier for a creature holder * @param creatureAscensionType The ascension type * @return rate multiplier for Creature collection */ function _getCreaturesMultiplierForType( CreaturesAscensionType creatureAscensionType ) internal pure returns (uint256) { if (creatureAscensionType == CreaturesAscensionType.NONE) { return 1; } else if ( creatureAscensionType == CreaturesAscensionType.ASCENDED_NONE ) { return 2; } else if ( creatureAscensionType == CreaturesAscensionType.ASCENDED_SINGLE ) { return 3; } else if ( creatureAscensionType == CreaturesAscensionType.ASCENDED_DOUBLE ) { return 4; } return 5; } /** * @notice Get Creatures reward for Id * @param creatureId id of the creature to get rewards from, * @return The reward for the type */ function _getCreaturesRewardForId(uint256 creatureId) internal view returns (uint256) { require( creaturesIdToUpdate[creatureId].lastUpdatedAt != 0, "Invalid Creature" ); CreatureUpdate memory creatureData = creaturesIdToUpdate[creatureId]; return (BASE_RATE * _getCreaturesMultiplierForType(creatureData.creatureType) * (block.timestamp - creatureData.lastUpdatedAt)) / 1 days; } /** * @notice Claim the creatures pending reward of a user * @param user The user * @return The pending rewards for a user */ function _claimCreaturesPendingRewards(address user) internal returns (uint256) { uint256[] memory ids = deployedCreature.tokensForOwner(user); uint256 cumulRewards; // Loop through all indexes of owner, for (uint256 index = 0; index < ids.length; index++) { uint256 currentId = ids[index]; cumulRewards += _getCreaturesRewardForId(currentId); creaturesIdToUpdate[currentId] = CreatureUpdate( creaturesIdToUpdate[currentId].creatureType, block.timestamp ); } return cumulRewards; } /** * @notice Update the last update timestamp for user * @param user The user to update * @param creatureId The ID of the creature to update * @param creatureType The type of the creature to update */ function _updateCreaturesRewardAndTimestamp( address user, uint256 creatureId, CreaturesAscensionType creatureType ) internal returns (uint256 rewards) { rewards = 0; if (user != address(0)) { // We check if the last update is before the current timestamp // The creatures contract update the FROM then the TO // On a transfer, FROM will get the pending rewards and TO will not // because timestamp is set after. On mint, we set it on the TO. if ( creaturesIdToUpdate[creatureId].lastUpdatedAt < block.timestamp ) { rewards = _getCreaturesRewardForId(creatureId); emit CreaturesDiviniumClaim(creatureId, user); } } if (creaturesIdToUpdate[creatureId].lastUpdatedAt < block.timestamp) { creaturesIdToUpdate[creatureId] = CreatureUpdate( creatureType, block.timestamp ); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IGenesisTypes { enum TokenType { NONE, GOD, DEMI_GOD, ELEMENTAL } enum TokenSubtype { NONE, CREATIVE, DESTRUCTIVE, AIR, EARTH, ELECTRICITY, FIRE, MAGMA, METAL, WATER } struct TokenTraits { TokenType tokenType; TokenSubtype tokenSubtype; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "./IGenesisTypes.sol"; interface IGenesisSupply is IGenesisTypes { function getMetadataForTokenId(uint256 tokenId) external view returns (TokenTraits memory traits); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IGenesis { function ownerOf(uint256 tokenId) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; abstract contract DiviniumConfig { uint256 public constant BASE_RATE = 1 ether; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "./ICreaturesTypes.sol"; interface ICreatures is ICreaturesTypes { function tokensForOwner(address user) external view returns (uint256[] memory ids); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface ICreaturesTypes { enum CreaturesAscensionType { NONE, ASCENDED_NONE, ASCENDED_SINGLE, ASCENDED_DOUBLE, ASCENDED_FULL } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @notice Get pending Creatures reward for a user @param user The user @return The pending rewards for a user/
function getCreaturesPendingRewards(address user) external view returns (uint256) { return _getCreaturesPendingRewards(user) + addressToCumulatedRewards[user]; }
463,905
[ 1, 967, 4634, 5799, 2790, 19890, 364, 279, 729, 225, 729, 1021, 729, 327, 1021, 4634, 283, 6397, 364, 279, 729, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15759, 2790, 8579, 17631, 14727, 12, 2867, 729, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 203, 5411, 389, 588, 1996, 2790, 8579, 17631, 14727, 12, 1355, 13, 397, 1758, 774, 39, 5283, 690, 17631, 14727, 63, 1355, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /* Borrowed heavily from Synthetix * MIT License * =========== * * Copyright (c) 2021 Synthetix * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.8.0; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IBankNodeManager} from "../../Management/interfaces/IBankNodeManager.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; /// @title BNPL bank node lending reward system contract /// /// @dev This contract is inherited by the `BankNodeLendingRewards` contract /// @notice /// - Users: /// **Stake** /// **Withdraw** /// **GetReward** /// - Manager: /// **SetRewardsDuration** /// - Distributor: /// **distribute BNPL tokens to BankNodes** /// /// @author BNPL contract BankNodeRewardSystem is Initializable, ReentrancyGuardUpgradeable, PausableUpgradeable, AccessControlUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; bytes32 public constant REWARDS_DISTRIBUTOR_ROLE = keccak256("REWARDS_DISTRIBUTOR_ROLE"); bytes32 public constant REWARDS_DISTRIBUTOR_ADMIN_ROLE = keccak256("REWARDS_DISTRIBUTOR_ADMIN_ROLE"); bytes32 public constant REWARDS_MANAGER = keccak256("REWARDS_MANAGER_ROLE"); bytes32 public constant REWARDS_MANAGER_ROLE_ADMIN = keccak256("REWARDS_MANAGER_ROLE_ADMIN"); /// @notice [Bank node id] => [Previous rewards period] mapping(uint32 => uint256) public periodFinish; /// @notice [Bank node id] => [Reward rate] mapping(uint32 => uint256) public rewardRate; /// @notice [Bank node id] => [Rewards duration] mapping(uint32 => uint256) public rewardsDuration; /// @notice [Bank node id] => [Rewards last update time] mapping(uint32 => uint256) public lastUpdateTime; /// @notice [Bank node id] => [Reward per token stored] mapping(uint32 => uint256) public rewardPerTokenStored; /// @notice [Encoded user bank node key (user, bankNodeId)] => [Reward per token paid] mapping(uint256 => uint256) public userRewardPerTokenPaid; /// @notice [Encoded user bank node key (user, bankNodeId)] => [Rewards amount] mapping(uint256 => uint256) public rewards; /// @notice [Bank node id] => [Stake amount] mapping(uint32 => uint256) public _totalSupply; /// @notice [Encoded user bank node key (user, bankNodeId)] => [Staked balance] mapping(uint256 => uint256) private _balances; /// @notice BNPL bank node manager contract IBankNodeManager public bankNodeManager; /// @notice Rewards token contract IERC20 public rewardsToken; /// @notice Default rewards duration (secs) uint256 public defaultRewardsDuration; /// @dev Encode user address and bank node id into a uint256. /// /// @param user The address of user /// @param bankNodeId The id of the bank node /// @return encodedUserBankNodeKey The encoded user bank node key. function encodeUserBankNodeKey(address user, uint32 bankNodeId) public pure returns (uint256) { return (uint256(uint160(user)) << 32) | uint256(bankNodeId); } /// @dev Decode user bank node key to user address and bank node id. /// /// @param stakingVaultKey The user bank node key /// @return user The address of user /// @return bankNodeId The id of the bank node function decodeUserBankNodeKey(uint256 stakingVaultKey) external pure returns (address user, uint32 bankNodeId) { bankNodeId = uint32(stakingVaultKey & 0xffffffff); user = address(uint160(stakingVaultKey >> 32)); } /// @dev Encode amount and depositTime into a uint256. /// /// @param amount An uint256 amount /// @param depositTime An uint40 deposit time /// @return encodedVaultValue The encoded vault value function encodeVaultValue(uint256 amount, uint40 depositTime) external pure returns (uint256) { require( amount <= 0xffffffffffffffffffffffffffffffffffffffffffffffffffffff, "cannot encode amount larger than 2^216-1" ); return (amount << 40) | uint256(depositTime); } /// @notice Decode vault value to amount and depositTime /// /// @param vaultValue The encoded vault value /// @return amount An `uint256` amount /// @return depositTime An `uint40` deposit time function decodeVaultValue(uint256 vaultValue) external pure returns (uint256 amount, uint40 depositTime) { depositTime = uint40(vaultValue & 0xffffffffff); amount = vaultValue >> 40; } /// @dev Ensure the given address not zero and return it as IERC20 /// @return ERC20Token function _ensureAddressIERC20Not0(address tokenAddress) internal pure returns (IERC20) { require(tokenAddress != address(0), "invalid token address!"); return IERC20(tokenAddress); } /// @dev Ensure the given address not zero /// @return Address function _ensureContractAddressNot0(address contractAddress) internal pure returns (address) { require(contractAddress != address(0), "invalid token address!"); return contractAddress; } /// @dev Get the lending pool token contract (ERC20) address of the specified bank node /// /// @param bankNodeId The id of the bank node /// @return BankNodeTokenContract The lending pool token contract (ERC20) function getStakingTokenForBankNode(uint32 bankNodeId) internal view returns (IERC20) { return _ensureAddressIERC20Not0(bankNodeManager.getBankNodeToken(bankNodeId)); } /// @notice Get the lending pool token amount in rewards of the specified bank node /// /// @param bankNodeId The id of the bank node /// @return BankNodeTokenBalanceInRewards The lending pool token balance in rewards function getPoolLiquidityTokensStakedInRewards(uint32 bankNodeId) public view returns (uint256) { return getStakingTokenForBankNode(bankNodeId).balanceOf(address(this)); } /// @dev Returns the input `amount` function getInternalValueForStakedTokenAmount(uint256 amount) internal pure returns (uint256) { return amount; } /// @dev Returns the input `amount` function getStakedTokenAmountForInternalValue(uint256 amount) internal pure returns (uint256) { return amount; } /// @notice Get the stake amount of the specified bank node /// /// @param bankNodeId The id of the bank node /// @return TotalSupply The stake amount function totalSupply(uint32 bankNodeId) external view returns (uint256) { return getStakedTokenAmountForInternalValue(_totalSupply[bankNodeId]); } /// @notice Get the user's staked balance under the specified bank node /// /// @param account User address /// @param bankNodeId The id of the bank node /// @return StakedBalance User's staked balance function balanceOf(address account, uint32 bankNodeId) external view returns (uint256) { return getStakedTokenAmountForInternalValue(_balances[encodeUserBankNodeKey(account, bankNodeId)]); } /// @notice Get the last time reward applicable of the specified bank node /// /// @param bankNodeId The id of the bank node /// @return lastTimeRewardApplicable The last time reward applicable function lastTimeRewardApplicable(uint32 bankNodeId) public view returns (uint256) { return block.timestamp < periodFinish[bankNodeId] ? block.timestamp : periodFinish[bankNodeId]; } /// @notice Get reward amount with bank node id /// /// @param bankNodeId The id of the bank node /// @return rewardPerToken Reward per token amount function rewardPerToken(uint32 bankNodeId) public view returns (uint256) { if (_totalSupply[bankNodeId] == 0) { return rewardPerTokenStored[bankNodeId]; } return rewardPerTokenStored[bankNodeId].add( lastTimeRewardApplicable(bankNodeId) .sub(lastUpdateTime[bankNodeId]) .mul(rewardRate[bankNodeId]) .mul(1e18) .div(_totalSupply[bankNodeId]) ); } /// @notice Get the benefits earned by users in the bank node /// /// @param account The user address /// @param bankNodeId The id of the bank node /// @return Earnd Benefits earned by users in the bank node function earned(address account, uint32 bankNodeId) public view returns (uint256) { uint256 key = encodeUserBankNodeKey(account, bankNodeId); return ((_balances[key] * (rewardPerToken(bankNodeId) - (userRewardPerTokenPaid[key]))) / 1e18) + (rewards[key]); } /// @notice Get bank node reward for duration /// /// @param bankNodeId The id of the bank node /// @return RewardForDuration Bank node reward for duration function getRewardForDuration(uint32 bankNodeId) external view returns (uint256) { return rewardRate[bankNodeId] * rewardsDuration[bankNodeId]; } /// @notice Stake `tokenAmount` tokens to specified bank node /// /// @param bankNodeId The id of the bank node to stake /// @param tokenAmount The amount to be staked function stake(uint32 bankNodeId, uint256 tokenAmount) external nonReentrant whenNotPaused updateReward(msg.sender, bankNodeId) { require(tokenAmount > 0, "Cannot stake 0"); uint256 amount = getInternalValueForStakedTokenAmount(tokenAmount); require(amount > 0, "Cannot stake 0"); require(getStakedTokenAmountForInternalValue(amount) == tokenAmount, "token amount too high!"); _totalSupply[bankNodeId] += amount; _balances[encodeUserBankNodeKey(msg.sender, bankNodeId)] += amount; getStakingTokenForBankNode(bankNodeId).safeTransferFrom(msg.sender, address(this), tokenAmount); emit Staked(msg.sender, bankNodeId, tokenAmount); } /// @notice Withdraw `tokenAmount` tokens from specified bank node /// /// @param bankNodeId The id of the bank node to withdraw /// @param tokenAmount The amount to be withdrawn function withdraw(uint32 bankNodeId, uint256 tokenAmount) public nonReentrant updateReward(msg.sender, bankNodeId) { require(tokenAmount > 0, "Cannot withdraw 0"); uint256 amount = getInternalValueForStakedTokenAmount(tokenAmount); require(amount > 0, "Cannot withdraw 0"); require(getStakedTokenAmountForInternalValue(amount) == tokenAmount, "token amount too high!"); _totalSupply[bankNodeId] -= amount; _balances[encodeUserBankNodeKey(msg.sender, bankNodeId)] -= amount; getStakingTokenForBankNode(bankNodeId).safeTransfer(msg.sender, tokenAmount); emit Withdrawn(msg.sender, bankNodeId, tokenAmount); } /// @notice Get reward from specified bank node. /// @param bankNodeId The id of the bank node function getReward(uint32 bankNodeId) public nonReentrant updateReward(msg.sender, bankNodeId) { uint256 reward = rewards[encodeUserBankNodeKey(msg.sender, bankNodeId)]; if (reward > 0) { rewards[encodeUserBankNodeKey(msg.sender, bankNodeId)] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, bankNodeId, reward); } } /// @notice Withdraw tokens and get reward from specified bank node. /// @param bankNodeId The id of the bank node function exit(uint32 bankNodeId) external { withdraw( bankNodeId, getStakedTokenAmountForInternalValue(_balances[encodeUserBankNodeKey(msg.sender, bankNodeId)]) ); getReward(bankNodeId); } /// @dev Update the reward and emit the `RewardAdded` event function _notifyRewardAmount(uint32 bankNodeId, uint256 reward) internal updateReward(address(0), bankNodeId) { if (rewardsDuration[bankNodeId] == 0) { rewardsDuration[bankNodeId] = defaultRewardsDuration; } if (block.timestamp >= periodFinish[bankNodeId]) { rewardRate[bankNodeId] = reward / (rewardsDuration[bankNodeId]); } else { uint256 remaining = periodFinish[bankNodeId] - (block.timestamp); uint256 leftover = remaining * (rewardRate[bankNodeId]); rewardRate[bankNodeId] = (reward + leftover) / (rewardsDuration[bankNodeId]); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = rewardsToken.balanceOf(address(this)); require(rewardRate[bankNodeId] <= (balance / rewardsDuration[bankNodeId]), "Provided reward too high"); lastUpdateTime[bankNodeId] = block.timestamp; periodFinish[bankNodeId] = block.timestamp + (rewardsDuration[bankNodeId]); emit RewardAdded(bankNodeId, reward); } /// @notice Update the reward and emit the `RewardAdded` event /// /// - PRIVILEGES REQUIRED: /// Admins with the role "REWARDS_DISTRIBUTOR_ROLE" /// /// @param bankNodeId The id of the bank node /// @param reward The reward amount function notifyRewardAmount(uint32 bankNodeId, uint256 reward) external onlyRole(REWARDS_DISTRIBUTOR_ROLE) { _notifyRewardAmount(bankNodeId, reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders /* function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require(tokenAddress != address(stakingToken[]), "Cannot withdraw the staking token"); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); }*/ /// @notice Set reward duration for a bank node /// /// - PRIVILEGES REQUIRED: /// Admins with the role "REWARDS_MANAGER" /// /// @param bankNodeId The id of the bank node /// @param _rewardsDuration New reward duration (secs) function setRewardsDuration(uint32 bankNodeId, uint256 _rewardsDuration) external onlyRole(REWARDS_MANAGER) { require( block.timestamp > periodFinish[bankNodeId], "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration[bankNodeId] = _rewardsDuration; emit RewardsDurationUpdated(bankNodeId, rewardsDuration[bankNodeId]); } /// @dev Update user bank node reward modifier updateReward(address account, uint32 bankNodeId) { if (rewardsDuration[bankNodeId] == 0) { rewardsDuration[bankNodeId] = defaultRewardsDuration; } rewardPerTokenStored[bankNodeId] = rewardPerToken(bankNodeId); lastUpdateTime[bankNodeId] = lastTimeRewardApplicable(bankNodeId); if (account != address(0)) { uint256 key = encodeUserBankNodeKey(msg.sender, bankNodeId); rewards[key] = earned(msg.sender, bankNodeId); userRewardPerTokenPaid[key] = rewardPerTokenStored[bankNodeId]; } _; } /// @dev Emitted when `_notifyRewardAmount` is called. /// /// @param bankNodeId The id of the bank node /// @param reward The reward amount event RewardAdded(uint32 indexed bankNodeId, uint256 reward); /// @dev Emitted when user `user` stake `tokenAmount` to specified `bankNodeId` bank node. /// /// @param user The user address /// @param bankNodeId The id of the bank node /// @param amount The staked amount event Staked(address indexed user, uint32 indexed bankNodeId, uint256 amount); /// @dev Emitted when user `user` withdraw `amount` of BNPL tokens from `bankNodeId` bank node. /// /// @param user The user address /// @param bankNodeId The id of the bank node /// @param amount The withdrawn amount event Withdrawn(address indexed user, uint32 indexed bankNodeId, uint256 amount); /// @dev Emitted when user `user` calls `getReward`. /// /// @param user The user address /// @param bankNodeId The id of the bank node /// @param reward The reward amount event RewardPaid(address indexed user, uint32 indexed bankNodeId, uint256 reward); /// @dev Emitted when `setRewardsDuration` is called. /// /// @param bankNodeId The id of the bank node /// @param newDuration The new reward duration event RewardsDurationUpdated(uint32 indexed bankNodeId, uint256 newDuration); }
@dev Decode user bank node key to user address and bank node id. @param stakingVaultKey The user bank node key @return user The address of user @return bankNodeId The id of the bank node
function decodeUserBankNodeKey(uint256 stakingVaultKey) external pure returns (address user, uint32 bankNodeId) { bankNodeId = uint32(stakingVaultKey & 0xffffffff); user = address(uint160(stakingVaultKey >> 32)); }
6,480,649
[ 1, 6615, 729, 11218, 756, 498, 358, 729, 1758, 471, 11218, 756, 612, 18, 225, 384, 6159, 12003, 653, 1021, 729, 11218, 756, 498, 327, 729, 1021, 1758, 434, 729, 327, 11218, 15883, 1021, 612, 434, 326, 11218, 756, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 2495, 1299, 16040, 907, 653, 12, 11890, 5034, 384, 6159, 12003, 653, 13, 3903, 16618, 1135, 261, 2867, 729, 16, 2254, 1578, 11218, 15883, 13, 288, 203, 3639, 11218, 15883, 273, 2254, 1578, 12, 334, 6159, 12003, 653, 473, 374, 28857, 1769, 203, 3639, 729, 273, 1758, 12, 11890, 16874, 12, 334, 6159, 12003, 653, 1671, 3847, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x73dF03B5436C84Cf9d5A758fb756928DCEAf19d7/sources/ExchangeIssuanceModule.sol
File: contracts/core/lib/ExchangeHeaderLibrary.sol/* @title ExchangeHeaderLibrary @author Set Protocol This library contains functions and structs to assist with parsing exchange orders data/ ============ Structs ============
library ExchangeHeaderLibrary { using LibBytes for bytes; using SafeMath for uint256; function slice(bytes memory b, uint256 from, uint256 to) internal pure returns (bytes memory result) } } Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pragma solidity 0.5.7; struct ExchangeHeader { uint8 exchange; uint8 orderCount; uint256 orderDataBytesLength; } function EXCHANGE_HEADER_LENGTH() internal pure returns (uint256) { return uint256(96); } function parseExchangeHeader( bytes memory _orderData, uint256 _offset ) internal pure returns (ExchangeHeader memory) { ExchangeHeader memory header; uint256 headerDataStart = _orderData.contentAddress().add(_offset); assembly { } return header; } function parseExchangeHeader( bytes memory _orderData, uint256 _offset ) internal pure returns (ExchangeHeader memory) { ExchangeHeader memory header; uint256 headerDataStart = _orderData.contentAddress().add(_offset); assembly { } return header; } function sliceBodyData( bytes memory _orderData, uint256 _scannedBytes, uint256 _exchangeDataLength ) internal pure returns (bytes memory) { bytes memory bodyData = LibBytes.slice( _orderData, _scannedBytes.add(EXCHANGE_HEADER_LENGTH()), _scannedBytes.add(_exchangeDataLength) ); return bodyData; } }
4,492,623
[ 1, 812, 30, 20092, 19, 3644, 19, 2941, 19, 11688, 1864, 9313, 18, 18281, 19, 225, 18903, 1864, 9313, 225, 1000, 4547, 1220, 5313, 1914, 4186, 471, 8179, 358, 1551, 376, 598, 5811, 7829, 11077, 501, 19, 422, 1432, 631, 7362, 87, 422, 1432, 631, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 18903, 1864, 9313, 288, 203, 565, 1450, 10560, 2160, 364, 1731, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 445, 2788, 12, 3890, 3778, 324, 16, 2254, 5034, 628, 16, 2254, 5034, 358, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 3778, 563, 13, 203, 565, 289, 203, 97, 203, 203, 203, 565, 25417, 14863, 1000, 511, 5113, 15090, 18, 203, 203, 565, 511, 335, 28003, 3613, 326, 24840, 16832, 16, 4049, 576, 18, 20, 261, 5787, 315, 13211, 8863, 203, 565, 1846, 2026, 486, 999, 333, 585, 1335, 316, 29443, 598, 326, 16832, 18, 203, 565, 4554, 2026, 7161, 279, 1610, 434, 326, 16832, 622, 203, 203, 203, 565, 1351, 2656, 1931, 635, 12008, 328, 2219, 578, 1737, 15656, 358, 316, 7410, 16, 17888, 203, 565, 16859, 3613, 326, 16832, 353, 16859, 603, 392, 315, 3033, 4437, 6, 28143, 15664, 16, 203, 565, 13601, 5069, 678, 985, 54, 6856, 8805, 4869, 3492, 18575, 55, 15932, 16743, 1475, 2356, 16, 3344, 16947, 578, 23547, 18, 203, 565, 2164, 326, 16832, 364, 326, 2923, 2653, 314, 1643, 2093, 4371, 471, 203, 565, 31810, 3613, 326, 16832, 18, 203, 203, 683, 9454, 18035, 560, 374, 18, 25, 18, 27, 31, 203, 203, 203, 203, 203, 565, 1958, 18903, 1864, 288, 203, 3639, 2254, 28, 7829, 31, 203, 3639, 2254, 28, 1353, 1380, 31, 203, 3639, 2254, 5034, 1353, 751, 2160, 1782, 31, 203, 565, 289, 203, 203, 565, 445, 5675, 14473, 67, 7557, 67, 7096, 2 ]
pragma solidity ^0.4.24; import "./ILibSignatures.sol"; contract VPC { event EventVpcClosing(bytes32 indexed _id); event EventVpcClosed(bytes32 indexed _id, uint cashAlice, uint cashBob); // datatype for virtual state struct VpcState { uint AliceCash; uint BobCash; uint seqNo; uint validity; uint extendedValidity; bool open; bool waitingForAlice; bool waitingForBob; bool init; } // datatype for virtual state mapping (bytes32 => VpcState) public states; VpcState public s; bytes32 public id; ILibSignatures public libSig; constructor(address _libSig) public { libSig = ILibSignatures(_libSig); } /* * This function is called by any participant of the virtual channel * It is used to establish a final distribution of funds in the virtual channel */ function close(address alice, address bob, uint sid, uint version, uint aliceCash, uint bobCash, bytes signA, bytes signB) public { require(msg.sender == alice || msg.sender == bob); id = keccak256(abi.encodePacked(alice, bob, sid)); s = states[id]; // verfiy signatures bytes32 msgHash = keccak256(abi.encodePacked(id, version, aliceCash, bobCash)); bytes32 gethPrefixHash = keccak256(abi.encodePacked("\u0019Ethereum Signed Message:\n32", msgHash)); require(libSig.verify(alice, gethPrefixHash, signA) && libSig.verify(bob, gethPrefixHash, signB)); // if such a virtual channel state does not exist yet, create one if (!s.init) { uint validity = now + 10 minutes; uint extendedValidity = validity + 10 minutes; s = VpcState(aliceCash, bobCash, version, validity, extendedValidity, true, true, true, true); emit EventVpcClosing(id); } // if channel is closed or timeouted do nothing if (!s.open || s.extendedValidity < now) return; if ((s.validity < now) && (msg.sender == alice || msg.sender == bob)) return; // check if the message is from alice or bob if (msg.sender == alice) s.waitingForAlice = false; if (msg.sender == bob) s.waitingForBob = false; // set values of Internal State if (version > s.seqNo) { s = VpcState(aliceCash, bobCash, version, s.validity, s.extendedValidity, true, s.waitingForAlice, s.waitingForBob, true); } // execute if both players responded if (!s.waitingForAlice && !s.waitingForBob) { s.open = false; emit EventVpcClosed(id, s.AliceCash, s.BobCash); } states[id] = s; } /* * For the virtual channel with id = (alice, ingrid, bob, sid) this function: * returns (false, 0, 0) if such a channel does not exist or is neither closed nor timeouted, or * return (true, a, b) otherwise, where (a, b) is a final distribution of funds in this channel */ function finalize(address alice, address bob, uint sid) public returns (bool v, uint a, uint b) { id = keccak256(abi.encodePacked(alice, bob, sid)); if (states[id].init) { if (states[id].extendedValidity < now) { states[id].open = false; emit EventVpcClosed(id, states[id].AliceCash, states[id].BobCash); } if (states[id].open) return (false, 0, 0); else return (true, states[id].AliceCash, states[id].BobCash); } else return (false, 0, 0); } }
This function is called by any participant of the virtual channel It is used to establish a final distribution of funds in the virtual channel/ verfiy signatures if such a virtual channel state does not exist yet, create one set values of Internal State execute if both players responded
function close(address alice, address bob, uint sid, uint version, uint aliceCash, uint bobCash, bytes signA, bytes signB) public { require(msg.sender == alice || msg.sender == bob); id = keccak256(abi.encodePacked(alice, bob, sid)); s = states[id]; bytes32 msgHash = keccak256(abi.encodePacked(id, version, aliceCash, bobCash)); bytes32 gethPrefixHash = keccak256(abi.encodePacked("\u0019Ethereum Signed Message:\n32", msgHash)); require(libSig.verify(alice, gethPrefixHash, signA) && libSig.verify(bob, gethPrefixHash, signB)); if (!s.init) { uint validity = now + 10 minutes; uint extendedValidity = validity + 10 minutes; s = VpcState(aliceCash, bobCash, version, validity, extendedValidity, true, true, true, true); emit EventVpcClosing(id); } if ((s.validity < now) && (msg.sender == alice || msg.sender == bob)) return; if (msg.sender == bob) s.waitingForBob = false; if (version > s.seqNo) { s = VpcState(aliceCash, bobCash, version, s.validity, s.extendedValidity, true, s.waitingForAlice, s.waitingForBob, true); } if (!s.waitingForAlice && !s.waitingForBob) { s.open = false; emit EventVpcClosed(id, s.AliceCash, s.BobCash); } states[id] = s; }
12,777,836
[ 1, 2503, 445, 353, 2566, 635, 1281, 14188, 434, 326, 5024, 1904, 2597, 353, 1399, 358, 18312, 279, 727, 7006, 434, 284, 19156, 316, 326, 5024, 1904, 19, 1924, 22056, 93, 14862, 309, 4123, 279, 5024, 1904, 919, 1552, 486, 1005, 4671, 16, 752, 1245, 444, 924, 434, 3186, 3287, 1836, 309, 3937, 18115, 7899, 785, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 1746, 12, 2867, 524, 1812, 16, 1758, 800, 70, 16, 2254, 7348, 16, 2254, 1177, 16, 2254, 524, 1812, 39, 961, 16, 2254, 800, 70, 39, 961, 16, 203, 5411, 1731, 1573, 37, 16, 1731, 1573, 38, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 524, 1812, 747, 1234, 18, 15330, 422, 800, 70, 1769, 203, 540, 203, 3639, 612, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 287, 1812, 16, 800, 70, 16, 7348, 10019, 203, 3639, 272, 273, 5493, 63, 350, 15533, 203, 540, 203, 3639, 1731, 1578, 1234, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 350, 16, 1177, 16, 524, 1812, 39, 961, 16, 800, 70, 39, 961, 10019, 203, 3639, 1731, 1578, 336, 76, 2244, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 31458, 89, 713, 3657, 41, 18664, 379, 16724, 2350, 5581, 82, 1578, 3113, 1234, 2310, 10019, 203, 3639, 2583, 12, 2941, 8267, 18, 8705, 12, 287, 1812, 16, 336, 76, 2244, 2310, 16, 1573, 37, 13, 7010, 7734, 597, 2561, 8267, 18, 8705, 12, 70, 947, 16, 336, 76, 2244, 2310, 16, 1573, 38, 10019, 203, 203, 3639, 309, 16051, 87, 18, 2738, 13, 288, 203, 5411, 2254, 13800, 273, 2037, 397, 1728, 6824, 31, 203, 5411, 2254, 7021, 19678, 273, 13800, 397, 1728, 6824, 31, 203, 5411, 272, 273, 26301, 1119, 12, 287, 1812, 39, 961, 16, 800, 70, 39, 961, 16, 1177, 16, 13800, 16, 7021, 2 ]
./partial_match/56/0xe23d9b272240a45A35a92ACCB41887318F036fEb/sources/project:/contracts/MyLvga.sol
2 minutes in seconds
txWindow = 2 * 60;
11,042,507
[ 1, 22, 6824, 316, 3974, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2229, 3829, 273, 576, 380, 4752, 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 ]
pragma solidity ^0.4.0; contract DataOwner_v3 { /* Public viewable valiables */ address public DO; // The DataOwner - owner of this contract int public Data_List_Length; // Length of the above data list int public taskCount; // Number of DataConsumer records so far uint public waitTimeOut; // Length of time DC needs to wait before asking for refund int public status; // 0: waiting for request(), 1: waiting for computationComplete(), // 2: waiting for completeTransaction() /* Internal variables */ uint totalPrice; address DC_cur; int op_cur; int avail_source_num; mapping(int => uint) data_WorkingList; struct dataSource_t { // Single data source type int data; int op; uint price; mapping(address => bool) DC_auth_list; } struct dataRecord_t { // Single data record type address DC; int op; uint DC_CompleteTime; // The time point when receiving computationComplete() from DC uint TransactionTime; // The time point when receiving completeTransaction() from DO/DB int Data_used; // Number of data used for computation string K_result; // A AESGCM-128 key (16 Bytes) for DC to decrypt computation result bytes32 K_result_hash; // SHA3 (keccak256) hash of K_result } /* Addition public viewable variables for book keeping */ mapping(int => dataSource_t) public dataSourceList; mapping(int => dataRecord_t) public dataRecordList; /* Contract creation */ constructor() public { DO = msg.sender; Data_List_Length = 0; taskCount = 0; status = 0; waitTimeOut = 600; // 10 min. increase it to 2 hrs in real case. } /* Handle register tx from DO: (Current design) all attributes can be changed simultaneously. */ // The value of data starts from 1 (data == 0 means no data). // To add a new DC: assign DC_action = 0. // To ban a old DC: assign DC_action = else. function register(int data, int op, uint price, address DC, int DC_action) public { if(msg.sender == DO) { if(dataSourceList[data-1].data == 0) { // new DO registration Data_List_Length ++; } dataSourceList[data-1].data = data; dataSourceList[data-1].op = op; dataSourceList[data-1].price = price; // in wei. When using remix, change to price*1000000000000000000 for convenience dataSourceList[data-1].DC_auth_list[DC] = (DC_action==0); // 0 <=> true } } /* Handle request tx from DC. */ // Assume the DC requests a specific data with desired operation. function request(int data_range_start, int data_range_end, int op) public payable { if(status != 0) { // Contract onhold, unable to accept new request from DC msg.sender.transfer(msg.value); // Return the value return; } totalPrice = 0; avail_source_num = 0; // avail_source_num is no bigger than 1 in this version for(int i=data_range_start-1; i<data_range_end && i<Data_List_Length; i++) { // Check only those data in range dataSource_t storage tmpDS = dataSourceList[i]; if(tmpDS.data != 0 && tmpDS.op == op && tmpDS.DC_auth_list[msg.sender] == true) { data_WorkingList[avail_source_num] = uint(i+1); avail_source_num ++; totalPrice += tmpDS.price; } } if(avail_source_num == 0 || msg.value < totalPrice) { // No available data sources or insufficient fund msg.sender.transfer(msg.value); // Return the value return; } if(msg.value > totalPrice) { msg.sender.transfer(msg.value - totalPrice); // Return the overpaid amount if there is any } DC_cur = msg.sender; op_cur = op; status = 1; } /* Handle computationComplete tx from DC */ function computationComplete(bytes32 K_result_hash) public { if(status != 1 || msg.sender != DC_cur) { return; } dataRecordList[taskCount].DC = msg.sender; dataRecordList[taskCount].op = op_cur; dataRecordList[taskCount].DC_CompleteTime = block.timestamp; dataRecordList[taskCount].K_result_hash = K_result_hash; dataRecordList[taskCount].Data_used = avail_source_num; status = 2; } /* Handle cancel tx from DC */ // Refund DC if timeout is met function cancel() public { if(status != 2 || msg.sender != DC_cur) { return; } if((block.timestamp - waitTimeOut) > dataRecordList[taskCount].DC_CompleteTime) { dataRecordList[taskCount].TransactionTime = block.timestamp; dataRecordList[taskCount].K_result = "Cancelled by DC."; taskCount ++; msg.sender.transfer(totalPrice); status = 0; } } /* Handle completeTransaction tx from DO/DB */ function completeTransaction(string K_result) public { if(status != 2 || msg.sender != DO) { return; } if(keccak256(abi.encodePacked(K_result)) == dataRecordList[taskCount].K_result_hash) { dataRecordList[taskCount].TransactionTime = block.timestamp; dataRecordList[taskCount].K_result = K_result; DO.transfer(totalPrice); taskCount ++; status = 0; } } /* Handle revoke tx from DB: Revoke the contract */ function revoke() public { if(status == 0 && msg.sender == DO) { if(address(this).balance > 0) { DO.transfer(address(this).balance); } selfdestruct(DO); } } }
10 min. increase it to 2 hrs in real case.
waitTimeOut = 600;
2,566,862
[ 1, 2163, 1131, 18, 10929, 518, 358, 576, 366, 5453, 316, 2863, 648, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 30452, 1182, 273, 14707, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract TheCoinBBToken { //币名字 string public name; //token 标志 string public symbol; ////token 小数位数 uint public decimals; //转账事件通知 event Transfer(address indexed from, address indexed to, uint256 value); // 创建一个数组存放所有用户的余额 mapping(address => uint256) public balanceOf; /* Constructor */ function TheCoinBBToken(uint256 initialSupply,string tokenName, string tokenSymbol, uint8 decimalUnits) public { //初始发币金额(总额要去除小数位数设置的长度) balanceOf[msg.sender] = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; } //转账操作 function transfer(address _to,uint256 _value) public { //检查转账是否满足条件 1.转出账户余额是否充足 2.转出金额是否大于0 并且是否超出限制 require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; //转账通知 Transfer(msg.sender, _to, _value); } }
币名字token 标志转账事件通知 创建一个数组存放所有用户的余额
contract TheCoinBBToken { string public name; string public symbol; uint public decimals; event Transfer(address indexed from, address indexed to, uint256 value); mapping(address => uint256) public balanceOf; function TheCoinBBToken(uint256 initialSupply,string tokenName, string tokenSymbol, uint8 decimalUnits) public { balanceOf[msg.sender] = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; } function transfer(address _to,uint256 _value) public { require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } }
12,867,780
[ 1, 166, 121, 228, 166, 243, 240, 166, 260, 250, 2316, 225, 167, 259, 234, 166, 128, 250, 169, 126, 110, 169, 117, 104, 165, 123, 238, 165, 124, 119, 170, 227, 253, 168, 258, 103, 225, 166, 235, 254, 166, 124, 123, 165, 121, 227, 165, 121, 108, 167, 248, 113, 168, 124, 231, 166, 260, 251, 167, 247, 127, 167, 236, 227, 167, 255, 236, 168, 247, 106, 167, 235, 120, 168, 253, 231, 165, 126, 252, 170, 100, 256, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1021, 27055, 9676, 1345, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 1071, 15105, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 203, 203, 565, 445, 1021, 27055, 9676, 1345, 12, 11890, 5034, 2172, 3088, 1283, 16, 1080, 1147, 461, 16, 533, 1147, 5335, 16, 2254, 28, 6970, 7537, 13, 1071, 288, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 2172, 3088, 1283, 31, 203, 3639, 508, 273, 1147, 461, 31, 4766, 7010, 3639, 3273, 273, 1147, 5335, 31, 27573, 203, 3639, 15105, 273, 6970, 7537, 31, 7010, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 11890, 5034, 389, 1132, 13, 1071, 288, 203, 3639, 2583, 12, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 597, 11013, 951, 63, 67, 869, 65, 397, 389, 1132, 1545, 11013, 951, 63, 67, 869, 19226, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 203, 3639, 11013, 951, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 3639, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.8; import './lib/SafeMath.sol'; interface ERC20 { function balanceOf(address guy) external view returns (uint); } /// @title Governance Protocol contract Governance { using SafeMath for uint256; struct Proposal { bytes title; // proposal title bytes description; // proposal description uint id; // proposal id uint voteWeightFor; // vote weight in support uint voteWeightAgainst; // vote weight against uint startTime; // start time since epoch bool result; // result of proposal bool resulted; // has someone called the result? } struct Vote { bool support; // if true: for; if false: against uint weight; // weight of vote bool voted; // has the user voted for this proposal already? } struct Voter { uint weight; // based on amount of funds locked in contract mapping(uint => Vote) votes; // map proposal id to vote } // ERC20 token ERC20 public token; Proposal[] public proposals; mapping(address => Voter) private voters; // Next id to be used for proposals uint private nextId; // Time limit to vote on proposals (in seconds) uint public timeLimit; // Set time limit and token contract address constructor(uint _timeLimit, address _token) public { timeLimit = _timeLimit; token = ERC20(_token); } // Submit a proposal for others to vote on function submitProposal(bytes memory _title, bytes memory _description) public { proposals.push(Proposal({ result: false, title: _title, description: _description, id: nextId, voteWeightFor: 0, voteWeightAgainst: 0, startTime: now, resulted: false })); nextId += 1; } // Vote for or against a proposal function submitVote(uint _proposalId, bool _support) public { Vote storage vote = voters[msg.sender].votes[_proposalId]; // Prevent voter from voting on same proposal more than once require(vote.voted == false, 'You have already voted on this proposal.'); require(proposals[_proposalId].startTime + timeLimit > now, 'The voting period has expired.'); voters[msg.sender].weight = sqrt(token.balanceOf(msg.sender)); vote.voted = true; vote.support = _support; if(_support == true) { proposals[_proposalId].voteWeightFor += voters[msg.sender].weight; } else { proposals[_proposalId].voteWeightAgainst += voters[msg.sender].weight; } } // Show the result of a proposal function result(uint _proposalId) public { Proposal memory proposal = proposals[_proposalId]; // Ensure the proposal duration is complete require((proposal.startTime + timeLimit) <= now, 'There is still time left in the proposal.'); proposals[_proposalId].resulted = true; if(proposal.voteWeightFor > proposal.voteWeightAgainst) { proposals[_proposalId].result = true; } // If there is a draw, the proposal is not passed if(proposal.voteWeightAgainst >= proposal.voteWeightFor) { proposals[_proposalId].result = false; } } // Get the total number of proposals function getProposalsLength() public view returns(uint) { return proposals.length; } // Calculate the approximate square root function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } }
Show the result of a proposal Ensure the proposal duration is complete If there is a draw, the proposal is not passed
function result(uint _proposalId) public { Proposal memory proposal = proposals[_proposalId]; require((proposal.startTime + timeLimit) <= now, 'There is still time left in the proposal.'); proposals[_proposalId].resulted = true; if(proposal.voteWeightFor > proposal.voteWeightAgainst) { proposals[_proposalId].result = true; } if(proposal.voteWeightAgainst >= proposal.voteWeightFor) { proposals[_proposalId].result = false; } }
6,478,203
[ 1, 5706, 326, 563, 434, 279, 14708, 7693, 326, 14708, 3734, 353, 3912, 971, 1915, 353, 279, 3724, 16, 326, 14708, 353, 486, 2275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 563, 12, 11890, 389, 685, 8016, 548, 13, 1071, 288, 203, 3639, 19945, 3778, 14708, 273, 450, 22536, 63, 67, 685, 8016, 548, 15533, 203, 3639, 2583, 12443, 685, 8016, 18, 1937, 950, 397, 813, 3039, 13, 1648, 2037, 16, 296, 9828, 353, 4859, 813, 2002, 316, 326, 14708, 1093, 1769, 203, 203, 3639, 450, 22536, 63, 67, 685, 8016, 548, 8009, 2088, 329, 273, 638, 31, 203, 203, 3639, 309, 12, 685, 8016, 18, 25911, 6544, 1290, 405, 14708, 18, 25911, 6544, 23530, 334, 13, 288, 203, 5411, 450, 22536, 63, 67, 685, 8016, 548, 8009, 2088, 273, 638, 31, 203, 3639, 289, 203, 3639, 309, 12, 685, 8016, 18, 25911, 6544, 23530, 334, 1545, 14708, 18, 25911, 6544, 1290, 13, 288, 203, 5411, 450, 22536, 63, 67, 685, 8016, 548, 8009, 2088, 273, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // ---------------------------------------------------------------------------- // Contract owner and transfer functions // just in case someone wants to get my bacon // ---------------------------------------------------------------------------- contract ContractOwned { address public contract_owner; address public contract_newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { contract_owner = msg.sender; } modifier contract_onlyOwner { require(msg.sender == contract_owner); _; } function transferOwnership(address _newOwner) public contract_onlyOwner { contract_newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == contract_newOwner); emit OwnershipTransferred(contract_owner, contract_newOwner); contract_owner = contract_newOwner; contract_newOwner = address(0); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, returns 0 if it would go into minus range. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { if (b >= a) { return 0; } return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * ERC721 compatibility from * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC721/ERC721Token.sol * plus our magic sauce */ /** * @title Custom CustomEvents * @dev some custom events specific to this contract */ contract CustomEvents { event ChibiCreated(uint tokenId, address indexed _owner, bool founder, string _name, uint16[13] dna, uint father, uint mother, uint gen, uint adult, string infoUrl); event ChibiForFusion(uint tokenId, uint price); event ChibiForFusionCancelled(uint tokenId); event WarriorCreated(uint tokenId, string battleRoar); } /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; function tokenMetadata(uint256 _tokenId) constant public returns (string infoUrl); function tokenURI(uint256 _tokenId) public view returns (string); } // interacting with gene contract contract GeneInterface { // creates genes when bought directly on this contract, they will always be superb // address, seed, founder, tokenId function createGenes(address, uint, bool, uint, uint) external view returns ( uint16[13] genes ); // transfusion chamber, no one really knows what that crazy thing does // except the scientists, but they giggle all day long // address, seed, tokenId function splitGenes(address, uint, uint) external view returns ( uint16[13] genes ); function exhaustAfterFusion(uint _gen, uint _counter, uint _exhaustionTime) public pure returns (uint); function exhaustAfterBattle(uint _gen, uint _exhaust) public pure returns (uint); } // interacting with fcf contract contract FcfInterface { function balanceOf(address) public pure returns (uint) {} function transferFrom(address, address, uint) public pure returns (bool) {} } // interacting with battle contract contract BattleInterface { function addWarrior(address, uint, uint8, string) pure public returns (bool) {} function isDead(uint) public pure returns (bool) {} } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ChibiFighters is ERC721, ContractOwned, CustomEvents { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // 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 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; // interfaces for other contracts, so updates are possible GeneInterface geneContract; FcfInterface fcfContract; BattleInterface battleContract; address battleContractAddress; // default price for 1 Chibi uint public priceChibi; // minimum price for fusion chibis uint priceFusionChibi; // counter that keeps upping with each token uint uniqueCounter; // time to become adult uint adultTime; // recovery time after each fusion uint exhaustionTime; // our comission uint comission; // battleRemoveContractAddress to remove from array address battleRemoveContractAddress; struct Chibi { // address of current chibi owner address owner; // belongs to og bool founder; // name of the chibi, chibis need names string nameChibi; // the dna, specifies, bodyparts, etc. // array is easier to decode, but we are not reinventing the wheel here uint16[13] dna; // originates from tokenIds, gen0s will return 0 // uint size only matters in structs uint256 father; uint256 mother; // generations, gen0 is created from the incubator, they are pure // but of course the funniest combos will come from the fusion chamber uint gen; // fusions, the beautiful fusion Chibis that came out of this one uint256[] fusions; // up for fusion? bool forFusion; // cost to fusion with this Chibi, can be set by player at will uint256 fusionPrice; // exhaustion after fusion uint256 exhausted; // block after which chibi is an adult uint256 adult; // info url string infoUrl; } // the link to chibis website string _infoUrlPrefix; Chibi[] public chibies; string public constant name = "Chibi Fighters"; string public constant symbol = "CBF"; // pause function so fusion and minting can be paused for updates bool paused; bool fcfPaused; bool fusionPaused; // needed so founder can fuse while game is paused /** * @dev Run only once at contract creation */ constructor() public { // a helping counter to keep chibis unique uniqueCounter = 0; // inital price in wei priceChibi = 100000000000000000; // default price to allow fusion priceFusionChibi = 10000000000000000; // time to become adult adultTime = 2 hours; //exhaustionTime = 3 hours; exhaustionTime = 1 hours; // start the contract paused paused = true; fcfPaused = true; fusionPaused = true; // set comission percentage 100-90 = 10% comission = 90; _infoUrlPrefix = "http://chibigame.io/chibis.php?idj="; } /** * @dev Set Comission rate 100-x = % * @param _comission Rate inverted */ function setComission(uint _comission) public contract_onlyOwner returns(bool success) { comission = _comission; return true; } /** * @dev Set minimum price for fusion Chibis in Wei */ function setMinimumPriceFusion(uint _price) public contract_onlyOwner returns(bool success) { priceFusionChibi = _price; return true; } /** * @dev Set time until Chibi is considered adult * @param _adultTimeSecs Set time in seconds */ function setAdultTime(uint _adultTimeSecs) public contract_onlyOwner returns(bool success) { adultTime = _adultTimeSecs; return true; } /** * @dev Fusion Chamber Cool down * @param _exhaustionTime Set time in seconds */ function setExhaustionTime(uint _exhaustionTime) public contract_onlyOwner returns(bool success) { exhaustionTime = _exhaustionTime; return true; } /** * @dev Set game state paused for updates, pauses the entire creation * @param _setPaused Boolean sets the game paused or not */ function setGameState(bool _setPaused) public contract_onlyOwner returns(bool _paused) { paused = _setPaused; fcfPaused = _setPaused; fusionPaused = _setPaused; return paused; } /** * @dev Set game state for fcf tokens only, so Founder can get Chibis pre launch * @param _setPaused Boolean sets the game paused or not */ function setGameStateFCF(bool _setPaused) public contract_onlyOwner returns(bool _pausedFCF) { fcfPaused = _setPaused; return fcfPaused; } /** * @dev unpause Fusions so Founder can Fuse * @param _setPaused Boolean sets the game paused or not */ function setGameStateFusion(bool _setPaused) public contract_onlyOwner returns(bool _pausedFusions) { fusionPaused = _setPaused; return fusionPaused; } /** * @dev Query game state. Paused (True) or not? */ function getGameState() public constant returns(bool _paused) { return paused; } /** * @dev Set url prefix, of course that won`t change the existing Chibi urls on chain */ function setInfoUrlPrefix(string prefix) external contract_onlyOwner returns (bool success) { _infoUrlPrefix = prefix; return true; } /** * @dev Connect to Founder contract so user can pay in FCF */ function setFcfContractAddress(address _address) external contract_onlyOwner returns (bool success) { fcfContract = FcfInterface(_address); return true; } /** * @dev Connect to Battle contract */ function setBattleContractAddress(address _address) external contract_onlyOwner returns (bool success) { battleContract = BattleInterface(_address); battleContractAddress = _address; return true; } /** * @dev Connect to Battle contract */ function setBattleRemoveContractAddress(address _address) external contract_onlyOwner returns (bool success) { battleRemoveContractAddress = _address; return true; } /** * @dev Rename a Chibi * @param _tokenId ID of the Chibi * @param _name Name of the Chibi */ function renameChibi(uint _tokenId, string _name) public returns (bool success){ require(ownerOf(_tokenId) == msg.sender); chibies[_tokenId].nameChibi = _name; return true; } /** * @dev Has chibi necromancer trait? * @param _tokenId ID of the chibi */ function isNecromancer(uint _tokenId) public view returns (bool) { for (uint i=10; i<13; i++) { if (chibies[_tokenId].dna[i] == 1000) { return true; } } return false; } /** * @dev buy Chibis with Founders */ function buyChibiWithFcf(string _name, string _battleRoar, uint8 _region, uint _seed) public returns (bool success) { // must own at least 1 FCF, only entire FCF can be swapped for Chibis require(fcfContract.balanceOf(msg.sender) >= 1 * 10 ** 18); require(fcfPaused == false); // prevent hack uint fcfBefore = fcfContract.balanceOf(address(this)); // user must approved Founders contract to take tokens from account // oh my, this will need a tutorial video // always only take 1 Founder at a time if (fcfContract.transferFrom(msg.sender, this, 1 * 10 ** 18)) { _mint(_name, _battleRoar, _region, _seed, true, 0); } // prevent hacking assert(fcfBefore == fcfContract.balanceOf(address(this)) - 1 * 10 ** 18); return true; } /** * @dev Put Chibi up for fusion, this will not destroy your Chibi. Only adults can fuse. * @param _tokenId Id of Chibi token that is for fusion * @param _price Price for the chibi in wei */ function setChibiForFusion(uint _tokenId, uint _price) public returns (bool success) { require(ownerOf(_tokenId) == msg.sender); require(_price >= priceFusionChibi); require(chibies[_tokenId].adult <= now); require(chibies[_tokenId].exhausted <= now); require(chibies[_tokenId].forFusion == false); require(battleContract.isDead(_tokenId) == false); chibies[_tokenId].forFusion = true; chibies[_tokenId].fusionPrice = _price; emit ChibiForFusion(_tokenId, _price); return true; } function cancelChibiForFusion(uint _tokenId) public returns (bool success) { if (ownerOf(_tokenId) != msg.sender && msg.sender != address(battleRemoveContractAddress)) { revert(); } require(chibies[_tokenId].forFusion == true); chibies[_tokenId].forFusion = false; emit ChibiForFusionCancelled(_tokenId); return false; } /** * @dev Connect to gene contract. That way we can update that contract and add more fighters. */ function setGeneContractAddress(address _address) external contract_onlyOwner returns (bool success) { geneContract = GeneInterface(_address); return true; } /** * @dev Fusions cost too much so they are here * @return All the fusions (babies) of tokenId */ function queryFusionData(uint _tokenId) public view returns ( uint256[] fusions, bool forFusion, uint256 costFusion, uint256 adult, uint exhausted ) { return ( chibies[_tokenId].fusions, chibies[_tokenId].forFusion, chibies[_tokenId].fusionPrice, chibies[_tokenId].adult, chibies[_tokenId].exhausted ); } /** * @dev Minimal query for battle contract * @return If for fusion */ function queryFusionData_ext(uint _tokenId) public view returns ( bool forFusion, uint fusionPrice ) { return ( chibies[_tokenId].forFusion, chibies[_tokenId].fusionPrice ); } /** * @dev Triggers a Chibi event to get some data of token * @return various */ function queryChibi(uint _tokenId) public view returns ( string nameChibi, string infoUrl, uint16[13] dna, uint256 father, uint256 mother, uint gen, uint adult ) { return ( chibies[_tokenId].nameChibi, chibies[_tokenId].infoUrl, chibies[_tokenId].dna, chibies[_tokenId].father, chibies[_tokenId].mother, chibies[_tokenId].gen, chibies[_tokenId].adult ); } /** * @dev Triggers a Chibi event getting some additional data * @return various */ function queryChibiAdd(uint _tokenId) public view returns ( address owner, bool founder ) { return ( chibies[_tokenId].owner, chibies[_tokenId].founder ); } // exhaust after battle function exhaustBattle(uint _tokenId) internal view returns (uint) { uint _exhaust = 0; for (uint i=10; i<13; i++) { if (chibies[_tokenId].dna[i] == 1) { _exhaust += (exhaustionTime * 3); } if (chibies[_tokenId].dna[i] == 3) { _exhaust += exhaustionTime.div(2); } } _exhaust = geneContract.exhaustAfterBattle(chibies[_tokenId].gen, _exhaust); return _exhaust; } // exhaust after fusion function exhaustFusion(uint _tokenId) internal returns (uint) { uint _exhaust = 0; uint counter = chibies[_tokenId].dna[9]; // set dna here, that way boni still apply but not infinite fusions possible // max value 9999 if (chibies[_tokenId].dna[9] < 9999) chibies[_tokenId].dna[9]++; for (uint i=10; i<13; i++) { if (chibies[_tokenId].dna[i] == 2) { counter = counter.sub(1); } if (chibies[_tokenId].dna[i] == 4) { counter++; } } _exhaust = geneContract.exhaustAfterFusion(chibies[_tokenId].gen, counter, exhaustionTime); return _exhaust; } /** * @dev Exhaust Chibis after battle */ function exhaustChibis(uint _tokenId1, uint _tokenId2) public returns (bool success) { require(msg.sender == battleContractAddress); chibies[_tokenId1].exhausted = now.add(exhaustBattle(_tokenId1)); chibies[_tokenId2].exhausted = now.add(exhaustBattle(_tokenId2)); return true; } /** * @dev Split traits between father and mother and leave the random at the _tokenId2 */ function traits(uint16[13] memory genes, uint _seed, uint _fatherId, uint _motherId) internal view returns (uint16[13] memory) { uint _switch = uint136(keccak256(_seed, block.coinbase, block.timestamp)) % 5; if (_switch == 0) { genes[10] = chibies[_fatherId].dna[10]; genes[11] = chibies[_motherId].dna[11]; } if (_switch == 1) { genes[10] = chibies[_motherId].dna[10]; genes[11] = chibies[_fatherId].dna[11]; } if (_switch == 2) { genes[10] = chibies[_fatherId].dna[10]; genes[11] = chibies[_fatherId].dna[11]; } if (_switch == 3) { genes[10] = chibies[_motherId].dna[10]; genes[11] = chibies[_motherId].dna[11]; } return genes; } /** * @dev The fusion chamber combines both dnas and adds a generation. */ function fusionChibis(uint _fatherId, uint _motherId, uint _seed, string _name, string _battleRoar, uint8 _region) payable public returns (bool success) { require(fusionPaused == false); require(ownerOf(_fatherId) == msg.sender); require(ownerOf(_motherId) != msg.sender); require(chibies[_fatherId].adult <= now); require(chibies[_fatherId].exhausted <= now); require(chibies[_motherId].adult <= now); require(chibies[_motherId].exhausted <= now); require(chibies[_motherId].forFusion == true); require(chibies[_motherId].fusionPrice == msg.value); // exhaust father and mother chibies[_motherId].forFusion = false; chibies[_motherId].exhausted = now.add(exhaustFusion(_motherId)); chibies[_fatherId].exhausted = now.add(exhaustFusion(_fatherId)); uint _gen = 0; if (chibies[_fatherId].gen >= chibies[_motherId].gen) { _gen = chibies[_fatherId].gen.add(1); } else { _gen = chibies[_motherId].gen.add(1); } // fusion chamber here we come uint16[13] memory dna = traits(geneContract.splitGenes(address(this), _seed, uniqueCounter+1), _seed, _fatherId, _motherId); // new Chibi is born! addToken(msg.sender, uniqueCounter); // father and mother get the chibi in their fusion list chibies[_fatherId].fusions.push(uniqueCounter); // only add if mother different than father, otherwise double entry if (_fatherId != _motherId) { chibies[_motherId].fusions.push(uniqueCounter); } // baby Chibi won't have fusions uint[] memory _fusions; // baby Chibis can't be fused chibies.push(Chibi( msg.sender, false, _name, dna, _fatherId, _motherId, _gen, _fusions, false, priceFusionChibi, 0, now.add(adultTime.mul((_gen.mul(_gen)).add(1))), strConcat(_infoUrlPrefix, uint2str(uniqueCounter)) )); // fires chibi created event emit ChibiCreated( uniqueCounter, chibies[uniqueCounter].owner, chibies[uniqueCounter].founder, chibies[uniqueCounter].nameChibi, chibies[uniqueCounter].dna, chibies[uniqueCounter].father, chibies[uniqueCounter].mother, chibies[uniqueCounter].gen, chibies[uniqueCounter].adult, chibies[uniqueCounter].infoUrl ); // send transfer event emit Transfer(0x0, msg.sender, uniqueCounter); // create Warrior if (battleContract.addWarrior(address(this), uniqueCounter, _region, _battleRoar) == false) revert(); uniqueCounter ++; // transfer money to seller minus our share, remain stays in contract uint256 amount = msg.value / 100 * comission; chibies[_motherId].owner.transfer(amount); return true; } /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @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 totalTokens; } /** * @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) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner 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)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @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 onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } function mintSpecial(string _name, string _battleRoar, uint8 _region, uint _seed, uint _specialId) public contract_onlyOwner returns (bool success) { // name can be empty _mint(_name, _battleRoar, _region, _seed, false, _specialId); return true; } /** * @dev Mint token function * @param _name name of the Chibi */ function _mint(string _name, string _battleRoar, uint8 _region, uint _seed, bool _founder, uint _specialId) internal { require(msg.sender != address(0)); addToken(msg.sender, uniqueCounter); // creates a gen0 Chibi, no father, mother, gen0 uint16[13] memory dna; if (_specialId > 0) { dna = geneContract.createGenes(address(this), _seed, _founder, uniqueCounter, _specialId); } else { dna = geneContract.createGenes(address(this), _seed, _founder, uniqueCounter, 0); } uint[] memory _fusions; chibies.push(Chibi( msg.sender, _founder, _name, dna, 0, 0, 0, _fusions, false, priceFusionChibi, 0, now.add(adultTime), strConcat(_infoUrlPrefix, uint2str(uniqueCounter)) )); // send transfer event emit Transfer(0x0, msg.sender, uniqueCounter); // create Warrior if (battleContract.addWarrior(address(this), uniqueCounter, _region, _battleRoar) == false) revert(); // fires chibi created event emit ChibiCreated( uniqueCounter, chibies[uniqueCounter].owner, chibies[uniqueCounter].founder, chibies[uniqueCounter].nameChibi, chibies[uniqueCounter].dna, chibies[uniqueCounter].father, chibies[uniqueCounter].mother, chibies[uniqueCounter].gen, chibies[uniqueCounter].adult, chibies[uniqueCounter].infoUrl ); uniqueCounter ++; } /** * @dev buy gen0 chibis * @param _name name of the Chibi */ function buyGEN0Chibi(string _name, string _battleRoar, uint8 _region, uint _seed) payable public returns (bool success) { require(paused == false); // cost at least 100 wei require(msg.value == priceChibi); // name can be empty _mint(_name, _battleRoar, _region, _seed, false, 0); return true; } /** * @dev set default sale price of Chibies * @param _priceChibi price of 1 Chibi in Wei */ function setChibiGEN0Price(uint _priceChibi) public contract_onlyOwner returns (bool success) { priceChibi = _priceChibi; return true; } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); // Chibbi code chibies[_tokenId].owner = _to; chibies[_tokenId].forFusion = false; emit Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; emit Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @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 addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens++; } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } /** * @dev Send Ether to owner * @param _address Receiving address * @param amount Amount in WEI to send **/ function weiToOwner(address _address, uint amount) public contract_onlyOwner { require(amount <= address(this).balance); _address.transfer(amount); } /** * @dev Return the infoUrl of Chibi * @param _tokenId infoUrl of _tokenId **/ function tokenMetadata(uint256 _tokenId) constant public returns (string infoUrl) { return chibies[_tokenId].infoUrl; } function tokenURI(uint256 _tokenId) public view returns (string) { return chibies[_tokenId].infoUrl; } // // some helpful functions // https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol // function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } }
* @dev Approves another address to claim for the ownership of the given token ID @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 onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } }
12,725,645
[ 1, 12053, 3324, 4042, 1758, 358, 7516, 364, 326, 23178, 434, 326, 864, 1147, 1599, 225, 389, 869, 1758, 358, 506, 20412, 364, 326, 864, 1147, 1599, 225, 389, 2316, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 20412, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 1071, 1338, 5541, 951, 24899, 2316, 548, 13, 288, 203, 3639, 1758, 3410, 273, 3410, 951, 24899, 2316, 548, 1769, 203, 3639, 2583, 24899, 869, 480, 3410, 1769, 203, 3639, 309, 261, 25990, 1290, 24899, 2316, 548, 13, 480, 374, 747, 389, 869, 480, 374, 13, 288, 203, 5411, 1147, 12053, 4524, 63, 67, 2316, 548, 65, 273, 389, 869, 31, 203, 5411, 3626, 1716, 685, 1125, 12, 8443, 16, 389, 869, 16, 389, 2316, 548, 1769, 203, 3639, 289, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.10; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./StakingStorage.sol"; contract Staking is Ownable, Pausable, Initializable , StakingStorage { event Deposit(address indexed staker, uint indexed amount, uint depositTime); event AddMoreStake(address indexed staker, uint amount); event Unstake(address indexed staker, uint amount); event SetWhitelist(address indexed staker, bool isEnable); modifier onlyWhitelist() { require(whitelist[msg.sender] == true, "STAKING: Only whitelist"); _; } function initialize(address cra, uint min, uint max, uint _slippage, address _owner) external initializer() { CRAToken = cra; unstakedEpoch = 28; // wait to 28 days to withdraw stake minStakedAmount = min; maxStakedAmount = max; slippage = _slippage; _transferOwnership(_owner); } function deposit(uint amount) external whenNotPaused() onlyWhitelist(){ require(amount >= minStakedAmount, "STAKING: less than minimum amount"); require(amount <= maxStakedAmount, "STAKING: greater than maximum amount"); Validator storage user = validatorInfo[msg.sender]; require(user.stakedAmount == 0 && user.depositTime == 0, "STAKING: already deposited"); IERC20(CRAToken).transferFrom(msg.sender, address(this), amount); user.stakedAmount = amount; user.depositTime = block.timestamp; //update total stake totalStake = totalStake + amount; emit Deposit(msg.sender, amount, block.timestamp); } function addMoreStake(uint amount) external whenNotPaused() onlyWhitelist() { Validator storage user = validatorInfo[msg.sender]; uint current = user.stakedAmount; require(user.depositTime > 0, "STAKING: has not deposited"); require(current + amount <= maxStakedAmount, "STAKING: exceed max amount"); IERC20(CRAToken).transferFrom(msg.sender, address(this), amount); user.stakedAmount = current + amount; //update total stake totalStake = totalStake + amount; emit AddMoreStake(msg.sender, amount); } function calculate(uint depositTime) internal view returns(uint, uint){ uint r = (block.timestamp - depositTime)/day; uint remainder = r % unstakedEpoch; uint quotient = r / unstakedEpoch; return (quotient, remainder); } function unstake() external whenNotPaused() onlyWhitelist(){ Validator storage user = validatorInfo[msg.sender]; (uint quotient, uint remainder) = calculate(user.depositTime); require(quotient > 0, "STAKING: not allow to unstake"); require(remainder < slippage, "STAKING: can not unstake due to overtime"); uint amount = user.stakedAmount; user.stakedAmount = 0; //update staked amount user.depositTime = 0; totalStake = totalStake - amount; IERC20(CRAToken).transfer(msg.sender, amount); emit Unstake(msg.sender, amount); } function setWhitelist(address[] calldata stakers, bool[] calldata tf) external onlyOwner() { require(stakers.length == tf.length, "STAKING: invalid params length"); for(uint i; i < stakers.length; i++){ whitelist[stakers[i]] = tf[i]; emit SetWhitelist(stakers[i], tf[i]); } } function changeMinimumStake(uint value) external onlyOwner(){ minStakedAmount = value; } function changeMaximumStake(uint value) external onlyOwner(){ maxStakedAmount = value; } function changeUnstakeEpoch(uint value) external onlyOwner(){ unstakedEpoch = value; } function changeSlippage(uint256 value) external onlyOwner() { slippage = value; } function setPause(bool isPaused) external onlyOwner() { if (isPaused) { _pause(); } else { _unpause(); } } }
wait to 28 days to withdraw stake
unstakedEpoch = 28;
12,786,651
[ 1, 7048, 358, 9131, 4681, 358, 598, 9446, 384, 911, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 640, 334, 9477, 14638, 273, 9131, 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 ]
./full_match/1/0x90c3803BCCf9cC64A0226FbbFE9C471E4F3eA0D2/sources/DDOB.sol
100,000,000,000 tokens with 9 decimal places
_totalSupply = 100000000000 * 10**9;
8,371,337
[ 1, 6625, 16, 3784, 16, 3784, 16, 3784, 2430, 598, 2468, 6970, 12576, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 4963, 3088, 1283, 273, 15088, 11706, 380, 1728, 636, 29, 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 ]
./partial_match/1/0xDf2BF3ef4F5c9DC69E3a6642Fa3168327EE1cdd7/sources/IBurner.sol
Gro burner interface - used to move gro tokens into the vesting contract
interface IBurner { function reVest(uint256 amount) external; pragma solidity ^0.8.12; }
16,195,079
[ 1, 43, 303, 18305, 264, 1560, 300, 1399, 358, 3635, 314, 303, 2430, 1368, 326, 331, 10100, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 23450, 321, 264, 288, 203, 565, 445, 283, 58, 395, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2138, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /* Internal Imports */ import { CanonicalTransactionChain } from "./CanonicalTransactionChain.sol"; import { StateCommitmentChain } from "./StateCommitmentChain.sol"; /** * @title SequencerBatchSubmitter * @notice Helper contract that allows the sequencer to submit both a state * commitment batch and tx batch in a single transaction. This ensures * that # state roots == # of txs, preventing other users from * submitting state batches to the state chain. */ contract SequencerBatchSubmitter { /* * Contract Variables */ CanonicalTransactionChain canonicalTransactionChain; StateCommitmentChain stateCommitmentChain; address public sequencer; /* * Modifiers */ modifier onlySequencer () { require( msg.sender == sequencer, "Only the sequencer may perform this action" ); _; } /* * Constructor */ constructor(address _sequencer) public { sequencer = _sequencer; } /* * Public Functions */ function initialize( address _canonicalTransactionChain, address _stateCommitmentChain ) public onlySequencer { canonicalTransactionChain = CanonicalTransactionChain(_canonicalTransactionChain); stateCommitmentChain = StateCommitmentChain(_stateCommitmentChain); } /** * @notice Append equal sized batches of transactions and state roots to * their respective chains. * @param _txBatch An array of transactions. * @param _txBatchTimestamp The timestamp that will be submitted with the * tx batch - this timestamp will likely lag * behind the actual time by a few minutes. * @param _stateBatch An array of 32 byte state roots */ function appendTransitionBatch( bytes[] memory _txBatch, uint _txBatchTimestamp, bytes[] memory _stateBatch ) public onlySequencer { require( _stateBatch.length == _txBatch.length, "Must append the same number of state roots and transactions" ); canonicalTransactionChain.appendSequencerBatch(_txBatch, _txBatchTimestamp); stateCommitmentChain.appendStateBatch(_stateBatch); } }
* @notice Append equal sized batches of transactions and state roots to their respective chains. @param _txBatch An array of transactions. @param _txBatchTimestamp The timestamp that will be submitted with the tx batch - this timestamp will likely lag behind the actual time by a few minutes. @param _stateBatch An array of 32 byte state roots/
function appendTransitionBatch( bytes[] memory _txBatch, uint _txBatchTimestamp, bytes[] memory _stateBatch ) public onlySequencer { require( _stateBatch.length == _txBatch.length, "Must append the same number of state roots and transactions" ); canonicalTransactionChain.appendSequencerBatch(_txBatch, _txBatchTimestamp); stateCommitmentChain.appendStateBatch(_stateBatch); }
12,692,561
[ 1, 5736, 3959, 26046, 13166, 434, 8938, 471, 919, 12876, 358, 540, 3675, 17613, 13070, 18, 225, 389, 978, 4497, 1922, 526, 434, 8938, 18, 225, 389, 978, 4497, 4921, 1021, 2858, 716, 903, 506, 9638, 598, 326, 12900, 2229, 2581, 300, 333, 2858, 903, 10374, 17241, 12900, 21478, 326, 3214, 813, 635, 279, 11315, 6824, 18, 225, 389, 2019, 4497, 1922, 526, 434, 3847, 1160, 919, 12876, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 714, 8850, 4497, 12, 203, 3639, 1731, 8526, 3778, 389, 978, 4497, 16, 203, 3639, 2254, 389, 978, 4497, 4921, 16, 203, 3639, 1731, 8526, 3778, 389, 2019, 4497, 203, 565, 262, 1071, 1338, 1761, 372, 23568, 288, 203, 3639, 2583, 12, 203, 5411, 389, 2019, 4497, 18, 2469, 422, 389, 978, 4497, 18, 2469, 16, 203, 5411, 315, 10136, 714, 326, 1967, 1300, 434, 919, 12876, 471, 8938, 6, 203, 3639, 11272, 203, 203, 3639, 7378, 3342, 3893, 18, 6923, 1761, 372, 23568, 4497, 24899, 978, 4497, 16, 389, 978, 4497, 4921, 1769, 203, 3639, 919, 5580, 475, 3893, 18, 6923, 1119, 4497, 24899, 2019, 4497, 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 ]
./full_match/1/0xb2883633995c5a88073db20CE6C658EC1f459d46/sources/contracts/TestUpcycleThird.sol
* @notice Sets the uri suffix @param _uriSuffix string/
function setUriSuffix(string calldata _uriSuffix) external onlyOwner { uriSuffix = _uriSuffix; }
3,078,385
[ 1, 2785, 326, 2003, 3758, 225, 389, 1650, 5791, 533, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30473, 5791, 12, 1080, 745, 892, 389, 1650, 5791, 13, 3903, 1338, 5541, 288, 203, 3639, 2003, 5791, 273, 389, 1650, 5791, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-06-01 */ pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract KillerShiba is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "KillerShiba"; symbol = "KSHIB"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "KillerShiba"; symbol = "KSHIB"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
6,845,456
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 19045, 264, 1555, 495, 69, 14432, 203, 3639, 3273, 273, 315, 47, 2664, 13450, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 17877, 31, 203, 540, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "add: +"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "sub: -"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, "mul: *"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "div: /"); } /** * @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { return mod(a, b, "mod: %"); } /** * @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { 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]. */ 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; } } interface IGovernance { function proposeJob(address job) external returns (uint); } interface IKeep3rHelper { function getQuoteLimit(uint gasUsed) external view returns (uint); } /** * @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 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"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value:amount}(""); require(success, "Address: reverted"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: < 0"); 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: !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: !succeed"); } } } contract Keep3r is ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; /// @notice Keep3r Helper to set max prices for the ecosystem IKeep3rHelper public KPRH; /// @notice EIP-20 token name for this token string public constant name = "Keep3r"; /// @notice EIP-20 token symbol for this token string public constant symbol = "KPR"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 0; // Initial 0 /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: sig"); require(nonce == nonces[signatory]++, "delegateBySig: nonce"); require(now <= expiry, "delegateBySig: expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint) { require(blockNumber < block.number, "getPriorVotes:"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint delegatorBalance = votes[delegator].add(bonds[delegator][address(this)]); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.sub(amount, "_moveVotes: underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { uint32 blockNumber = safe32(block.number, "_writeCheckpoint: 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Submit a job event SubmitJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Apply credit to a job event ApplyCredit(address indexed job, address indexed provider, uint block, uint credit); /// @notice Remove credit for a job event RemoveJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Unbond credit for a job event UnbondJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Added a Job event JobAdded(address indexed job, uint block, address governance); /// @notice Removed a job event JobRemoved(address indexed job, uint block, address governance); /// @notice Worked a job event KeeperWorked(address indexed credit, address indexed job, address indexed keeper, uint block); /// @notice Keeper bonding event KeeperBonding(address indexed keeper, uint block, uint active, uint bond); /// @notice Keeper bonded event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond); /// @notice Keeper unbonding event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond); /// @notice Keeper unbound event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond); /// @notice Keeper slashed event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash); /// @notice Keeper disputed event KeeperDispute(address indexed keeper, uint block); /// @notice Keeper resolved event KeeperResolved(address indexed keeper, uint block); event AddCredit(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount); /// @notice 1 day to bond to become a keeper uint constant public BOND = 3 days; /// @notice 14 days to unbond to remove funds from being a keeper uint constant public UNBOND = 14 days; /// @notice 7 days maximum downtime before being slashed uint constant public DOWNTIME = 7 days; /// @notice 3 days till liquidity can be bound uint constant public LIQUIDITYBOND = 3 days; /// @notice direct liquidity fee 0.3% uint constant public FEE = 30; /// @notice 5% of funds slashed for downtime uint constant public DOWNTIMESLASH = 500; uint constant public BASE = 10000; /// @notice address used for ETH transfers address constant public ETH = address(0xE); /// @notice tracks all current bondings (time) mapping(address => mapping(address => uint)) public bondings; /// @notice tracks all current unbondings (time) mapping(address => mapping(address => uint)) public unbondings; /// @notice allows for partial unbonding mapping(address => mapping(address => uint)) public partialUnbonding; /// @notice tracks all current pending bonds (amount) mapping(address => mapping(address => uint)) public pendingbonds; /// @notice tracks how much a keeper has bonded mapping(address => mapping(address => uint)) public bonds; /// @notice tracks underlying votes (that don't have bond) mapping(address => uint) public votes; /// @notice total bonded (totalSupply for bonds) uint public totalBonded = 0; /// @notice tracks when a keeper was first registered mapping(address => uint) public firstSeen; /// @notice tracks if a keeper has a pending dispute mapping(address => bool) public disputes; /// @notice tracks last job performed for a keeper mapping(address => uint) public lastJob; /// @notice tracks the total job executions for a keeper mapping(address => uint) public workCompleted; /// @notice list of all jobs registered for the keeper system mapping(address => bool) public jobs; /// @notice the current credit available for a job mapping(address => mapping(address => uint)) public credits; /// @notice the balances for the liquidity providers mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; /// @notice liquidity unbonding days mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; /// @notice liquidity unbonding amounts mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; /// @notice job proposal delay mapping(address => uint) public jobProposalDelay; /// @notice liquidity apply date mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; /// @notice liquidity amount to apply mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; /// @notice list of all current keepers mapping(address => bool) public keepers; /// @notice blacklist of keepers not allowed to participate mapping(address => bool) public blacklist; /// @notice traversable array of keepers to make external management easier address[] public keeperList; /// @notice traversable array of jobs to make external management easier address[] public jobList; /// @notice governance address for the governance contract address public governance; address public pendingGovernance; /// @notice the liquidity token supplied by users paying for jobs mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal _gasUsed; constructor() public { // Set governance for this token governance = msg.sender; } /** * @notice Add ETH credit to a job to be paid out for work * @param job the job being credited */ function addCreditETH(address job) external payable { require(jobs[job], "addCreditETH: !job"); uint _fee = msg.value.mul(FEE).div(BASE); credits[job][ETH] = credits[job][ETH].add(msg.value.sub(_fee)); payable(governance).transfer(_fee); emit AddCredit(ETH, job, msg.sender, block.number, msg.value); } /** * @notice Add credit to a job to be paid out for work * @param credit the credit being assigned to the job * @param job the job being credited * @param amount the amount of credit being added to the job */ function addCredit(address credit, address job, uint amount) external nonReentrant { require(jobs[job], "addCreditETH: !job"); uint _before = IERC20(credit).balanceOf(address(this)); IERC20(credit).safeTransferFrom(msg.sender, address(this), amount); uint _received = IERC20(credit).balanceOf(address(this)).sub(_before); uint _fee = _received.mul(FEE).div(BASE); credits[job][credit] = credits[job][credit].add(_received.sub(_fee)); IERC20(credit).safeTransfer(governance, _fee); emit AddCredit(credit, job, msg.sender, block.number, _received); } /** * @notice Add non transferable votes for governance * @param voter to add the votes to * @param amount of votes to add */ function addVotes(address voter, uint amount) external { require(msg.sender == governance, "addVotes: !gov"); votes[voter] = votes[voter].add(amount); totalBonded = totalBonded.add(amount); _moveDelegates(address(0), delegates[voter], amount); } /** * @notice Remove non transferable votes for governance * @param voter to subtract the votes * @param amount of votes to remove */ function removeVotes(address voter, uint amount) external { require(msg.sender == governance, "addVotes: !gov"); votes[voter] = votes[voter].sub(amount); totalBonded = totalBonded.sub(amount); _moveDelegates(delegates[voter], address(0), amount); } /** * @notice Add credit to a job to be paid out for work * @param job the job being credited * @param amount the amount of credit being added to the job */ function addKPRCredit(address job, uint amount) external { require(msg.sender == governance, "addKPRCredit: !gov"); require(jobs[job], "addKPRCredit: !job"); credits[job][address(this)] = credits[job][address(this)].add(amount); emit AddCredit(address(this), job, msg.sender, block.number, amount); } /** * @notice Approve a liquidity pair for being accepted in future * @param liquidity the liquidity no longer accepted */ function approveLiquidity(address liquidity) external { require(msg.sender == governance, "approveLiquidity: !gov"); require(!liquidityAccepted[liquidity], "approveLiquidity: !pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } /** * @notice Revoke a liquidity pair from being accepted in future * @param liquidity the liquidity no longer accepted */ function revokeLiquidity(address liquidity) external { require(msg.sender == governance, "revokeLiquidity: !gov"); liquidityAccepted[liquidity] = false; } /** * @notice Displays all accepted liquidity pairs */ function pairs() external view returns (address[] memory) { return liquidityPairs; } /** * @notice Allows liquidity providers to submit jobs * @param liquidity the liquidity being added * @param job the job to assign credit to * @param amount the amount of liquidity tokens to use */ function addLiquidityToJob(address liquidity, address job, uint amount) external nonReentrant { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); IERC20(liquidity).safeTransferFrom(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount); liquidityApplied[msg.sender][liquidity][job] = now.add(LIQUIDITYBOND); liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount); if (!jobs[job] && jobProposalDelay[job] < now) { IGovernance(governance).proposeJob(job); jobProposalDelay[job] = now.add(UNBOND); } emit SubmitJob(job, msg.sender, block.number, amount); } /** * @notice Applies the credit provided in addLiquidityToJob to the job * @param provider the liquidity provider * @param liquidity the pair being added as liquidity * @param job the job that is receiving the credit */ function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond"); require(liquidityApplied[provider][liquidity][job] < now, "credit: bonding"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(liquidityAmount[provider][liquidity][job]).div(IERC20(liquidity).totalSupply()); _mint(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].add(_credit); liquidityAmount[provider][liquidity][job] = 0; emit ApplyCredit(job, provider, block.number, _credit); } /** * @notice Unbond liquidity for a job * @param liquidity the pair being unbound * @param job the job being unbound from * @param amount the amount of liquidity being removed */ function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit"); liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "unbondLiquidityFromJob: insufficient funds"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(amount).div(IERC20(liquidity).totalSupply()); if (_credit > credits[job][address(this)]) { _burn(address(this), credits[job][address(this)]); credits[job][address(this)] = 0; } else { _burn(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].sub(_credit); } emit UnbondJob(job, msg.sender, block.number, amount); } /** * @notice Allows liquidity providers to remove liquidity * @param liquidity the pair being unbound * @param job the job being unbound from */ function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "removeJob: unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; IERC20(liquidity).safeTransfer(msg.sender, _amount); emit RemoveJob(job, msg.sender, block.number, _amount); } /** * @notice Allows governance to mint new tokens to treasury * @param amount the amount of tokens to mint to treasury */ function mint(uint amount) external { require(msg.sender == governance, "mint: !gov"); _mint(governance, amount); } /** * @notice burn owned tokens * @param amount the amount of tokens to burn */ function burn(uint amount) external { _burn(msg.sender, amount); } function _mint(address dst, uint amount) internal { // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { require(dst != address(0), "_burn: zero address"); balances[dst] = balances[dst].sub(amount, "_burn: exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(dst, address(0), amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work */ function worked(address keeper) external { workReceipt(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft()))); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function workReceipt(address keeper, uint amount) public { require(jobs[msg.sender], "workReceipt: !job"); require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), "workReceipt: max limit"); credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; _bond(address(this), keeper, amount); workCompleted[keeper] = workCompleted[keeper].add(amount); emit KeeperWorked(address(this), msg.sender, keeper, block.number); } /** * @notice Implemented by jobs to show that a keeper performed work * @param credit the asset being awarded to the keeper * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function receipt(address credit, address keeper, uint amount) external { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][credit] = credits[msg.sender][credit].sub(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; IERC20(credit).safeTransfer(keeper, amount); emit KeeperWorked(credit, msg.sender, keeper, block.number); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the amount of ETH sent to the keeper */ function receiptETH(address keeper, uint amount) external { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][ETH] = credits[msg.sender][ETH].sub(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; payable(keeper).transfer(amount); emit KeeperWorked(ETH, msg.sender, keeper, block.number); } function _bond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].add(_amount); if (bonding == address(this)) { totalBonded = totalBonded.add(_amount); _moveDelegates(address(0), delegates[_from], _amount); } } function _unbond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].sub(_amount); if (bonding == address(this)) { totalBonded = totalBonded.sub(_amount); _moveDelegates(delegates[_from], address(0), _amount); } } /** * @notice Allows governance to add new job systems * @param job address of the contract for which work should be performed */ function addJob(address job) external { require(msg.sender == governance, "addJob: !gov"); require(!jobs[job], "addJob: job known"); jobs[job] = true; jobList.push(job); emit JobAdded(job, block.number, msg.sender); } /** * @notice Full listing of all jobs ever added * @return array blob */ function getJobs() external view returns (address[] memory) { return jobList; } /** * @notice Allows governance to remove a job from the systems * @param job address of the contract for which work should be performed */ function removeJob(address job) external { require(msg.sender == governance, "removeJob: !gov"); jobs[job] = false; emit JobRemoved(job, block.number, msg.sender); } /** * @notice Allows governance to change the Keep3rHelper for max spend * @param _kprh new helper address to set */ function setKeep3rHelper(IKeep3rHelper _kprh) external { require(msg.sender == governance, "setKeep3rHelper: !gov"); KPRH = _kprh; } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } /** * @notice confirms if the current keeper is registered, can be used for general (non critical) functions * @param keeper the keeper being investigated * @return true/false if the address is a keeper */ function isKeeper(address keeper) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper]; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][address(this)].add(votes[keeper]) >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param bond the bound asset being evaluated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isBondedKeeper(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][bond] >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice begin the bonding process for a new keeper * @param bonding the asset being bound * @param amount the amount of bonding asset being bound */ function bond(address bonding, uint amount) external nonReentrant { require(!blacklist[msg.sender], "bond: blacklisted"); bondings[msg.sender][bonding] = now.add(BOND); if (bonding == address(this)) { _transferTokens(msg.sender, address(this), amount); } else { IERC20(bonding).safeTransferFrom(msg.sender, address(this), amount); } pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].add(amount); emit KeeperBonding(msg.sender, block.number, bondings[msg.sender][bonding], amount); } /** * @notice get full list of keepers in the system */ function getKeepers() external view returns (address[] memory) { return keeperList; } /** * @notice allows a keeper to activate/register themselves after bonding * @param bonding the asset being activated as bond collateral */ function activate(address bonding) external { require(!blacklist[msg.sender], "activate: blacklisted"); require(bondings[msg.sender][bonding] != 0 && bondings[msg.sender][bonding] < now, "activate: bonding"); if (firstSeen[msg.sender] == 0) { firstSeen[msg.sender] = now; keeperList.push(msg.sender); lastJob[msg.sender] = now; } keepers[msg.sender] = true; _bond(bonding, msg.sender, pendingbonds[msg.sender][bonding]); pendingbonds[msg.sender][bonding] = 0; emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender][bonding]); } /** * @notice begin the unbonding process to stop being a keeper * @param bonding the asset being unbound * @param amount allows for partial unbonding */ function unbond(address bonding, uint amount) external { unbondings[msg.sender][bonding] = now.add(UNBOND); _unbond(bonding, msg.sender, amount); partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].add(amount); emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender][bonding], amount); } /** * @notice withdraw funds after unbonding has finished * @param bonding the asset to withdraw from the bonding pool */ function withdraw(address bonding) external nonReentrant { require(unbondings[msg.sender][bonding] != 0 && unbondings[msg.sender][bonding] < now, "withdraw: unbonding"); require(!disputes[msg.sender], "withdraw: disputes"); if (bonding == address(this)) { _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender][bonding]); } else { IERC20(bonding).safeTransfer(msg.sender, partialUnbonding[msg.sender][bonding]); } emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]); partialUnbonding[msg.sender][bonding] = 0; } /** * @notice slash a keeper for downtime * @param keeper the address being slashed */ function down(address keeper) external { require(keepers[msg.sender], "down: !keeper"); require(keepers[keeper], "down: msg.sender !keeper"); require(lastJob[keeper].add(DOWNTIME) < now, "down: safe"); uint _slash = bonds[keeper][address(this)].mul(DOWNTIMESLASH).div(BASE); _unbond(address(this), keeper, _slash); _bond(address(this), msg.sender, _slash); lastJob[keeper] = now; lastJob[msg.sender] = now; emit KeeperSlashed(keeper, msg.sender, block.number, _slash); } /** * @notice allows governance to create a dispute for a given keeper * @param keeper the address in dispute */ function dispute(address keeper) external { require(msg.sender == governance, "dispute: !gov"); disputes[keeper] = true; emit KeeperDispute(keeper, block.number); } /** * @notice allows governance to slash a keeper based on a dispute * @param bonded the asset being slashed * @param keeper the address being slashed * @param amount the amount being slashed */ function slash(address bonded, address keeper, uint amount) public nonReentrant { require(msg.sender == governance, "slash: !gov"); if (bonded == address(this)) { _transferTokens(address(this), governance, amount); } else { IERC20(bonded).safeTransfer(governance, amount); } _unbond(bonded, keeper, amount); disputes[keeper] = false; emit KeeperSlashed(keeper, msg.sender, block.number, amount); } /** * @notice blacklists a keeper from participating in the network * @param keeper the address being slashed */ function revoke(address keeper) external { require(msg.sender == governance, "slash: !gov"); keepers[keeper] = false; blacklist[keeper] = true; slash(address(this), keeper, bonds[keeper][address(this)]); } /** * @notice allows governance to resolve a dispute on a keeper * @param keeper the address cleared */ function resolve(address keeper) external { require(msg.sender == governance, "resolve: !gov"); disputes[keeper] = false; emit KeeperResolved(keeper, block.number); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @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 permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "permit: signature"); require(signatory == owner, "permit: unauthorized"); require(now <= deadline, "permit: expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "transferFrom: exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); balances[src] = balances[src].sub(amount, "_transferTokens: exceeds balance"); balances[dst] = balances[dst].add(amount, "_transferTokens: overflows"); emit Transfer(src, dst, amount); } function _getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } }
* @notice Applies the credit provided in addLiquidityToJob to the job @param provider the liquidity provider @param liquidity the pair being added as liquidity @param job the job that is receiving the credit/
function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond"); require(liquidityApplied[provider][liquidity][job] < now, "credit: bonding"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(liquidityAmount[provider][liquidity][job]).div(IERC20(liquidity).totalSupply()); _mint(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].add(_credit); liquidityAmount[provider][liquidity][job] = 0; emit ApplyCredit(job, provider, block.number, _credit); }
494,233
[ 1, 13029, 326, 12896, 2112, 316, 527, 48, 18988, 24237, 774, 2278, 358, 326, 1719, 225, 2893, 326, 4501, 372, 24237, 2893, 225, 4501, 372, 24237, 326, 3082, 3832, 3096, 487, 4501, 372, 24237, 225, 1719, 326, 1719, 716, 353, 15847, 326, 12896, 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, 2230, 16520, 774, 2278, 12, 2867, 2893, 16, 1758, 4501, 372, 24237, 16, 1758, 1719, 13, 3903, 288, 203, 3639, 2583, 12, 549, 372, 24237, 18047, 63, 549, 372, 24237, 6487, 315, 1289, 48, 18988, 24237, 774, 2278, 30, 401, 6017, 8863, 203, 3639, 2583, 12, 549, 372, 24237, 16203, 63, 6778, 6362, 549, 372, 24237, 6362, 4688, 65, 480, 374, 16, 315, 20688, 30, 1158, 8427, 8863, 203, 3639, 2583, 12, 549, 372, 24237, 16203, 63, 6778, 6362, 549, 372, 24237, 6362, 4688, 65, 411, 2037, 16, 315, 20688, 30, 8427, 310, 8863, 203, 3639, 2254, 389, 549, 372, 24237, 273, 324, 26488, 63, 2867, 12, 549, 372, 24237, 13, 15533, 203, 3639, 2254, 389, 20688, 273, 389, 549, 372, 24237, 18, 16411, 12, 549, 372, 24237, 6275, 63, 6778, 6362, 549, 372, 24237, 6362, 4688, 65, 2934, 2892, 12, 45, 654, 39, 3462, 12, 549, 372, 24237, 2934, 4963, 3088, 1283, 10663, 203, 3639, 389, 81, 474, 12, 2867, 12, 2211, 3631, 389, 20688, 1769, 203, 3639, 6197, 1282, 63, 4688, 6362, 2867, 12, 2211, 25887, 273, 6197, 1282, 63, 4688, 6362, 2867, 12, 2211, 13, 8009, 1289, 24899, 20688, 1769, 203, 3639, 4501, 372, 24237, 6275, 63, 6778, 6362, 549, 372, 24237, 6362, 4688, 65, 273, 374, 31, 203, 203, 3639, 3626, 5534, 16520, 12, 4688, 16, 2893, 16, 1203, 18, 2696, 16, 389, 20688, 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 ]
pragma solidity ^0.4.24; import "zeppelin-solidity/contracts/token/ERC20/MintableToken.sol"; import "zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol"; import "./SnapshotToken.sol"; /** * @title PreserveBalancesOnTransferToken (Copy-on-Write) token * @author Based on code by Thetta DAO Framework: https://github.com/Thetta/Thetta-DAO-Framework/ * @dev Token that can preserve the balances after some EVENT happens (voting is started, didivends are calculated, etc) * without blocking the transfers! Please notice that EVENT in this case has nothing to do with Ethereum events. * * Example of usage1 (pseudocode): * PreserveBalancesOnTransferToken token; * * token.mint(ADDRESS_A, 100); * assert.equal(token.balanceOf(ADDRESS_A), 100); * assert.equal(token.balanceOf(ADDRESS_B), 0); * * SnapshotToken snapshot = token.createNewSnapshot(); * token.transfer(ADDRESS_A, ADDRESS_B, 30); * * assert.equal(token.balanceOf(ADDRESS_A), 70); * assert.equal(token.balanceOf(ADDRESS_B), 30); * * assert.equal(snapshot.balanceOf(ADDRESS_A), 100); * assert.equal(snapshot.balanceOf(ADDRESS_B), 0); * * token.stopSnapshot(snapshot); * * Example of usage2 (pseudocode): * PreserveBalancesOnTransferToken token; * * token.mint(ADDRESS_A, 100); * assert.equal(token.balanceOf(ADDRESS_A), 100); * assert.equal(token.balanceOf(ADDRESS_B), 0); * * uint someEventID_1 = token.startNewEvent(); * token.transfer(ADDRESS_A, ADDRESS_B, 30); * * assert.equal(token.balanceOf(ADDRESS_A), 70); * assert.equal(token.balanceOf(ADDRESS_B), 30); * * assert.equal(token.getBalanceAtEvent(someEventID_1, ADDRESS_A), 100); * assert.equal(token.getBalanceAtEvent(someEventID_1, ADDRESS_B), 0); * * token.finishEvent(someEventID_1); */ contract PreserveBalancesOnTransferToken is MintableToken, BurnableToken { struct Holder { uint256 balance; uint lastUpdateTime; } struct Event { mapping (address => Holder) holders; bool isEventInProgress; uint eventStartTime; } Event[] events; SnapshotToken[] snapshotTokens; event EventStarted(address indexed _address, uint _eventID); event EventFinished(address indexed _address, uint _eventID); event SnapshotCreated(address indexed _snapshotTokenAddress); modifier onlyFromSnapshotOrOwner() { require((msg.sender == owner) || isFromSnapshot(msg.sender)); _; } // BasicToken overrides: /** * @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) { updateCopyOnWriteMaps(msg.sender, _to); return super.transfer(_to, _value); } // StandardToken overrides: /** * @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) { updateCopyOnWriteMaps(_from, _to); return super.transferFrom(_from, _to, _value); } // MintableToken overrides: /** * @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 canMint onlyOwner returns(bool) { updateCopyOnWriteMap(_to); return super.mint(_to, _amount); } // PreserveBalancesOnTransferToken - new methods: /** * @dev Creates new ERC20 balances snapshot. * In this case SnapshotToken is an easy way to get the balances * using the standard 'balanceOf' method instead of getBalanceAtEventStart() * @return Address of the new created snapshot ERC20 token. */ function createNewSnapshot() public onlyOwner returns(address) { SnapshotToken st = new SnapshotToken(this); snapshotTokens.push(st); // will call back this.startNewEvent(); st.start(); emit SnapshotCreated(st); return st; } /** * @dev End working with the ERC20 balances snapshot * @param _st The SnapshotToken that was created with 'createNewSnapshot' * method before */ function stopSnapshot(SnapshotToken _st) public onlyOwner { // will call back this.finishEvent(); _st.finish(); } /** * @dev Function to signal that some event happens (dividends are calculated, voting, etc) * so we need to start preserving balances AT THE time this event happened. * @return An index of the event started. */ function startNewEvent() external onlyFromSnapshotOrOwner returns(uint) { return _startNewEvent(); } function _startNewEvent() internal returns(uint) { // check if we have empty slots for (uint i = 0; i < events.length; ++i) { if (!events[i].isEventInProgress) { events[i].isEventInProgress = true; events[i].eventStartTime = now; emit EventStarted(msg.sender, i); return i; } } // create new event and add to the tail Event e; e.isEventInProgress = true; e.eventStartTime = now; events.push(e); emit EventStarted(msg.sender, events.length - 1); return (events.length - 1); } /** * @dev Function to signal that some event is finished * @param _eventID An index of the event that was previously returned by startNewEvent(). */ function finishEvent(uint _eventID) external onlyFromSnapshotOrOwner { _finishEvent(_eventID); } function _finishEvent(uint _eventID) internal { require(_eventID < events.length); require(events[_eventID].isEventInProgress); // TODO: check that we are from the snapshot events[_eventID].isEventInProgress = false; emit EventFinished(msg.sender, _eventID); } /** * @dev Returns the balance of the address _for at the time event _eventID happened * !!! WARNING !!! * We do not give STRONG guarantees. The return value is time-dependent: * If startNewEvent() and then getBalanceAtEventStart() -> it CAN return wrong data * In case time between these calls has passed -> the return value is ALWAYS correct. * * Please see tests. * return Token balance (when the event started, but not a CURRENT balanceOf()!) */ function getBalanceAtEventStart(uint _eventID, address _for) public view returns(uint256) { require(_eventID < events.length); require(events[_eventID].isEventInProgress); if (!isBalanceWasChangedAfterEventStarted(_eventID, _for)) { return balances[_for]; } return events[_eventID].holders[_for].balance; } // BurnableToken overrides: /** @dev This is an override of internal method! Public method burn() calls _burn() automatically * (see BurnableToken implementation) */ function _burn(address _who, uint256 _value) internal { updateCopyOnWriteMap(_who); super._burn(_who, _value); } // Internal methods: function updateCopyOnWriteMaps(address _from, address _to) internal { updateCopyOnWriteMap(_to); updateCopyOnWriteMap(_from); } function updateCopyOnWriteMap(address _for) internal { for (uint i = 0; i < events.length; ++i) { bool res = isNeedToUpdateBalancesMap(i, _for); if (res) { events[i].holders[_for].balance = balances[_for]; events[i].holders[_for].lastUpdateTime = now; } } } function isNeedToUpdateBalancesMap(uint _eventID, address _for) internal view returns(bool) { return (events[_eventID].isEventInProgress && !isBalanceWasChangedAfterEventStarted(_eventID, _for)); } function isBalanceWasChangedAfterEventStarted(uint _eventID, address _for) internal view returns(bool) { return (events[_eventID].holders[_for].lastUpdateTime >= events[_eventID].eventStartTime); } function isFromSnapshot(address _a) internal view returns(bool) { for (uint i = 0; i < snapshotTokens.length; ++i) { if (snapshotTokens[i] == _a) { return true; } } return false; } }
PreserveBalancesOnTransferToken - new methods:* @dev Creates new ERC20 balances snapshot. In this case SnapshotToken is an easy way to get the balances using the standard 'balanceOf' method instead of getBalanceAtEventStart() @return Address of the new created snapshot ERC20 token./ will call back this.startNewEvent();
function createNewSnapshot() public onlyOwner returns(address) { SnapshotToken st = new SnapshotToken(this); snapshotTokens.push(st); st.start(); emit SnapshotCreated(st); return st; }
1,036,606
[ 1, 12236, 6527, 38, 26488, 1398, 5912, 1345, 300, 394, 2590, 30, 225, 10210, 394, 4232, 39, 3462, 324, 26488, 4439, 18, 657, 333, 648, 10030, 1345, 353, 392, 12779, 4031, 358, 336, 326, 324, 26488, 1450, 326, 4529, 296, 12296, 951, 11, 707, 3560, 434, 2882, 6112, 861, 1133, 1685, 1435, 327, 5267, 434, 326, 394, 2522, 4439, 4232, 39, 3462, 1147, 18, 19, 903, 745, 1473, 333, 18, 1937, 1908, 1133, 5621, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 15291, 4568, 1435, 1071, 1338, 5541, 1135, 12, 2867, 13, 288, 203, 202, 202, 4568, 1345, 384, 273, 394, 10030, 1345, 12, 2211, 1769, 203, 203, 202, 202, 11171, 5157, 18, 6206, 12, 334, 1769, 203, 202, 202, 334, 18, 1937, 5621, 203, 203, 202, 202, 18356, 10030, 6119, 12, 334, 1769, 203, 202, 202, 2463, 384, 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 ]
pragma solidity ^0.4.24; contract FDDEvents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } contract modularFomoDD is FDDEvents {} contract FomoDD is modularFomoDD { using SafeMath for *; using NameFilter for string; using FDDKeysCalc for uint256; // TODO: check address BankInterfaceForForwarder constant private Bank = BankInterfaceForForwarder(0xfa1678C00299fB685794865eA5e20dB155a8C913); PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xA5d855212A9475558ACf92338F6a1df44dFCE908); address private admin = msg.sender; string constant public name = "FomoDD"; string constant public symbol = "Chives"; // TODO: check time uint256 private rndGap_ = 0; uint256 private rndExtra_ = 0 minutes; uint256 constant private rndInit_ = 12 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => FDDdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => FDDdatasets.PlayerRounds) public plyrRnds_; // current round mapping (uint256 => mapping (uint256 => FDDdatasets.PlayerRounds)) public plyrRnds; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** uint256 public rID_; // round id number / total rounds that have happened FDDdatasets.Round public round_; // round data mapping (uint256 => FDDdatasets.Round) public round; // current round //**************** // TEAM FEE DATA //**************** uint256 public fees_ = 60; // fee distribution uint256 public potSplit_ = 45; // pot split distribution //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } /** * @dev prevents contracts from interacting with FomoDD */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "non smart contract address only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not FDDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not FDDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not FDDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not FDDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data FDDdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data FDDdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data FDDdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round[_rID].end && round[_rID].ended == false && round[_rID].plyr != 0) { // set up our tx event data FDDdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit FDDEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit FDDEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit FDDEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit FDDEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit FDDEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) return ( (round[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round[_rID].end) if (_now > round[_rID].strt + rndGap_) return( (round[_rID].end).sub(_now) ); else return( (round[_rID].strt + rndGap_).sub(_now)); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round[_rID].end && round[_rID].ended == false && round[_rID].plyr != 0) { // if player is winner if (round[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds[_pID][_rID].mask) ), plyr_[_pID].aff ); } plyrRnds_[_pID] = plyrRnds[_pID][_rID]; // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round[_rID].mask).add(((((round[_rID].pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round[_rID].keys))).mul(plyrRnds[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return total keys * @return time ends * @return time started * @return current pot * @return current player ID in lead * @return current player in leads address * @return current player in leads name * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { uint256 _rID = rID_; return ( round[_rID].keys, //0 round[_rID].end, //1 round[_rID].strt, //2 round[_rID].pot, //3 round[_rID].plyr, //4 plyr_[round[_rID].plyr].addr, //5 plyr_[round[_rID].plyr].name, //6 airDropTracker_ + (airDropPot_ * 1000) //7 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, FDDdatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round[_rID].end && round[_rID].ended == false) { // end the round (distributes pot) & start new round round[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit FDDEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, FDDdatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round[_rID].end && round[_rID].ended == false) { // end the round (distributes pot) & start new round round[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit FDDEvents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, FDDdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round[_rID].eth < 100000000000000000000 && plyrRnds[_pID][_rID].eth.add(_eth) > 10000000000000000000) { uint256 _availableLimit = (10000000000000000000).sub(plyrRnds[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round[_rID].plyr != _pID) round[_rID].plyr = _pID; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 1 prize was won _eventData_.compressedData += 100000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds[_pID][_rID].keys = _keys.add(plyrRnds[_pID][_rID].keys); plyrRnds[_pID][_rID].eth = _eth.add(plyrRnds[_pID][_rID].eth); // update round round[_rID].keys = _keys.add(round[_rID].keys); round[_rID].eth = _eth.add(round[_rID].eth); // distribute eth _eventData_ = distributeExternal(_pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } plyrRnds_[_pID] = plyrRnds[_pID][_rID]; round_ = round[_rID]; } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return((((round[_rIDlast].mask).mul(plyrRnds[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds[_pID][_rIDlast].mask)); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _eth) public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) return ( (round[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) return ( (round[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "only PlayerBook can call this function"); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "only PlayerBook can call this function"); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(FDDdatasets.EventReturns memory _eventData_) private returns (FDDdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of FomoDD if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, FDDdatasets.EventReturns memory _eventData_) private returns (FDDdatasets.EventReturns) { if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(FDDdatasets.EventReturns memory _eventData_) private returns (FDDdatasets.EventReturns) { uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round[_rID].plyr; // grab our pot amount // add airdrop pot into the final pot // uint256 _pot = round[_rID].pot + airDropPot_; uint256 _pot = round[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(45)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_)) / 100; // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _com = _com.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards // if (!address(Bank).call.value(_com)(bytes4(keccak256("deposit()")))) // { // _gen = _gen.add(_com); // _com = 0; // } // distribute gen portion to key holders round[_rID].mask = _ppt.add(round[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = _com; // start next round rID_++; _rID++; round[_rID].strt = now + rndExtra_; round[_rID].end = now + rndInit_ + rndExtra_; round[_rID].pot = _com; round_ = round[_rID]; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds[_pID][_rIDlast].mask = _earnings.add(plyrRnds[_pID][_rIDlast].mask); plyrRnds_[_pID] = plyrRnds[_pID][_rIDlast]; } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round[_rID].end && round[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round[_rID].end = _newTime; else round[_rID].end = rndMax_.add(_now); round_ = round[_rID]; } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _pID, uint256 _eth, uint256 _affID, FDDdatasets.EventReturns memory _eventData_) private returns(FDDdatasets.EventReturns) { // pay 5% out to community rewards uint256 _com = _eth * 5 / 100; // distribute share to affiliate uint256 _aff = _eth * 10 / 100; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit FDDEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now); } else { // no affiliates, add to community _com += _aff; } if (!address(Bank).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. } return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, FDDdatasets.EventReturns memory _eventData_) private returns(FDDdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_)) / 100; // toss 5% into airdrop pot uint256 _air = (_eth / 20); airDropPot_ = airDropPot_.add(_air); // calculate pot (20%) uint256 _pot = (_eth.mul(20) / 100); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round[_rID].pot = _pot.add(_dust).add(round[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; round_ = round[_rID]; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round[_rID].keys); round[_rID].mask = _ppt.add(round[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds[_pID][_rID].mask = (((round[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds[_pID][_rID].mask); plyrRnds_[_pID] = plyrRnds[_pID][_rID]; round_ = round[_rID]; // calculate & return dust return(_gen.sub((_ppt.mul(round[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _eth, uint256 _keys, FDDdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit FDDEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only owner can activate // TODO: set owner require(msg.sender == admin); // can only be ran once require(activated_ == false, "FomoDD already activated"); // activate the contract activated_ = true; rID_ = 1; round[1].strt = now + rndExtra_; round[1].end = now + rndInit_ + rndExtra_; round_ = round[1]; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library FDDdatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask } struct Round { uint256 plyr; // pID of player in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library FDDKeysCalc { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } interface BankInterfaceForForwarder { function deposit() external payable returns(bool); } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } }
* @dev ends the round. manages paying out winner/splitting up pot/ grab our winning player and team id's grab our pot amount add airdrop pot into the final pot uint256 _pot = round[_rID].pot + airDropPot_; calculate our winner share, community rewards, gen share, p3d share, and amount reserved for next pot calculate ppt for round mask
function endRound(FDDdatasets.EventReturns memory _eventData_) private returns (FDDdatasets.EventReturns) { uint256 _rID = rID_; uint256 _winPID = round[_rID].plyr; uint256 _pot = round[_rID].pot; uint256 _win = (_pot.mul(45)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_)) / 100; uint256 _ppt = (_gen.mul(1000000000000000000)) / (round[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _com = _com.add(_dust); } _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = _com; _rID++; round[_rID].strt = now + rndExtra_; round[_rID].end = now + rndInit_ + rndExtra_; round[_rID].pot = _com; round_ = round[_rID]; return(_eventData_); }
546,633
[ 1, 5839, 326, 3643, 18, 20754, 281, 8843, 310, 596, 5657, 1224, 19, 4939, 1787, 731, 5974, 19, 11086, 3134, 5657, 2093, 7291, 471, 5927, 612, 1807, 11086, 3134, 5974, 3844, 527, 279, 6909, 1764, 5974, 1368, 326, 727, 5974, 2254, 5034, 389, 13130, 273, 3643, 63, 67, 86, 734, 8009, 13130, 397, 23350, 7544, 18411, 67, 31, 4604, 3134, 5657, 1224, 7433, 16, 19833, 283, 6397, 16, 3157, 7433, 16, 293, 23, 72, 7433, 16, 471, 3844, 8735, 364, 1024, 5974, 4604, 293, 337, 364, 3643, 3066, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 679, 11066, 12, 42, 5698, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 13, 203, 3639, 3238, 203, 3639, 1135, 261, 42, 5698, 21125, 18, 1133, 1356, 13, 203, 565, 288, 540, 203, 3639, 2254, 5034, 389, 86, 734, 273, 436, 734, 67, 31, 203, 3639, 2254, 5034, 389, 8082, 16522, 273, 3643, 63, 67, 86, 734, 8009, 1283, 86, 31, 203, 540, 203, 3639, 2254, 5034, 389, 13130, 273, 3643, 63, 67, 86, 734, 8009, 13130, 31, 203, 540, 203, 3639, 2254, 5034, 389, 8082, 273, 261, 67, 13130, 18, 16411, 12, 7950, 3719, 342, 2130, 31, 203, 3639, 2254, 5034, 389, 832, 273, 261, 67, 13130, 342, 1728, 1769, 203, 3639, 2254, 5034, 389, 4507, 273, 261, 67, 13130, 18, 16411, 12, 13130, 5521, 67, 3719, 342, 2130, 31, 203, 540, 203, 3639, 2254, 5034, 389, 84, 337, 273, 261, 67, 4507, 18, 16411, 12, 21, 12648, 2787, 9449, 3719, 342, 261, 2260, 63, 67, 86, 734, 8009, 2452, 1769, 203, 3639, 2254, 5034, 389, 72, 641, 273, 389, 4507, 18, 1717, 12443, 67, 84, 337, 18, 16411, 12, 2260, 63, 67, 86, 734, 8009, 2452, 3719, 342, 2130, 12648, 12648, 1769, 203, 3639, 309, 261, 67, 72, 641, 405, 374, 13, 203, 3639, 288, 203, 5411, 389, 4507, 273, 389, 4507, 18, 1717, 24899, 72, 641, 1769, 203, 5411, 389, 832, 273, 389, 832, 18, 1289, 24899, 72, 641, 1769, 203, 3639, 289, 203, 540, 203, 540, 203, 2398, 203, 3639, 389, 2575, 751, 27799, 15385, 5103, 273, 2 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@plasma-fi/contracts/interfaces/ITokensApprover.sol"; contract TokensApprover is ITokensApprover, Ownable { // Contains data for issuing permissions for the token mapping(uint256 => ApproveConfig) private _configs; uint256 private _configsLength = 0; // Contains methods for issuing permissions for tokens mapping(address => uint256) private _tokens; constructor(ApproveConfig[] memory configs) { for (uint256 i = 0; i < configs.length; i++) { _addConfig(configs[i]); } } function addConfig(ApproveConfig calldata config) external onlyOwner returns (uint256) { return _addConfig(config); } function setConfig(uint256 id, ApproveConfig calldata config) external onlyOwner returns (uint256) { return _setConfig(id, config); } function setToken(uint256 id, address token) external onlyOwner { _setToken(id, token); } function getConfig(address token) view external returns (ApproveConfig memory) { return _getConfig(token); } function getConfigById(uint256 id) view external returns (ApproveConfig memory) { require(id < _configsLength, "Approve config not found"); return _configs[id]; } function configsLength() view external returns (uint256) { return _configsLength; } function hasConfigured(address token) view external returns (bool) { return _tokens[token] > 0; } function callPermit(address token, bytes calldata permitCallData) external returns (bool, bytes memory) { ApproveConfig storage config = _getConfig(token); bytes4 selector = _getSelector(permitCallData); require(config.permitMethodSelector == selector, "Wrong permit method"); return token.call(permitCallData); } function _addConfig(ApproveConfig memory config) internal returns (uint256) { _configs[_configsLength++] = config; return _configsLength; } function _setConfig(uint256 id, ApproveConfig memory config) internal returns (uint256) { require(id <= _configsLength, "Approve config not found"); _configs[id] = config; return _configsLength; } function _setToken(uint256 id, address token) internal { require(token != address(0), "Invalid token address"); require(id <= _configsLength, "Approve config not found"); _tokens[token] = id + 1; } function _getConfig(address token) view internal returns (ApproveConfig storage) { require(_tokens[token] > 0, "Approve config not found"); return _configs[_tokens[token] - 1]; } function _getSelector(bytes memory data) pure private returns (bytes4 selector) { require(data.length >= 4, "Data to short"); assembly { selector := mload(add(data, add(0, 32))) // Clean the trailing bytes. selector := and(selector, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; interface ITokensApprover { /** * @notice Data for issuing permissions for the token */ struct ApproveConfig { string name; string version; string domainType; string primaryType; string noncesMethod; string permitMethod; bytes4 permitMethodSelector; } function addConfig(ApproveConfig calldata config) external returns (uint256); function setConfig(uint256 id, ApproveConfig calldata config) external returns (uint256); function setToken(uint256 id, address token) external; function getConfig(address token) view external returns (ApproveConfig memory); function getConfigById(uint256 id) view external returns (ApproveConfig memory); function configsLength() view external returns (uint256); function hasConfigured(address token) view external returns (bool); function callPermit(address token, bytes calldata permitCallData) external returns (bool, bytes memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // 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); } }
Clean the trailing bytes.
function _getSelector(bytes memory data) pure private returns (bytes4 selector) { require(data.length >= 4, "Data to short"); assembly { selector := mload(add(data, add(0, 32))) selector := and(selector, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } }
590,072
[ 1, 7605, 326, 7341, 1731, 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, 445, 389, 588, 4320, 12, 3890, 3778, 501, 13, 16618, 3238, 1135, 261, 3890, 24, 3451, 13, 288, 203, 3639, 2583, 12, 892, 18, 2469, 1545, 1059, 16, 315, 751, 358, 3025, 8863, 203, 203, 3639, 19931, 288, 203, 5411, 3451, 519, 312, 945, 12, 1289, 12, 892, 16, 527, 12, 20, 16, 3847, 20349, 203, 5411, 3451, 519, 471, 12, 9663, 16, 374, 28949, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 13, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Part: OpenZeppelin/[email protected]/Address /** * @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); } } } } // Part: OpenZeppelin/[email protected]/Context /** * @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; } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721Receiver /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // Part: OpenZeppelin/[email protected]/Strings /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // Part: OpenZeppelin/[email protected]/IERC721 /** * @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; } // Part: OpenZeppelin/[email protected]/Ownable /** * @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); } } // Part: OpenZeppelin/[email protected]/IERC721Enumerable /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721Metadata /** * @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); } // Part: OpenZeppelin/[email protected]/ERC721 /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // Part: OpenZeppelin/[email protected]/ERC721Enumerable /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: Marnotaur721.sol contract Marnotaurs is ERC721Enumerable, Ownable { struct Partners { uint256 limit; uint256 nftMinted; } struct Upgrade { uint256 priceETH; uint256 limit; // 0 - unlimited uint256 count; // How much upgraded uint256 tokenIdShift; //used for gen newTokenId, add to old tokenId bool enabled; } struct Beneficiary { address bAddress; uint256 bPercent; } uint256 constant public MAX_TOTAL_SUPPLY = 9990; uint256 constant public MAX_MINT_PER_TX = 10; uint256 constant public MAX_BUY_PER_TX = 10; uint256 public mintPrice = 5e16; uint256 public stopMintAfter = 2775; //5*555 uint256 public reservedForPartners; uint256 public enableBuyAfterTimestamp; mapping (address => Partners) public partnersLimit; Upgrade[] public upgradeTypes; Beneficiary[2] public beneficiaries; //Event for track mint channel: // 1 - MagicBox - depricated // 2 - With Ethere // 3 - Partners White List // 4 - With ERC20 - depricated event MintSource(uint256 tokenId, uint8 channel); event PartnesChanged(address partner, uint256 limit); event Upgraded(address indexed holder, uint256 upgradeIndex, uint256 oldTokenId, uint256 newTokenId); /** * @dev Set _mintMagicBox to true for enable this feature * */ //constructor() ERC721("MÆRⴼTΩR NFT Collection", "MÆRⴼTΩR") { constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) { //1630353600 - 2021-08-30 20:00 UTC enableBuyAfterTimestamp = 1630353600; beneficiaries[0] = Beneficiary(msg.sender, 6650); beneficiaries[1] = Beneficiary(msg.sender, 3350); } /** * @dev Mint new NFTs with ether or free for partners. * */ function multiMint() external payable { uint256 mintAmount = _availableFreeMint(msg.sender); if(mintAmount > 0) { require(msg.value == 0, "No need Ether"); mintAmount = _multiMint(msg.sender, mintAmount, 3); partnersLimit[msg.sender].nftMinted += mintAmount; reservedForPartners -= mintAmount; } else { require(enableBuyAfterTimestamp <= block.timestamp, "To early"); require(msg.value >= mintPrice, "Less ether for mint"); uint256 estimateAmountForMint = msg.value / mintPrice; require(estimateAmountForMint <= MAX_BUY_PER_TX, "So much payable mint"); require(stopMintAfter - reservedForPartners >= totalSupply() + estimateAmountForMint, "Minting is paused"); mintAmount = _multiMint(msg.sender, estimateAmountForMint, 2); if ((msg.value - mintAmount * mintPrice) > 0) { address payable s = payable(msg.sender); s.transfer(msg.value - mintAmount * mintPrice); } } } function upgradeMe(uint256 _upgradeIndex, uint256 _tokenId) external payable { require (_upgradeIndex < upgradeTypes.length, "Unknown upgrade"); require(ownerOf(_tokenId) == msg.sender, "Only for token owner"); require(upgradeTypes[_upgradeIndex].enabled, "Disabled upgrade"); require(upgradeTypes[_upgradeIndex].priceETH <= msg.value, "Not enough ether"); if (upgradeTypes[_upgradeIndex].limit != 0) { require( upgradeTypes[_upgradeIndex].count + 1 <= upgradeTypes[_upgradeIndex].limit, "Upgrade limit exceeded" ); } upgradeTypes[_upgradeIndex].count += 1; _burn(_tokenId); uint256 newToken = upgradeTypes[_upgradeIndex].tokenIdShift + _tokenId; _mint(msg.sender, newToken); emit Upgraded(msg.sender, _upgradeIndex, _tokenId, newToken); if (msg.value - upgradeTypes[_upgradeIndex].priceETH > 0 ){ address payable s = payable(msg.sender); s.transfer(msg.value - upgradeTypes[_upgradeIndex].priceETH); } } /** * @dev Returns avilable for free mint NFTs for address * */ function availableFreeMint(address _partner) external view returns (uint256) { return _availableFreeMint(_partner); } function getUpgradeType(uint256 _index) external view returns(Upgrade memory) { require(_index < upgradeTypes.length, "Unknown upgrade"); return upgradeTypes[_index]; } function getUpgradeTypeCount() external view returns(uint256) { return upgradeTypes.length; } function getBeneficiaries() external view returns(Beneficiary[2] memory) { return beneficiaries; } /////////////////////////////////////////////////////////////////// ///// Owners Functions /////////////////////////////////////////// /////////////////////////////////////////////////////////////////// function setPartner(address _partner, uint256 _limit) external onlyOwner { _setPartner(_partner, _limit); } function setPartnerBatch(address[] memory _partners, uint256[] memory _limits) external onlyOwner { require(_partners.length == _limits.length, "Array params must have equal length"); require(_partners.length <= 256, "Not more than 256"); for (uint8 i; i < _partners.length; i ++) { _setPartner(_partners[i], _limits[i]); } } function setMintPrice(uint256 _newPrice) external onlyOwner { mintPrice = _newPrice; } function withdrawEther() external onlyOwner { uint256 raised = address(this).balance; for (uint8 i; i < beneficiaries.length; i ++) { address payable o = payable(beneficiaries[i].bAddress); o.transfer(raised * beneficiaries[i].bPercent / 10000); } } function setMintPause(uint256 _newTotalSupply) external onlyOwner { stopMintAfter = _newTotalSupply; } function setEnableTimestamp(uint256 _newTimestamp) external onlyOwner { enableBuyAfterTimestamp = _newTimestamp; } function addUpgradeType( uint256 _priceETH, uint256 _limit, uint256 _tokenIdShift, bool _enabled ) external onlyOwner { require(_tokenIdShift > MAX_TOTAL_SUPPLY, "Not Zero"); upgradeTypes.push(Upgrade({ priceETH: _priceETH, limit: _limit, count: 0, tokenIdShift: _tokenIdShift, enabled: _enabled }) ); } function updateUpType( uint256 _inedx, uint256 _priceETH, uint256 _limit, bool _enabled ) external onlyOwner { upgradeTypes[_inedx].priceETH = _priceETH; upgradeTypes[_inedx].limit = _limit; upgradeTypes[_inedx].enabled = _enabled; } function setBeneficiary(uint256 _index, address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "No Zero Address"); beneficiaries[_index].bAddress = _beneficiary; } /////////////////////////////////////////////////////////////////// ///// INTERNALS ///////////////////////////////////////////// /////////////////////////////////////////////////////////////////// function _availableFreeMint(address _partner) internal view returns (uint256) { return partnersLimit[_partner].limit - partnersLimit[_partner].nftMinted; } function _baseURI() internal view override returns (string memory) { return string(abi.encodePacked( //"https://dev.nftstars.app/backend/api/v1/nfts/metadata/0x", "https://nftstars.app/backend/api/v1/nfts/metadata/0x", toAsciiString(address(this)), "/") ); } function _setPartner(address _partner, uint256 _limit) internal { require(_partner != address(0), "No zero"); require(_limit >= partnersLimit[_partner].nftMinted, "Cant decrease more then minted"); if (partnersLimit[_partner].limit < _limit) { reservedForPartners += (_limit - partnersLimit[_partner].limit); } else { reservedForPartners -= (partnersLimit[_partner].limit - _limit); } partnersLimit[_partner].limit = _limit; emit PartnesChanged(_partner, _limit); } function _multiMint(address to, uint256 amount, uint8 channel) internal returns (uint256) { require((totalSupply() + reservedForPartners + amount) <= MAX_TOTAL_SUPPLY, "No more common heroes"); uint256 counter; if (amount > MAX_MINT_PER_TX) { counter = MAX_MINT_PER_TX; } else { counter = amount; } if ((totalSupply() + counter) > MAX_TOTAL_SUPPLY) { counter = MAX_TOTAL_SUPPLY - totalSupply(); } for(uint i = 0; i < counter; i++) { _mint(to, totalSupply()); emit MintSource(totalSupply()-1, channel); } return counter; } function toAsciiString(address x) internal view returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(bytes1 b) internal view returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } }
Event for track mint channel: 1 - MagicBox - depricated 2 - With Ethere 3 - Partners White List 4 - With ERC20 - depricated
event MintSource(uint256 tokenId, uint8 channel);
13,707,684
[ 1, 1133, 364, 3298, 312, 474, 1904, 30, 404, 300, 28496, 3514, 300, 443, 683, 11780, 576, 300, 3423, 512, 18664, 890, 300, 6393, 9646, 30233, 987, 1059, 300, 3423, 4232, 39, 3462, 300, 443, 683, 11780, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 490, 474, 1830, 12, 11890, 5034, 1147, 548, 16, 2254, 28, 1904, 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 ]
./full_match/80001/0x235dEBaf1D9Fa33efa2095f9Df70Cf40b8F4cFaB/sources/contracts/TMHC-Reborn-Stake.sol
TMHC Reborn Stake Upgradeable Contract Release version 0.2 Staking pool onwer / admin Operation status of the Pool. Claim operation status of the Pool.
contract TMHCRebornStakeU2 is PermissionsEnumerable, Initializable, ReentrancyGuard, NTStakeMulti{ address private owner; bool public PauseStake; bool public PauseClaim; Constructor + initializer logic pragma solidity ^0.8.17; constructor(IERC1155 _EditionToken, IERC721 _NFTtoken, NTSRewardVault _RewardVault, NTSUserManager _userStorage, NTSGradeStorage _gradeStorage, uint256 _rewardPerHour, uint256 _rewardPerHourSub, address _owner) initializer { owner = _owner; _setupRole(DEFAULT_ADMIN_ROLE, _owner); tmhcToken = _EditionToken; momoToken = _NFTtoken; rewardVault = _RewardVault; userStorage = _userStorage; gradeStorage = _gradeStorage; rewardPerHour = _rewardPerHour; rewardPerHourSub = _rewardPerHourSub; PauseStake = false; PauseClaim = false; } Basic Staking Info function getStakedTMHC(address player) public view returns(uint16[] memory stakedIds){ return userStorage.getStakedUserTmhc(player); } function getStakedMOMO(address player) public view returns(uint16[] memory stakedIds){ return userStorage.getStakedUserMomo(player); } function getStakedTeam(address player) public view returns(uint16[] memory stakedIds){ return userStorage.getStakedUserTeam(player); } function getBoostsRate(address player, uint16 _staketeam) public view returns(uint256 _TeamBoostRate){ return _getTeamBoostRate(player, _staketeam); } function getBoostIds(uint16 _staketeam) public view returns(uint16[] memory boostIds){ NTSUserManager.StakeTeam memory _inStakedteam = userStorage.getInStakedTeam(_staketeam); return _inStakedteam.boostIds; } Single Stake Interface function stake(uint _tokenType, uint16[] calldata _tokenIds) external nonReentrant { require(!PauseStake, "Stacking pool is currently paused."); _stake(msg.sender, _tokenType, _tokenIds); } function claim(uint _tokenType, uint16 _tokenId) external nonReentrant { require(!PauseClaim, "The claim is currently paused."); _claim(msg.sender, _tokenType, _tokenId); } function claimBatch(uint _tokenType, uint16[] calldata _tokenIds) external nonReentrant { require(!PauseClaim, "The claim is currently paused."); _claimBatch(msg.sender, _tokenType, _tokenIds); } function claimAll() external nonReentrant { require(!PauseClaim, "The claim is currently paused."); _claimAll(msg.sender); } function unStake(uint _tokenType, uint16[] calldata _tokenIds) external nonReentrant { require(!PauseStake, "Stacking pool is currently paused."); _unStake(msg.sender, _tokenType, _tokenIds); } function calReward(address player, uint _tokenType, uint16 _tokenId) external view returns(uint256 _Reward){ return _calReward(player, _tokenType, _tokenId); } function calRewardAll(address player) external view returns(uint256 _totalReward){ return _calRewardAll(player); } Multi Stake Interface function stakeTeam(uint16 _leaderId ,uint16[] calldata _boostIds) external nonReentrant{ require(!PauseStake, "Stacking pool is currently paused."); _stakeTeam(msg.sender, _leaderId, _boostIds); } function claimTeam(uint16 _leaderId) external nonReentrant{ require(!PauseClaim, "The claim is currently paused."); _claimTeam(msg.sender, _leaderId); } function claimTeamBatch(uint16[] calldata _leaderIds) external nonReentrant{ require(!PauseClaim, "The claim is currently paused."); _claimTeamBatch(msg.sender, _leaderIds); } function claimTeamAll() external nonReentrant{ require(!PauseClaim, "The claim is currently paused."); _claimTeamAll(msg.sender); } function unStakeTeam(uint16[] calldata _leaderIds) external nonReentrant{ require(!PauseStake, "Stacking pool is currently paused."); _unStakeTeam(msg.sender, _leaderIds); } function refreshTeamAll() external nonReentrant{ _refreshAllTeam(msg.sender); } function calRewardTeam(address player, uint16 _staketeam) external view returns(uint256 _TotalReward){ return _calRewardTeam(player, _staketeam); } function calRewardTeamAll(address player) external view returns (uint256 _TotalReward){ return _calRewardTeamAll(player); } function calTeamBoost(address player, uint16 _staketeam) external view returns(uint256 _boostrate){ return _getTeamBoostRate(player, _staketeam); } Admin Function function setRewardPeHour(uint256 _rewardPerHour) external onlyRole(DEFAULT_ADMIN_ROLE){ rewardPerHour = _rewardPerHour; } function setRewardPeHourSub(uint256 _rewardPerHourSub) external onlyRole(DEFAULT_ADMIN_ROLE){ rewardPerHourSub = _rewardPerHourSub; } function setPausePool(bool _status) external onlyRole(DEFAULT_ADMIN_ROLE){ PauseStake = _status; } function setPauseCalim(bool _status) external onlyRole(DEFAULT_ADMIN_ROLE){ PauseClaim = _status; } function adminClaim(address _player, uint _tokenType, uint16 _tokenId) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant { require(!PauseClaim, "The claim is currently paused."); _claim(_player, _tokenType, _tokenId); } function adminClaimBatch(address _player, uint _tokenType, uint16[] calldata _tokenIds) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant { require(!PauseClaim, "The claim is currently paused."); _claimBatch(_player, _tokenType, _tokenIds); } function adminClaimAll(address _player) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant { require(!PauseClaim, "The claim is currently paused."); _claimAll(_player); } function adminClaimTeam(address _player, uint16 _leaderId) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant{ require(!PauseClaim, "The claim is currently paused."); _claimTeam(_player, _leaderId); } function adminClaimTeamBatch(address _player, uint16[] calldata _leaderIds) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant{ require(!PauseClaim, "The claim is currently paused."); _claimTeamBatch(_player, _leaderIds); } function adminClaimTeamAll(address _player) external nonReentrant{ require(!PauseClaim, "The claim is currently paused."); _claimTeamAll(_player); } View Function function getUsersArray() public view returns(address[] memory _usersArray){ _usersArray = userStorage.getUsersArray(); } function getUserCount() public view returns(uint256 _userCount){ address[] memory _usersArray = userStorage.getUsersArray(); return _usersArray.length; } function getSingleClaimed() public view returns(uint256 _singleClaimed){ return _getSingleClaimed(); } function getSingleUnClaim() public view returns(uint256 _singleUnClaim){ return _getSingleUnClaim(); } function getTeamClaimed() public view returns(uint256 _teamClaimed){ return _getTeamClaimed(); } function getTeamUnClaim() public view returns(uint256 _teamUnClaim){ return _getTeamUnClaim(); } }
5,691,735
[ 1, 22903, 23408, 868, 70, 14245, 934, 911, 17699, 429, 13456, 10819, 1177, 374, 18, 22, 934, 6159, 2845, 603, 2051, 342, 3981, 4189, 1267, 434, 326, 8828, 18, 18381, 1674, 1267, 434, 326, 8828, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 27435, 23408, 426, 70, 14245, 510, 911, 57, 22, 353, 15684, 3572, 25121, 16, 10188, 6934, 16, 868, 8230, 12514, 16709, 16, 20064, 510, 911, 5002, 95, 203, 565, 1758, 3238, 3410, 31, 203, 565, 1426, 1071, 31357, 510, 911, 31, 203, 565, 1426, 1071, 31357, 9762, 31, 203, 203, 10792, 11417, 397, 12562, 4058, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 4033, 31, 203, 565, 3885, 12, 45, 654, 39, 2499, 2539, 389, 41, 1460, 1345, 16, 467, 654, 39, 27, 5340, 389, 50, 4464, 2316, 16, 423, 8047, 17631, 1060, 12003, 389, 17631, 1060, 12003, 16, 423, 8047, 1299, 1318, 389, 1355, 3245, 16, 423, 8047, 14571, 323, 3245, 389, 3994, 3245, 16, 2254, 5034, 389, 266, 2913, 2173, 13433, 16, 2254, 5034, 389, 266, 2913, 2173, 13433, 1676, 16, 1758, 389, 8443, 13, 12562, 288, 203, 3639, 3410, 273, 389, 8443, 31, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 8443, 1769, 203, 3639, 6118, 28353, 1345, 273, 389, 41, 1460, 1345, 31, 203, 3639, 312, 362, 83, 1345, 273, 389, 50, 4464, 2316, 31, 203, 3639, 19890, 12003, 273, 389, 17631, 1060, 12003, 31, 203, 3639, 729, 3245, 273, 389, 1355, 3245, 31, 203, 3639, 7324, 3245, 273, 389, 3994, 3245, 31, 203, 3639, 19890, 2173, 13433, 273, 389, 266, 2913, 2173, 13433, 31, 203, 3639, 19890, 2173, 13433, 1676, 273, 389, 266, 2913, 2173, 13433, 1676, 31, 203, 3639, 31357, 510, 911, 273, 629, 31, 203, 3639, 31357, 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,481,013
[ 1, 145, 245, 145, 127, 146, 228, 145, 123, 145, 121, 225, 163, 227, 247, 225, 146, 227, 145, 113, 146, 228, 145, 128, 146, 227, 145, 127, 146, 228, 146, 229, 146, 227, 145, 113, 145, 126, 146, 244, 145, 126, 145, 126, 146, 238, 145, 118, 225, 145, 115, 225, 146, 227, 145, 113, 146, 228, 146, 229, 145, 121, 146, 229, 145, 118, 145, 124, 146, 239, 145, 126, 145, 127, 145, 125, 225, 145, 121, 225, 145, 119, 145, 121, 145, 115, 145, 127, 146, 229, 145, 126, 145, 127, 145, 125, 225, 145, 125, 145, 121, 146, 227, 145, 118, 225, 146, 228, 145, 124, 145, 127, 145, 119, 145, 126, 146, 238, 145, 118, 225, 146, 240, 146, 231, 145, 121, 146, 227, 146, 238, 225, 145, 115, 146, 238, 146, 228, 146, 235, 145, 121, 146, 232, 225, 145, 119, 145, 121, 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, 436, 407, 67, 502, 2038, 30, 145, 259, 145, 243, 145, 99, 145, 258, 145, 259, 145, 257, 145, 99, 145, 100, 145, 259, 145, 243, 145, 256, 145, 251, 145, 100, 145, 110, 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 ]
//SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @dev A gas optimized uintX[] implementation. The bitLength param determines the size * of the stored value. This can be a min of 1 and a maximum of 256. * * The array saves gas by avoiding bounds checks and tightly packing uintX elements. * The recommended use for this library is to derive from it a ArrayLibUintX library specific * to a hard-coded bitLength and then use that library within contracts. * * The storage layout conforms to the Solidity standard as described at * https://docs.soliditylang.org/en/latest/internals/layout_in_storage.html * * Error Codes (to save on gas costs): * - 1: Out of bounds * - 2: Invalid arguments * */ library ArrayLibUInt { /** * @dev Get length of the array * @param slot storage slot * @return length * * This function is here as a helper to avoid inline assembly (though less efficient). * It also helps to show how the arrays' length is stored in its designated slot. */ function len(bytes32 slot) internal view returns (uint256 length) { assembly { length := sload(slot) } } /***** Raw Storage Ops ******/ /** * @dev Get full storage slot at slotIndex * @param slot storage slot * @param slotIdx slot index * @return val * */ function _getSlotData(bytes32 slot, uint256 slotIdx) internal view returns (uint256 val) { assembly { mstore(0x0, slot) let p := keccak256(0x0, 0x20) //array[0] storage let idx := add(p, slotIdx) //array[idx] storage val := sload(idx) //load cur value } } /** * @dev Set full storage slot at slotIndex * @param slot storage slot * @param slotIdx slot index * @param val value * */ function _setSlotData( bytes32 slot, uint256 slotIdx, uint256 val ) internal { assembly { mstore(0x0, slot) let p := keccak256(0x0, 0x20) //array[0] storage let idx := add(p, slotIdx) //array[idx] storage sstore(idx, val) //load cur value } } /** * @dev Parse slot data at index to correct bit length * @param bitLength uint bit length * @param slotData raw slot data * @param subIdx indexed position of value in slot * @return val * */ function _getSlotDataValueAt( uint8 bitLength, uint256 slotData, uint256 subIdx ) internal pure returns (uint256 val) { uint256 slotPerStorage = 256 / bitLength; uint256 bitMask = ~(uint256(-1) << bitLength); // 000...FFFF uint256 bitShift = (slotPerStorage - 1 - subIdx) * bitLength; val = slotData >> bitShift; val = val & bitMask; } /** * @dev Encode value into the raw slot data * @param bitLength uint bit length * @param slotData raw slot data * @param subIdx indexed position of value in slot * @param val value * @return newSlotData * */ function _setSlotDataValueAt( uint8 bitLength, uint256 slotData, uint256 subIdx, uint256 val ) internal pure returns (uint256 newSlotData) { uint256 slotPerStorage = 256 / bitLength; uint256 bitMask = ~(uint256(-1) << bitLength); // 000...FFFF uint256 bitShift = (slotPerStorage - 1 - subIdx) * bitLength; val = val & bitMask; val = val << bitShift; uint256 slotBitmask = ~(bitMask << bitShift); newSlotData = (slotData & slotBitmask) | val; } /***** Array-Indexed Ops ******/ /** * @dev Get item at array[i] * @param bitLength uint bit length * @param slot storage slot * @param i index * @return val * * The array storage layout is divided in slots starting at keccak(slot). * Storage slots can store up to 256/bitLength items since one slot is 256 bits. * The get() cleans up the higher-order bits for you ensuring safety when converting. * See https://solidity.readthedocs.io/en/v0.7.0/internals/variable_cleanup.html */ function get( uint8 bitLength, bytes32 slot, uint256 i ) internal view returns (uint256 val) { uint256 slotPerStorage = 256 / bitLength; uint256 bitMask = ~(uint256(-1) << bitLength); // 000...FFFF assembly { mstore(0x0, slot) let p := keccak256(0x0, 0x20) //array[0] storage let idx := add(p, div(i, slotPerStorage)) //array[idx] storage let start := mul(sub(sub(slotPerStorage, 1), mod(i, slotPerStorage)), bitLength) //start pos let storedVal := sload(idx) //load cur value val := shr(start, storedVal) //Clean bits here } val = val & bitMask; } /** * @dev get() with bounds check * @param bitLength uint bit length * @param slot storage slot * @param i index * @return val */ function getSAFE( uint8 bitLength, bytes32 slot, uint256 i ) internal view returns (uint256 val) { uint256 length; assembly { length := sload(slot) } require(i < length, '1'); return get(bitLength, slot, i); } /** * @dev Set array[i] = val * @param bitLength uint bit length * @param slot storage slot * @param i index * @param val value */ function set( uint8 bitLength, bytes32 slot, uint256 i, uint256 val ) internal { uint256 slotPerStorage = 256 / bitLength; uint256 bitMask = ~(uint256(-1) << bitLength); // 000...FFFF val = val & bitMask; assembly { mstore(0x0, slot) let p := keccak256(0x0, 0x20) //array[0] storage let idx := add(p, div(i, slotPerStorage)) //array[idx] storage let start := mul(sub(sub(slotPerStorage, 1), mod(i, slotPerStorage)), bitLength) //start pos let storedVal := sload(idx) //load cur value let newVal := shl(start, val) //shift left logical to start pos let bitmask := not(shl(start, bitMask)) let newStoredVal := or(and(storedVal, bitmask), newVal) //clears old value and inserts new sstore(idx, newStoredVal) } } /** * @dev set() with bounds check * @param bitLength uint bit length * @param slot storage slot * @param i index * @param val value */ function setSAFE( uint8 bitLength, bytes32 slot, uint256 i, uint256 val ) internal { uint256 length; assembly { length := sload(slot) } require(i < length, '1'); set(bitLength, slot, i, val); } /** * @dev Append val to the end of the array, increasing its length. * @param bitLength uint bit length * @param slot storage slot * @param val value */ function push( uint8 bitLength, bytes32 slot, uint256 val ) internal { uint256 slotPerStorage = 256 / bitLength; uint256 bitMask = ~(uint256(-1) << bitLength); // 000...FFFF val = val & bitMask; assembly { mstore(0x0, slot) let p := keccak256(0x0, 0x20) //array[0] storage let length := sload(slot) //array length let idx := add(p, div(length, slotPerStorage)) //array[idx] storage let start := mul(sub(sub(slotPerStorage, 1), mod(length, slotPerStorage)), bitLength) //start pos let storedVal := sload(idx) //load cur value let newVal := shl(start, val) //shift left logical to start pos let bitmask := not(shl(start, bitMask)) let newStoredVal := or(and(storedVal, bitmask), newVal) //clears old value and inserts new sstore(idx, newStoredVal) sstore(slot, add(length, 1)) //increase length } } /** * @dev Pop end val of the array, decreasing its length. * @param bitLength uint bit length * @param slot storage slot */ function pop(uint8 bitLength, bytes32 slot) internal { uint256 slotPerStorage = 256 / bitLength; uint256 bitMask = ~(uint256(-1) << bitLength); // 000...FFFF uint256 length; assembly { length := sload(slot) } uint256 remainder = length % slotPerStorage; if (remainder == 1) { //pop slot to get gas refund uint256 quotient = length / slotPerStorage; assembly { mstore(0x0, slot) let p := keccak256(0x0, 0x20) //array[0] storage let idx := add(p, quotient) sstore(idx, 0) //clear storage } } assembly { sstore(slot, sub(length, 1)) //decrease length } } /** * @dev Swap two values at i, j. * @param bitLength uint bit length * @param slot storage slot * @param i index * @param j subindex * * There is potential for optimizing how same slot items are swapped. */ function swap( uint8 bitLength, bytes32 slot, uint256 i, uint256 j ) internal { uint256 slotPerStorage = 256 / bitLength; uint256 slotI = i / slotPerStorage; uint256 slotJ = j / slotPerStorage; if (slotI == slotJ) { uint256 subIdxI = i % slotPerStorage; uint256 subIdxJ = j % slotPerStorage; //Same storage slot, swap using bit operations uint256 slotData = _getSlotData(slot, slotI); //SLOAD uint256 a = _getSlotDataValueAt(bitLength, slotData, subIdxI); uint256 b = _getSlotDataValueAt(bitLength, slotData, subIdxJ); slotData = _setSlotDataValueAt(bitLength, slotData, subIdxI, b); slotData = _setSlotDataValueAt(bitLength, slotData, subIdxJ, a); _setSlotData(slot, slotI, slotData); //SSTORE } else { //Naive implementation uint256 a = get(bitLength, slot, i); uint256 b = get(bitLength, slot, j); set(bitLength, slot, i, b); set(bitLength, slot, j, a); } } /** * @dev swap() with bounds check * @param bitLength uint bit length * @param slot storage slot * @param i index * @param j subindex */ function swapSAFE( uint8 bitLength, bytes32 slot, uint256 i, uint256 j ) internal { uint256 length; assembly { length := sload(slot) } require(i < length, '1'); require(j < length, '1'); swap(bitLength, slot, i, j); } /***** Batched Ops ******/ /** * @dev Get a batch of items. Optimized to minimize SLOADs. * @param bitLength uint bit lengthh * @param slot storage slot * @param iArray index array. Assumes sorted for purpose of SLOAD optimization though still works if unsorted. * @return valList * */ function getBatch( uint8 bitLength, bytes32 slot, uint256[] memory iArray ) internal view returns (uint256[] memory valList) { valList = new uint256[](iArray.length); uint256 slotPerStorage = 256 / bitLength; uint256 slotPrev = iArray[0] / slotPerStorage; uint256 slotDataPrev = _getSlotData(slot, slotPrev); //SLOAD uint256 subIdxInit = iArray[0] % slotPerStorage; valList[0] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdxInit); for (uint256 i = 1; i < iArray.length; i++) { uint256 slotCurr = iArray[i] / slotPerStorage; uint256 subIdx = iArray[i] % slotPerStorage; if (slotCurr == slotPrev) { //Use cached slot data valList[i] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdx); } else { //New storage slot data slotPrev = slotCurr; slotDataPrev = _getSlotData(slot, slotPrev); //SLOAD valList[i] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdx); } } } /** * @dev Set a batch of values in the array. * @param bitLength uint bit length * @param slot storage slot * @param iArray index array. Assumes sorted for purpose of SLOAD optimization though still works if unsorted. * @param valArray value array * */ function setBatch( uint8 bitLength, bytes32 slot, uint256[] memory iArray, uint256[] memory valArray ) internal { require(iArray.length == valArray.length, '2'); uint256 slotPerStorage = 256 / bitLength; uint256 slotPrev = iArray[0] / slotPerStorage; uint256 slotDataPrev = _getSlotData(slot, slotPrev); //SLOAD uint256 subIdxInit = iArray[0] % slotPerStorage; slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); for (uint256 i = 1; i < iArray.length; i++) { uint256 slotCurr = iArray[i] / slotPerStorage; uint256 subIdx = iArray[i] % slotPerStorage; if (slotCurr == slotPrev) { //Set cached slot data slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); } else { //Write new data _setSlotData(slot, slotPrev, slotDataPrev); //STORE //New storage slot data slotPrev = slotCurr; slotDataPrev = _getSlotData(slot, slotPrev); //SLOAD slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); } } //Write new data _setSlotData(slot, slotPrev, slotDataPrev); //STORE } /** * @dev Append a batch of values to the end of the array, increasing its length. * @param bitLength uint bit length * @param slot storage slot * @param valArray value array * */ function pushBatch( uint8 bitLength, bytes32 slot, uint256[] memory valArray ) internal { //Increment length uint256 valArrayLength = valArray.length; uint256 length; assembly { length := sload(slot) //array length sstore(slot, add(length, valArrayLength)) //increase length } //Fill last slot uint256 slotPerStorage = 256 / bitLength; uint256 slotPrev = length / slotPerStorage; //last slot uint256 slotDataPrev; uint256 subIdxInit = length % slotPerStorage; if (subIdxInit != 0) { slotDataPrev = _getSlotData(slot, slotPrev); //SLOAD slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); } else { //New slot slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdxInit, valArray[0]); } for (uint256 i = 1; i < valArray.length; i++) { uint256 subIdx = (length + i) % slotPerStorage; if (subIdx != 0) { //Existing storage slot //Set cached slot data slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); } else { //New storage slot //Write new data _setSlotData(slot, slotPrev, slotDataPrev); //STORE //New storage slot data slotPrev += 1; slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdx, valArray[i]); } } //Write new data _setSlotData(slot, slotPrev, slotDataPrev); //STORE } /** * @dev Pop a batch of values from the array, decreasing its length. * @param bitLength uint bit length * @param slot storage slot * @param n number of times to pop * */ function popBatch( uint8 bitLength, bytes32 slot, uint256 n ) internal { //Decrement length uint256 length; assembly { length := sload(slot) //SLOAD sstore(slot, sub(length, n)) //decrease length } require(n <= length, '1'); //Pop last slot uint256 slotPerStorage = 256 / bitLength; uint256 storageLast = length / slotPerStorage; //last storage slot uint256 subIdxInit = length % slotPerStorage; uint256 storageClear = n / slotPerStorage; uint256 storageClearRemainder = n % slotPerStorage; if (storageClearRemainder == subIdxInit) { storageClear += 1; } for (uint256 i = 0; i < storageClear; i++) { //Pop storage slot _setSlotData(slot, storageLast - i, 0); //STORE } } }
* @dev A gas optimized uintX[] implementation. The bitLength param determines the size of the stored value. This can be a min of 1 and a maximum of 256. The array saves gas by avoiding bounds checks and tightly packing uintX elements. The recommended use for this library is to derive from it a ArrayLibUintX library specific to a hard-coded bitLength and then use that library within contracts. The storage layout conforms to the Solidity standard as described at Error Codes (to save on gas costs): - 1: Out of bounds - 2: Invalid arguments/
library ArrayLibUInt { pragma solidity >=0.6.0; function len(bytes32 slot) internal view returns (uint256 length) { assembly { length := sload(slot) } } function len(bytes32 slot) internal view returns (uint256 length) { assembly { length := sload(slot) } } function _getSlotData(bytes32 slot, uint256 slotIdx) internal view returns (uint256 val) { assembly { mstore(0x0, slot) } } function _getSlotData(bytes32 slot, uint256 slotIdx) internal view returns (uint256 val) { assembly { mstore(0x0, slot) } } function _setSlotData( bytes32 slot, uint256 slotIdx, uint256 val ) internal { assembly { mstore(0x0, slot) } } function _setSlotData( bytes32 slot, uint256 slotIdx, uint256 val ) internal { assembly { mstore(0x0, slot) } } function _getSlotDataValueAt( uint8 bitLength, uint256 slotData, uint256 subIdx ) internal pure returns (uint256 val) { uint256 slotPerStorage = 256 / bitLength; uint256 bitShift = (slotPerStorage - 1 - subIdx) * bitLength; val = slotData >> bitShift; val = val & bitMask; } function _setSlotDataValueAt( uint8 bitLength, uint256 slotData, uint256 subIdx, uint256 val ) internal pure returns (uint256 newSlotData) { uint256 slotPerStorage = 256 / bitLength; uint256 bitShift = (slotPerStorage - 1 - subIdx) * bitLength; val = val & bitMask; val = val << bitShift; uint256 slotBitmask = ~(bitMask << bitShift); newSlotData = (slotData & slotBitmask) | val; } function get( uint8 bitLength, bytes32 slot, uint256 i ) internal view returns (uint256 val) { uint256 slotPerStorage = 256 / bitLength; assembly { mstore(0x0, slot) } val = val & bitMask; } function get( uint8 bitLength, bytes32 slot, uint256 i ) internal view returns (uint256 val) { uint256 slotPerStorage = 256 / bitLength; assembly { mstore(0x0, slot) } val = val & bitMask; } function getSAFE( uint8 bitLength, bytes32 slot, uint256 i ) internal view returns (uint256 val) { uint256 length; assembly { length := sload(slot) } require(i < length, '1'); return get(bitLength, slot, i); } function getSAFE( uint8 bitLength, bytes32 slot, uint256 i ) internal view returns (uint256 val) { uint256 length; assembly { length := sload(slot) } require(i < length, '1'); return get(bitLength, slot, i); } function set( uint8 bitLength, bytes32 slot, uint256 i, uint256 val ) internal { uint256 slotPerStorage = 256 / bitLength; val = val & bitMask; assembly { mstore(0x0, slot) let bitmask := not(shl(start, bitMask)) sstore(idx, newStoredVal) } } function set( uint8 bitLength, bytes32 slot, uint256 i, uint256 val ) internal { uint256 slotPerStorage = 256 / bitLength; val = val & bitMask; assembly { mstore(0x0, slot) let bitmask := not(shl(start, bitMask)) sstore(idx, newStoredVal) } } function setSAFE( uint8 bitLength, bytes32 slot, uint256 i, uint256 val ) internal { uint256 length; assembly { length := sload(slot) } require(i < length, '1'); set(bitLength, slot, i, val); } function setSAFE( uint8 bitLength, bytes32 slot, uint256 i, uint256 val ) internal { uint256 length; assembly { length := sload(slot) } require(i < length, '1'); set(bitLength, slot, i, val); } function push( uint8 bitLength, bytes32 slot, uint256 val ) internal { uint256 slotPerStorage = 256 / bitLength; val = val & bitMask; assembly { mstore(0x0, slot) let bitmask := not(shl(start, bitMask)) sstore(idx, newStoredVal) } } function push( uint8 bitLength, bytes32 slot, uint256 val ) internal { uint256 slotPerStorage = 256 / bitLength; val = val & bitMask; assembly { mstore(0x0, slot) let bitmask := not(shl(start, bitMask)) sstore(idx, newStoredVal) } } function pop(uint8 bitLength, bytes32 slot) internal { uint256 slotPerStorage = 256 / bitLength; uint256 length; assembly { length := sload(slot) } uint256 remainder = length % slotPerStorage; if (remainder == 1) { uint256 quotient = length / slotPerStorage; assembly { mstore(0x0, slot) let idx := add(p, quotient) } } assembly { } } function pop(uint8 bitLength, bytes32 slot) internal { uint256 slotPerStorage = 256 / bitLength; uint256 length; assembly { length := sload(slot) } uint256 remainder = length % slotPerStorage; if (remainder == 1) { uint256 quotient = length / slotPerStorage; assembly { mstore(0x0, slot) let idx := add(p, quotient) } } assembly { } } function pop(uint8 bitLength, bytes32 slot) internal { uint256 slotPerStorage = 256 / bitLength; uint256 length; assembly { length := sload(slot) } uint256 remainder = length % slotPerStorage; if (remainder == 1) { uint256 quotient = length / slotPerStorage; assembly { mstore(0x0, slot) let idx := add(p, quotient) } } assembly { } } function pop(uint8 bitLength, bytes32 slot) internal { uint256 slotPerStorage = 256 / bitLength; uint256 length; assembly { length := sload(slot) } uint256 remainder = length % slotPerStorage; if (remainder == 1) { uint256 quotient = length / slotPerStorage; assembly { mstore(0x0, slot) let idx := add(p, quotient) } } assembly { } } function pop(uint8 bitLength, bytes32 slot) internal { uint256 slotPerStorage = 256 / bitLength; uint256 length; assembly { length := sload(slot) } uint256 remainder = length % slotPerStorage; if (remainder == 1) { uint256 quotient = length / slotPerStorage; assembly { mstore(0x0, slot) let idx := add(p, quotient) } } assembly { } } function swap( uint8 bitLength, bytes32 slot, uint256 i, uint256 j ) internal { uint256 slotPerStorage = 256 / bitLength; uint256 slotI = i / slotPerStorage; uint256 slotJ = j / slotPerStorage; if (slotI == slotJ) { uint256 subIdxI = i % slotPerStorage; uint256 subIdxJ = j % slotPerStorage; uint256 a = _getSlotDataValueAt(bitLength, slotData, subIdxI); uint256 b = _getSlotDataValueAt(bitLength, slotData, subIdxJ); slotData = _setSlotDataValueAt(bitLength, slotData, subIdxI, b); slotData = _setSlotDataValueAt(bitLength, slotData, subIdxJ, a); uint256 a = get(bitLength, slot, i); uint256 b = get(bitLength, slot, j); set(bitLength, slot, i, b); set(bitLength, slot, j, a); } } function swap( uint8 bitLength, bytes32 slot, uint256 i, uint256 j ) internal { uint256 slotPerStorage = 256 / bitLength; uint256 slotI = i / slotPerStorage; uint256 slotJ = j / slotPerStorage; if (slotI == slotJ) { uint256 subIdxI = i % slotPerStorage; uint256 subIdxJ = j % slotPerStorage; uint256 a = _getSlotDataValueAt(bitLength, slotData, subIdxI); uint256 b = _getSlotDataValueAt(bitLength, slotData, subIdxJ); slotData = _setSlotDataValueAt(bitLength, slotData, subIdxI, b); slotData = _setSlotDataValueAt(bitLength, slotData, subIdxJ, a); uint256 a = get(bitLength, slot, i); uint256 b = get(bitLength, slot, j); set(bitLength, slot, i, b); set(bitLength, slot, j, a); } } } else { function swapSAFE( uint8 bitLength, bytes32 slot, uint256 i, uint256 j ) internal { uint256 length; assembly { length := sload(slot) } require(i < length, '1'); require(j < length, '1'); swap(bitLength, slot, i, j); } function swapSAFE( uint8 bitLength, bytes32 slot, uint256 i, uint256 j ) internal { uint256 length; assembly { length := sload(slot) } require(i < length, '1'); require(j < length, '1'); swap(bitLength, slot, i, j); } function getBatch( uint8 bitLength, bytes32 slot, uint256[] memory iArray ) internal view returns (uint256[] memory valList) { valList = new uint256[](iArray.length); uint256 slotPerStorage = 256 / bitLength; uint256 slotPrev = iArray[0] / slotPerStorage; uint256 subIdxInit = iArray[0] % slotPerStorage; valList[0] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdxInit); for (uint256 i = 1; i < iArray.length; i++) { uint256 slotCurr = iArray[i] / slotPerStorage; uint256 subIdx = iArray[i] % slotPerStorage; if (slotCurr == slotPrev) { valList[i] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdx); slotPrev = slotCurr; valList[i] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdx); } } } function getBatch( uint8 bitLength, bytes32 slot, uint256[] memory iArray ) internal view returns (uint256[] memory valList) { valList = new uint256[](iArray.length); uint256 slotPerStorage = 256 / bitLength; uint256 slotPrev = iArray[0] / slotPerStorage; uint256 subIdxInit = iArray[0] % slotPerStorage; valList[0] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdxInit); for (uint256 i = 1; i < iArray.length; i++) { uint256 slotCurr = iArray[i] / slotPerStorage; uint256 subIdx = iArray[i] % slotPerStorage; if (slotCurr == slotPrev) { valList[i] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdx); slotPrev = slotCurr; valList[i] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdx); } } } function getBatch( uint8 bitLength, bytes32 slot, uint256[] memory iArray ) internal view returns (uint256[] memory valList) { valList = new uint256[](iArray.length); uint256 slotPerStorage = 256 / bitLength; uint256 slotPrev = iArray[0] / slotPerStorage; uint256 subIdxInit = iArray[0] % slotPerStorage; valList[0] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdxInit); for (uint256 i = 1; i < iArray.length; i++) { uint256 slotCurr = iArray[i] / slotPerStorage; uint256 subIdx = iArray[i] % slotPerStorage; if (slotCurr == slotPrev) { valList[i] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdx); slotPrev = slotCurr; valList[i] = _getSlotDataValueAt(bitLength, slotDataPrev, subIdx); } } } } else { function setBatch( uint8 bitLength, bytes32 slot, uint256[] memory iArray, uint256[] memory valArray ) internal { require(iArray.length == valArray.length, '2'); uint256 slotPerStorage = 256 / bitLength; uint256 slotPrev = iArray[0] / slotPerStorage; uint256 subIdxInit = iArray[0] % slotPerStorage; slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); for (uint256 i = 1; i < iArray.length; i++) { uint256 slotCurr = iArray[i] / slotPerStorage; uint256 subIdx = iArray[i] % slotPerStorage; if (slotCurr == slotPrev) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); slotPrev = slotCurr; slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); } } function setBatch( uint8 bitLength, bytes32 slot, uint256[] memory iArray, uint256[] memory valArray ) internal { require(iArray.length == valArray.length, '2'); uint256 slotPerStorage = 256 / bitLength; uint256 slotPrev = iArray[0] / slotPerStorage; uint256 subIdxInit = iArray[0] % slotPerStorage; slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); for (uint256 i = 1; i < iArray.length; i++) { uint256 slotCurr = iArray[i] / slotPerStorage; uint256 subIdx = iArray[i] % slotPerStorage; if (slotCurr == slotPrev) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); slotPrev = slotCurr; slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); } } function setBatch( uint8 bitLength, bytes32 slot, uint256[] memory iArray, uint256[] memory valArray ) internal { require(iArray.length == valArray.length, '2'); uint256 slotPerStorage = 256 / bitLength; uint256 slotPrev = iArray[0] / slotPerStorage; uint256 subIdxInit = iArray[0] % slotPerStorage; slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); for (uint256 i = 1; i < iArray.length; i++) { uint256 slotCurr = iArray[i] / slotPerStorage; uint256 subIdx = iArray[i] % slotPerStorage; if (slotCurr == slotPrev) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); slotPrev = slotCurr; slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); } } } else { } function pushBatch( uint8 bitLength, bytes32 slot, uint256[] memory valArray ) internal { uint256 valArrayLength = valArray.length; uint256 length; assembly { } uint256 slotDataPrev; uint256 subIdxInit = length % slotPerStorage; if (subIdxInit != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdxInit, valArray[0]); } for (uint256 i = 1; i < valArray.length; i++) { uint256 subIdx = (length + i) % slotPerStorage; if (subIdx != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); slotPrev += 1; slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdx, valArray[i]); } } function pushBatch( uint8 bitLength, bytes32 slot, uint256[] memory valArray ) internal { uint256 valArrayLength = valArray.length; uint256 length; assembly { } uint256 slotDataPrev; uint256 subIdxInit = length % slotPerStorage; if (subIdxInit != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdxInit, valArray[0]); } for (uint256 i = 1; i < valArray.length; i++) { uint256 subIdx = (length + i) % slotPerStorage; if (subIdx != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); slotPrev += 1; slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdx, valArray[i]); } } uint256 slotPerStorage = 256 / bitLength; function pushBatch( uint8 bitLength, bytes32 slot, uint256[] memory valArray ) internal { uint256 valArrayLength = valArray.length; uint256 length; assembly { } uint256 slotDataPrev; uint256 subIdxInit = length % slotPerStorage; if (subIdxInit != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdxInit, valArray[0]); } for (uint256 i = 1; i < valArray.length; i++) { uint256 subIdx = (length + i) % slotPerStorage; if (subIdx != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); slotPrev += 1; slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdx, valArray[i]); } } } else { function pushBatch( uint8 bitLength, bytes32 slot, uint256[] memory valArray ) internal { uint256 valArrayLength = valArray.length; uint256 length; assembly { } uint256 slotDataPrev; uint256 subIdxInit = length % slotPerStorage; if (subIdxInit != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdxInit, valArray[0]); } for (uint256 i = 1; i < valArray.length; i++) { uint256 subIdx = (length + i) % slotPerStorage; if (subIdx != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); slotPrev += 1; slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdx, valArray[i]); } } function pushBatch( uint8 bitLength, bytes32 slot, uint256[] memory valArray ) internal { uint256 valArrayLength = valArray.length; uint256 length; assembly { } uint256 slotDataPrev; uint256 subIdxInit = length % slotPerStorage; if (subIdxInit != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdxInit, valArray[0]); slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdxInit, valArray[0]); } for (uint256 i = 1; i < valArray.length; i++) { uint256 subIdx = (length + i) % slotPerStorage; if (subIdx != 0) { slotDataPrev = _setSlotDataValueAt(bitLength, slotDataPrev, subIdx, valArray[i]); slotPrev += 1; slotDataPrev = _setSlotDataValueAt(bitLength, 0, subIdx, valArray[i]); } } } else { } function popBatch( uint8 bitLength, bytes32 slot, uint256 n ) internal { uint256 length; assembly { } require(n <= length, '1'); uint256 subIdxInit = length % slotPerStorage; uint256 storageClear = n / slotPerStorage; uint256 storageClearRemainder = n % slotPerStorage; if (storageClearRemainder == subIdxInit) { storageClear += 1; } for (uint256 i = 0; i < storageClear; i++) { } } function popBatch( uint8 bitLength, bytes32 slot, uint256 n ) internal { uint256 length; assembly { } require(n <= length, '1'); uint256 subIdxInit = length % slotPerStorage; uint256 storageClear = n / slotPerStorage; uint256 storageClearRemainder = n % slotPerStorage; if (storageClearRemainder == subIdxInit) { storageClear += 1; } for (uint256 i = 0; i < storageClear; i++) { } } uint256 slotPerStorage = 256 / bitLength; function popBatch( uint8 bitLength, bytes32 slot, uint256 n ) internal { uint256 length; assembly { } require(n <= length, '1'); uint256 subIdxInit = length % slotPerStorage; uint256 storageClear = n / slotPerStorage; uint256 storageClearRemainder = n % slotPerStorage; if (storageClearRemainder == subIdxInit) { storageClear += 1; } for (uint256 i = 0; i < storageClear; i++) { } } function popBatch( uint8 bitLength, bytes32 slot, uint256 n ) internal { uint256 length; assembly { } require(n <= length, '1'); uint256 subIdxInit = length % slotPerStorage; uint256 storageClear = n / slotPerStorage; uint256 storageClearRemainder = n % slotPerStorage; if (storageClearRemainder == subIdxInit) { storageClear += 1; } for (uint256 i = 0; i < storageClear; i++) { } } }
12,540,072
[ 1, 37, 16189, 15411, 2254, 60, 8526, 4471, 18, 1021, 2831, 1782, 579, 12949, 326, 963, 434, 326, 4041, 460, 18, 1220, 848, 506, 279, 1131, 434, 404, 471, 279, 4207, 434, 8303, 18, 1021, 526, 14649, 16189, 635, 4543, 310, 4972, 4271, 471, 26066, 715, 2298, 310, 2254, 60, 2186, 18, 1021, 14553, 999, 364, 333, 5313, 353, 358, 14763, 628, 518, 279, 1510, 5664, 5487, 60, 5313, 2923, 358, 279, 7877, 17, 24808, 2831, 1782, 471, 1508, 999, 716, 5313, 3470, 20092, 18, 1021, 2502, 3511, 356, 9741, 358, 326, 348, 7953, 560, 4529, 487, 11893, 622, 1068, 8347, 261, 869, 1923, 603, 16189, 22793, 4672, 300, 404, 30, 2976, 434, 4972, 300, 576, 30, 1962, 1775, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 12083, 1510, 5664, 14342, 288, 203, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 20, 31, 203, 565, 445, 562, 12, 3890, 1578, 4694, 13, 2713, 1476, 1135, 261, 11890, 5034, 769, 13, 288, 203, 3639, 19931, 288, 203, 5411, 769, 519, 272, 945, 12, 14194, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 562, 12, 3890, 1578, 4694, 13, 2713, 1476, 1135, 261, 11890, 5034, 769, 13, 288, 203, 3639, 19931, 288, 203, 5411, 769, 519, 272, 945, 12, 14194, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 588, 8764, 751, 12, 3890, 1578, 4694, 16, 2254, 5034, 4694, 4223, 13, 2713, 1476, 1135, 261, 11890, 5034, 1244, 13, 288, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 20, 92, 20, 16, 4694, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 588, 8764, 751, 12, 3890, 1578, 4694, 16, 2254, 5034, 4694, 4223, 13, 2713, 1476, 1135, 261, 11890, 5034, 1244, 13, 288, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 20, 92, 20, 16, 4694, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 542, 8764, 751, 12, 203, 3639, 1731, 1578, 4694, 16, 203, 3639, 2254, 5034, 4694, 4223, 16, 203, 3639, 2254, 5034, 1244, 203, 565, 262, 2713, 288, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 20, 92, 20, 16, 4694, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 542, 8764, 751, 12, 203, 3639, 1731, 1578, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./ERC1155/ERC1155.sol"; import "./ERC1155/extensions/ERC1155Burnable.sol"; import "./ERC1155/utils/AccessControlEnumerable.sol"; import "./ERC1155/utils/Context.sol"; import "./IMinter.sol"; import "./IRegister.sol"; /** * @dev {Bondzier1155} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) assigned to bondzier market curve contracts * - a register function to help token discovery * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the default admin role, which will let it grant minter * roles to other accounts. */ contract Bondzier1155 is Context, AccessControlEnumerable, ERC1155Burnable, IMinter, IRegister { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE` to the account that * deploys the contract. */ constructor(string memory uri) ERC1155(uri) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Registers a new token type. */ function register(string memory uri, address c, uint128 nonce) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "BondzierERC1155: must have admin role to register"); grantRole(MINTER_ROLE, c); emit URI(uri, uint256 (nonce) << 128); } /** * @dev Creates `amount` new tokens for `to`, of token type `id`. * * See {ERC1155-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 id, uint256 amount, bytes memory data) external override virtual { require(hasRole(MINTER_ROLE, _msgSender()), "BondzierERC1155: must have minter role to mint"); _mint(to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}. */ function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) external virtual { require(hasRole(MINTER_ROLE, _msgSender()), "BondzierERC1155: must have minter role to mint"); _mintBatch(to, ids, amounts, data); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC1155) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } }
* @dev Registers a new token type./
function register(string memory uri, address c, uint128 nonce) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "BondzierERC1155: must have admin role to register"); grantRole(MINTER_ROLE, c); emit URI(uri, uint256 (nonce) << 128); }
14,072,605
[ 1, 10277, 279, 394, 1147, 618, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1744, 12, 1080, 3778, 2003, 16, 1758, 276, 16, 2254, 10392, 7448, 13, 3903, 3849, 288, 203, 3639, 2583, 12, 5332, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 1435, 3631, 315, 9807, 18377, 654, 39, 2499, 2539, 30, 1297, 1240, 3981, 2478, 358, 1744, 8863, 203, 540, 203, 3639, 7936, 2996, 12, 6236, 2560, 67, 16256, 16, 276, 1769, 203, 3639, 3626, 3699, 12, 1650, 16, 2254, 5034, 261, 12824, 13, 2296, 8038, 1769, 203, 565, 289, 7010, 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: MIT pragma solidity 0.6.12; import "./libraries/math/SafeMath.sol"; import "./libraries/token/IERC20.sol"; import "./interfaces/IXVIX.sol"; import "./interfaces/IFloor.sol"; contract XVIX is IERC20, IXVIX { using SafeMath for uint256; struct TransferConfig { bool active; uint256 senderBurnBasisPoints; uint256 senderFundBasisPoints; uint256 receiverBurnBasisPoints; uint256 receiverFundBasisPoints; } uint256 public constant BASIS_POINTS_DIVISOR = 10000; uint256 public constant MAX_FUND_BASIS_POINTS = 20; // 0.2% uint256 public constant MAX_BURN_BASIS_POINTS = 500; // 5% uint256 public constant MIN_REBASE_INTERVAL = 30 minutes; uint256 public constant MAX_REBASE_INTERVAL = 1 weeks; // cap the max intervals per rebase to avoid uint overflow errors uint256 public constant MAX_INTERVALS_PER_REBASE = 10; uint256 public constant MAX_REBASE_BASIS_POINTS = 500; // 5% // cap the normalDivisor to avoid uint overflow errors // the normalDivisor will be reached about 20 years after the first rebase uint256 public constant MAX_NORMAL_DIVISOR = 10**23; uint256 public constant SAFE_DIVISOR = 10**8; string public constant name = "XVIX"; string public constant symbol = "XVIX"; uint8 public constant decimals = 18; string public website = "https://xvix.finance/"; address public gov; address public minter; address public floor; address public distributor; address public fund; uint256 public _normalSupply; uint256 public _safeSupply; uint256 public override maxSupply; uint256 public normalDivisor = 10**8; uint256 public rebaseInterval = 1 hours; uint256 public rebaseBasisPoints = 2; // 0.02% uint256 public nextRebaseTime = 0; uint256 public defaultSenderBurnBasisPoints = 0; uint256 public defaultSenderFundBasisPoints = 0; uint256 public defaultReceiverBurnBasisPoints = 43; // 0.43% uint256 public defaultReceiverFundBasisPoints = 7; // 0.07% uint256 public govHandoverTime; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; // msg.sender => transfer config mapping (address => TransferConfig) public transferConfigs; // balances in safe addresses do not get rebased mapping (address => bool) public safes; event Toast(address indexed account, uint256 value, uint256 maxSupply); event FloorPrice(uint256 capital, uint256 supply); event Rebase(uint256 normalDivisor, uint256 nextRebaseTime); event GovChange(address gov); event CreateSafe(address safe, uint256 balance); event DestroySafe(address safe, uint256 balance); event RebaseConfigChange(uint256 rebaseInterval, uint256 rebaseBasisPoints); event DefaultTransferConfigChange( uint256 senderBasisPoints, uint256 senderFundBasisPoints, uint256 receiverBurnBasisPoints, uint256 receiverFundBasisPoints ); event SetTransferConfig( address indexed msgSender, uint256 senderBasisPoints, uint256 senderFundBasisPoints, uint256 receiverBurnBasisPoints, uint256 receiverFundBasisPoints ); event ClearTransferConfig(address indexed msgSender); modifier onlyGov() { require(msg.sender == gov, "XVIX: forbidden"); _; } // the govHandoverTime should be set to a time after XLGE participants can // withdraw their funds modifier onlyAfterHandover() { require(block.timestamp > govHandoverTime, "XVIX: handover time has not passed"); _; } modifier enforceMaxSupply() { _; require(totalSupply() <= maxSupply, "XVIX: max supply exceeded"); } constructor(uint256 _initialSupply, uint256 _maxSupply, uint256 _govHandoverTime) public { gov = msg.sender; govHandoverTime = _govHandoverTime; maxSupply = _maxSupply; _mint(msg.sender, _initialSupply); _setNextRebaseTime(); } function setGov(address _gov) public override onlyGov { gov = _gov; emit GovChange(_gov); } function setWebsite(string memory _website) public onlyGov { website = _website; } function setMinter(address _minter) public onlyGov { require(minter == address(0), "XVIX: minter already set"); minter = _minter; } function setFloor(address _floor) public onlyGov { require(floor == address(0), "XVIX: floor already set"); floor = _floor; } function setDistributor(address _distributor) public onlyGov { require(distributor == address(0), "XVIX: distributor already set"); distributor = _distributor; } function setFund(address _fund) public override onlyGov { fund = _fund; } function createSafe(address _account) public override onlyGov enforceMaxSupply { require(!safes[_account], "XVIX: account is already a safe"); safes[_account] = true; uint256 balance = balances[_account]; _normalSupply = _normalSupply.sub(balance); uint256 safeBalance = balance.mul(SAFE_DIVISOR).div(normalDivisor); balances[_account] = safeBalance; _safeSupply = _safeSupply.add(safeBalance); emit CreateSafe(_account, balanceOf(_account)); } // onlyAfterHandover guards against a possible gov attack vector // since XLGE participants have their funds locked for one month, // it is possible for gov to create a safe address and keep // XVIX tokens there while destroying all other safes // this would raise the value of the tokens kept in the safe address // // with the onlyAfterHandover modifier this attack can only be attempted // after XLGE participants are able to withdraw their funds // this would make it difficult for the attack to be profitable function destroySafe(address _account) public onlyGov onlyAfterHandover enforceMaxSupply { require(safes[_account], "XVIX: account is not a safe"); safes[_account] = false; uint256 balance = balances[_account]; _safeSupply = _safeSupply.sub(balance); uint256 normalBalance = balance.mul(normalDivisor).div(SAFE_DIVISOR); balances[_account] = normalBalance; _normalSupply = _normalSupply.add(normalBalance); emit DestroySafe(_account, balanceOf(_account)); } function setRebaseConfig( uint256 _rebaseInterval, uint256 _rebaseBasisPoints ) public onlyGov onlyAfterHandover { require(_rebaseInterval >= MIN_REBASE_INTERVAL, "XVIX: rebaseInterval below limit"); require(_rebaseInterval <= MAX_REBASE_INTERVAL, "XVIX: rebaseInterval exceeds limit"); require(_rebaseBasisPoints <= MAX_REBASE_BASIS_POINTS, "XVIX: rebaseBasisPoints exceeds limit"); rebaseInterval = _rebaseInterval; rebaseBasisPoints = _rebaseBasisPoints; emit RebaseConfigChange(_rebaseInterval, _rebaseBasisPoints); } function setDefaultTransferConfig( uint256 _senderBurnBasisPoints, uint256 _senderFundBasisPoints, uint256 _receiverBurnBasisPoints, uint256 _receiverFundBasisPoints ) public onlyGov onlyAfterHandover { _validateTransferConfig( _senderBurnBasisPoints, _senderFundBasisPoints, _receiverBurnBasisPoints, _receiverFundBasisPoints ); defaultSenderBurnBasisPoints = _senderBurnBasisPoints; defaultSenderFundBasisPoints = _senderFundBasisPoints; defaultReceiverBurnBasisPoints = _receiverBurnBasisPoints; defaultReceiverFundBasisPoints = _receiverFundBasisPoints; emit DefaultTransferConfigChange( _senderBurnBasisPoints, _senderFundBasisPoints, _receiverBurnBasisPoints, _receiverFundBasisPoints ); } function setTransferConfig( address _msgSender, uint256 _senderBurnBasisPoints, uint256 _senderFundBasisPoints, uint256 _receiverBurnBasisPoints, uint256 _receiverFundBasisPoints ) public override onlyGov { require(_msgSender != address(0), "XVIX: cannot set zero address"); _validateTransferConfig( _senderBurnBasisPoints, _senderFundBasisPoints, _receiverBurnBasisPoints, _receiverFundBasisPoints ); transferConfigs[_msgSender] = TransferConfig( true, _senderBurnBasisPoints, _senderFundBasisPoints, _receiverBurnBasisPoints, _receiverFundBasisPoints ); emit SetTransferConfig( _msgSender, _senderBurnBasisPoints, _senderFundBasisPoints, _receiverBurnBasisPoints, _receiverFundBasisPoints ); } function clearTransferConfig(address _msgSender) public onlyGov onlyAfterHandover { delete transferConfigs[_msgSender]; emit ClearTransferConfig(_msgSender); } function rebase() public override returns (bool) { if (block.timestamp < nextRebaseTime) { return false; } // calculate the number of intervals that have passed uint256 timeDiff = block.timestamp.sub(nextRebaseTime); uint256 intervals = timeDiff.div(rebaseInterval).add(1); // the multiplier is calculated as (~10000)^intervals // the max value of intervals is capped at 10 to avoid uint overflow errors // 2^256 has 77 digits // 10,000^10 has 40 // MAX_NORMAL_DIVISOR has 23 digits if (intervals > MAX_INTERVALS_PER_REBASE) { intervals = MAX_INTERVALS_PER_REBASE; } _setNextRebaseTime(); if (rebaseBasisPoints == 0) { return false; } uint256 multiplier = BASIS_POINTS_DIVISOR.add(rebaseBasisPoints) ** intervals; uint256 divider = BASIS_POINTS_DIVISOR ** intervals; uint256 nextDivisor = normalDivisor.mul(multiplier).div(divider); if (nextDivisor > MAX_NORMAL_DIVISOR) { return false; } normalDivisor = nextDivisor; emit Rebase(normalDivisor, nextRebaseTime); return true; } function mint(address _account, uint256 _amount) public override returns (bool) { require(msg.sender == minter, "XVIX: forbidden"); _mint(_account, _amount); return true; } // permanently remove tokens from circulation by reducing maxSupply function toast(uint256 _amount) public override returns (bool) { require(msg.sender == distributor, "XVIX: forbidden"); if (_amount == 0) { return false; } _burn(msg.sender, _amount); maxSupply = maxSupply.sub(_amount); emit Toast(msg.sender, _amount, maxSupply); return true; } function burn(address _account, uint256 _amount) public override returns (bool) { require(msg.sender == floor, "XVIX: forbidden"); _burn(_account, _amount); return true; } function balanceOf(address _account) public view override returns (uint256) { if (safes[_account]) { return balances[_account].div(SAFE_DIVISOR); } return balances[_account].div(normalDivisor); } function transfer(address _recipient, uint256 _amount) public override returns (bool) { _transfer(msg.sender, _recipient, _amount); rebase(); return true; } function allowance(address _owner, address _spender) public view override returns (uint256) { return allowances[_owner][_spender]; } function approve(address _spender, uint256 _amount) public override returns (bool) { _approve(msg.sender, _spender, _amount); return true; } function transferFrom(address _sender, address _recipient, uint256 _amount) public override returns (bool) { uint256 nextAllowance = allowances[_sender][msg.sender].sub(_amount, "XVIX: transfer amount exceeds allowance"); _approve(_sender, msg.sender, nextAllowance); _transfer(_sender, _recipient, _amount); rebase(); return true; } function normalSupply() public view returns (uint256) { return _normalSupply.div(normalDivisor); } function safeSupply() public view returns (uint256) { return _safeSupply.div(SAFE_DIVISOR); } function totalSupply() public view override returns (uint256) { return normalSupply().add(safeSupply()); } function _validateTransferConfig( uint256 _senderBurnBasisPoints, uint256 _senderFundBasisPoints, uint256 _receiverBurnBasisPoints, uint256 _receiverFundBasisPoints ) private pure { require(_senderBurnBasisPoints <= MAX_BURN_BASIS_POINTS, "XVIX: senderBurnBasisPoints exceeds limit"); require(_senderFundBasisPoints <= MAX_FUND_BASIS_POINTS, "XVIX: senderFundBasisPoints exceeds limit"); require(_receiverBurnBasisPoints <= MAX_BURN_BASIS_POINTS, "XVIX: receiverBurnBasisPoints exceeds limit"); require(_receiverFundBasisPoints <= MAX_FUND_BASIS_POINTS, "XVIX: receiverFundBasisPoints exceeds limit"); } function _setNextRebaseTime() private { uint256 roundedTime = block.timestamp.div(rebaseInterval).mul(rebaseInterval); nextRebaseTime = roundedTime.add(rebaseInterval); } function _transfer(address _sender, address _recipient, uint256 _amount) private { require(_sender != address(0), "XVIX: transfer from the zero address"); require(_recipient != address(0), "XVIX: transfer to the zero address"); (uint256 senderBurn, uint256 senderFund, uint256 receiverBurn, uint256 receiverFund) = _getTransferConfig(); // increase senderAmount based on senderBasisPoints uint256 senderAmount = _amount; uint256 senderBasisPoints = senderBurn.add(senderFund); if (senderBasisPoints > 0) { uint256 senderTax = _amount.mul(senderBasisPoints).div(BASIS_POINTS_DIVISOR); senderAmount = senderAmount.add(senderTax); } // decrease receiverAmount based on receiverBasisPoints uint256 receiverAmount = _amount; uint256 receiverBasisPoints = receiverBurn.add(receiverFund); if (receiverBasisPoints > 0) { uint256 receiverTax = _amount.mul(receiverBasisPoints).div(BASIS_POINTS_DIVISOR); receiverAmount = receiverAmount.sub(receiverTax); } _decreaseBalance(_sender, senderAmount); _increaseBalance(_recipient, receiverAmount); emit Transfer(_sender, _recipient, receiverAmount); // increase fund balance based on fundBasisPoints uint256 fundBasisPoints = senderFund.add(receiverFund); uint256 fundAmount = _amount.mul(fundBasisPoints).div(BASIS_POINTS_DIVISOR); if (fundAmount > 0) { _increaseBalance(fund, fundAmount); emit Transfer(_sender, fund, fundAmount); } // emit burn event uint256 burnAmount = senderAmount.sub(receiverAmount).sub(fundAmount); if (burnAmount > 0) { emit Transfer(_sender, address(0), burnAmount); } _emitFloorPrice(); } function _getTransferConfig() private view returns (uint256, uint256, uint256, uint256) { uint256 senderBurn = defaultSenderBurnBasisPoints; uint256 senderFund = defaultSenderFundBasisPoints; uint256 receiverBurn = defaultReceiverBurnBasisPoints; uint256 receiverFund = defaultReceiverFundBasisPoints; TransferConfig memory config = transferConfigs[msg.sender]; if (config.active) { senderBurn = config.senderBurnBasisPoints; senderFund = config.senderFundBasisPoints; receiverBurn = config.receiverBurnBasisPoints; receiverFund = config.receiverFundBasisPoints; } return (senderBurn, senderFund, receiverBurn, receiverFund); } function _approve(address _owner, address _spender, uint256 _amount) private { require(_owner != address(0), "XVIX: approve from the zero address"); require(_spender != address(0), "XVIX: approve to the zero address"); allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } function _mint(address _account, uint256 _amount) private { require(_account != address(0), "XVIX: mint to the zero address"); if (_amount == 0) { return; } _increaseBalance(_account, _amount); emit Transfer(address(0), _account, _amount); _emitFloorPrice(); } function _burn(address _account, uint256 _amount) private { require(_account != address(0), "XVIX: burn from the zero address"); if (_amount == 0) { return; } _decreaseBalance(_account, _amount); emit Transfer(_account, address(0), _amount); _emitFloorPrice(); } function _increaseBalance(address _account, uint256 _amount) private enforceMaxSupply { if (_amount == 0) { return; } if (safes[_account]) { uint256 safeAmount = _amount.mul(SAFE_DIVISOR); balances[_account] = balances[_account].add(safeAmount); _safeSupply = _safeSupply.add(safeAmount); return; } uint256 normalAmount = _amount.mul(normalDivisor); balances[_account] = balances[_account].add(normalAmount); _normalSupply = _normalSupply.add(normalAmount); } function _decreaseBalance(address _account, uint256 _amount) private { if (_amount == 0) { return; } if (safes[_account]) { uint256 safeAmount = _amount.mul(SAFE_DIVISOR); balances[_account] = balances[_account].sub(safeAmount, "XVIX: subtraction amount exceeds balance"); _safeSupply = _safeSupply.sub(safeAmount); return; } uint256 normalAmount = _amount.mul(normalDivisor); balances[_account] = balances[_account].sub(normalAmount, "XVIX: subtraction amount exceeds balance"); _normalSupply = _normalSupply.sub(normalAmount); } function _emitFloorPrice() private { if (_isContract(floor)) { emit FloorPrice(IFloor(floor).capital(), totalSupply()); } } function _isContract(address account) private view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } }
increase senderAmount based on senderBasisPoints
function _transfer(address _sender, address _recipient, uint256 _amount) private { require(_sender != address(0), "XVIX: transfer from the zero address"); require(_recipient != address(0), "XVIX: transfer to the zero address"); (uint256 senderBurn, uint256 senderFund, uint256 receiverBurn, uint256 receiverFund) = _getTransferConfig(); uint256 senderAmount = _amount; uint256 senderBasisPoints = senderBurn.add(senderFund); if (senderBasisPoints > 0) { uint256 senderTax = _amount.mul(senderBasisPoints).div(BASIS_POINTS_DIVISOR); senderAmount = senderAmount.add(senderTax); } uint256 receiverBasisPoints = receiverBurn.add(receiverFund); if (receiverBasisPoints > 0) { uint256 receiverTax = _amount.mul(receiverBasisPoints).div(BASIS_POINTS_DIVISOR); receiverAmount = receiverAmount.sub(receiverTax); } _decreaseBalance(_sender, senderAmount); _increaseBalance(_recipient, receiverAmount); emit Transfer(_sender, _recipient, receiverAmount); uint256 fundAmount = _amount.mul(fundBasisPoints).div(BASIS_POINTS_DIVISOR); if (fundAmount > 0) { _increaseBalance(fund, fundAmount); emit Transfer(_sender, fund, fundAmount); } if (burnAmount > 0) { emit Transfer(_sender, address(0), burnAmount); } _emitFloorPrice(); }
2,554,207
[ 1, 267, 11908, 5793, 6275, 2511, 603, 5793, 11494, 291, 5636, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 15330, 16, 1758, 389, 20367, 16, 2254, 5034, 389, 8949, 13, 3238, 288, 203, 3639, 2583, 24899, 15330, 480, 1758, 12, 20, 3631, 315, 60, 4136, 60, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 24899, 20367, 480, 1758, 12, 20, 3631, 315, 60, 4136, 60, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 261, 11890, 5034, 5793, 38, 321, 16, 203, 540, 2254, 5034, 5793, 42, 1074, 16, 203, 540, 2254, 5034, 5971, 38, 321, 16, 203, 540, 2254, 5034, 5971, 42, 1074, 13, 273, 389, 588, 5912, 809, 5621, 203, 203, 3639, 2254, 5034, 5793, 6275, 273, 389, 8949, 31, 203, 3639, 2254, 5034, 5793, 11494, 291, 5636, 273, 5793, 38, 321, 18, 1289, 12, 15330, 42, 1074, 1769, 203, 3639, 309, 261, 15330, 11494, 291, 5636, 405, 374, 13, 288, 203, 5411, 2254, 5034, 5793, 7731, 273, 389, 8949, 18, 16411, 12, 15330, 11494, 291, 5636, 2934, 2892, 12, 12536, 15664, 67, 8941, 55, 67, 2565, 26780, 916, 1769, 203, 5411, 5793, 6275, 273, 5793, 6275, 18, 1289, 12, 15330, 7731, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 5971, 11494, 291, 5636, 273, 5971, 38, 321, 18, 1289, 12, 24454, 42, 1074, 1769, 203, 3639, 309, 261, 24454, 11494, 291, 5636, 405, 374, 13, 288, 203, 5411, 2254, 5034, 5971, 7731, 273, 389, 8949, 18, 16411, 12, 24454, 11494, 291, 5636, 2934, 2892, 12, 12536, 15664, 67, 8941, 55, 67, 2565, 26780, 916, 1769, 203, 5411, 5971, 6275, 2 ]
./partial_match/1/0xA017D0dF097e1d6cCC91414b1d56F4aFCd297F59/sources/PLATINUM.sol
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() * 10 / 1000, "Swap amount cannot be higher than 1% total supply."); swapTokensAtAmount = newAmount; return true; }
2,874,739
[ 1, 3427, 326, 5224, 3844, 434, 2430, 358, 357, 80, 628, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1089, 12521, 5157, 861, 6275, 12, 11890, 5034, 394, 6275, 13, 3903, 1338, 5541, 1135, 261, 6430, 15329, 203, 3639, 2583, 12, 2704, 6275, 1545, 2078, 3088, 1283, 1435, 380, 404, 342, 25259, 16, 315, 12521, 3844, 2780, 506, 2612, 2353, 374, 18, 11664, 9, 2078, 14467, 1199, 1769, 203, 3639, 2583, 12, 2704, 6275, 1648, 2078, 3088, 1283, 1435, 380, 1728, 342, 4336, 16, 315, 12521, 3844, 2780, 506, 10478, 2353, 404, 9, 2078, 14467, 1199, 1769, 203, 3639, 7720, 5157, 861, 6275, 273, 394, 6275, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]